diff --git a/accessapproval/apiv1/access_approval_client.go b/accessapproval/apiv1/access_approval_client.go index df6e0c52dc89..564363156d66 100644 --- a/accessapproval/apiv1/access_approval_client.go +++ b/accessapproval/apiv1/access_approval_client.go @@ -48,7 +48,7 @@ type CallOptions struct { DeleteAccessApprovalSettings []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("accessapproval.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("accessapproval.mtls.googleapis.com:443"), @@ -102,27 +102,164 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Access Approval API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListApprovalRequests(context.Context, *accessapprovalpb.ListApprovalRequestsMessage, ...gax.CallOption) *ApprovalRequestIterator + GetApprovalRequest(context.Context, *accessapprovalpb.GetApprovalRequestMessage, ...gax.CallOption) (*accessapprovalpb.ApprovalRequest, error) + ApproveApprovalRequest(context.Context, *accessapprovalpb.ApproveApprovalRequestMessage, ...gax.CallOption) (*accessapprovalpb.ApprovalRequest, error) + DismissApprovalRequest(context.Context, *accessapprovalpb.DismissApprovalRequestMessage, ...gax.CallOption) (*accessapprovalpb.ApprovalRequest, error) + GetAccessApprovalSettings(context.Context, *accessapprovalpb.GetAccessApprovalSettingsMessage, ...gax.CallOption) (*accessapprovalpb.AccessApprovalSettings, error) + UpdateAccessApprovalSettings(context.Context, *accessapprovalpb.UpdateAccessApprovalSettingsMessage, ...gax.CallOption) (*accessapprovalpb.AccessApprovalSettings, error) + DeleteAccessApprovalSettings(context.Context, *accessapprovalpb.DeleteAccessApprovalSettingsMessage, ...gax.CallOption) error +} + // Client is a client for interacting with Access Approval API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// This API allows a customer to manage accesses to cloud resources by +// Google personnel. It defines the following resource model: +// +// The API has a collection of +// ApprovalRequest +// resources, named approvalRequests/{approval_request_id} +// +// The API has top-level settings per Project/Folder/Organization, named +// accessApprovalSettings +// +// The service also periodically emails a list of recipients, defined at the +// Project/Folder/Organization level in the accessApprovalSettings, when there +// is a pending ApprovalRequest for them to act on. The ApprovalRequests can +// also optionally be published to a Cloud Pub/Sub topic owned by the customer +// (for Beta, the Pub/Sub setup is managed manually). +// +// ApprovalRequests can be approved or dismissed. Google personel can only +// access the indicated resource or resources if the request is approved +// (subject to some exclusions: +// https://cloud.google.com/access-approval/docs/overview#exclusions (at https://cloud.google.com/access-approval/docs/overview#exclusions)). +// +// Note: Using Access Approval functionality will mean that Google may not be +// able to meet the SLAs for your chosen products, as any support response times +// may be dramatically increased. As such the SLAs do not apply to any service +// disruption to the extent impacted by Customer’s use of Access Approval. Do +// not enable Access Approval for projects where you may require high service +// availability and rapid response by Google Cloud Support. +// +// After a request is approved or dismissed, no further action may be taken on +// it. Requests with the requested_expiration in the past or with no activity +// for 14 days are considered dismissed. When an approval expires, the request +// is considered dismissed. +// +// If a request is not approved or dismissed, we call it pending. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListApprovalRequests lists approval requests associated with a project, folder, or organization. +// Approval requests can be filtered by state (pending, active, dismissed). +// The order is reverse chronological. +func (c *Client) ListApprovalRequests(ctx context.Context, req *accessapprovalpb.ListApprovalRequestsMessage, opts ...gax.CallOption) *ApprovalRequestIterator { + return c.internalClient.ListApprovalRequests(ctx, req, opts...) +} + +// GetApprovalRequest gets an approval request. Returns NOT_FOUND if the request does not exist. +func (c *Client) GetApprovalRequest(ctx context.Context, req *accessapprovalpb.GetApprovalRequestMessage, opts ...gax.CallOption) (*accessapprovalpb.ApprovalRequest, error) { + return c.internalClient.GetApprovalRequest(ctx, req, opts...) +} + +// ApproveApprovalRequest approves a request and returns the updated ApprovalRequest. +// +// Returns NOT_FOUND if the request does not exist. Returns +// FAILED_PRECONDITION if the request exists but is not in a pending state. +func (c *Client) ApproveApprovalRequest(ctx context.Context, req *accessapprovalpb.ApproveApprovalRequestMessage, opts ...gax.CallOption) (*accessapprovalpb.ApprovalRequest, error) { + return c.internalClient.ApproveApprovalRequest(ctx, req, opts...) +} + +// DismissApprovalRequest dismisses a request. Returns the updated ApprovalRequest. +// +// NOTE: This does not deny access to the resource if another request has been +// made and approved. It is equivalent in effect to ignoring the request +// altogether. +// +// Returns NOT_FOUND if the request does not exist. +// +// Returns FAILED_PRECONDITION if the request exists but is not in a pending +// state. +func (c *Client) DismissApprovalRequest(ctx context.Context, req *accessapprovalpb.DismissApprovalRequestMessage, opts ...gax.CallOption) (*accessapprovalpb.ApprovalRequest, error) { + return c.internalClient.DismissApprovalRequest(ctx, req, opts...) +} + +// GetAccessApprovalSettings gets the settings associated with a project, folder, or organization. +func (c *Client) GetAccessApprovalSettings(ctx context.Context, req *accessapprovalpb.GetAccessApprovalSettingsMessage, opts ...gax.CallOption) (*accessapprovalpb.AccessApprovalSettings, error) { + return c.internalClient.GetAccessApprovalSettings(ctx, req, opts...) +} + +// UpdateAccessApprovalSettings updates the settings associated with a project, folder, or organization. +// Settings to update are determined by the value of field_mask. +func (c *Client) UpdateAccessApprovalSettings(ctx context.Context, req *accessapprovalpb.UpdateAccessApprovalSettingsMessage, opts ...gax.CallOption) (*accessapprovalpb.AccessApprovalSettings, error) { + return c.internalClient.UpdateAccessApprovalSettings(ctx, req, opts...) +} + +// DeleteAccessApprovalSettings deletes the settings associated with a project, folder, or organization. +// This will have the effect of disabling Access Approval for the project, +// folder, or organization, but only if all ancestors also have Access +// Approval disabled. If Access Approval is enabled at a higher level of the +// hierarchy, then Access Approval will still be enabled at this level as +// the settings are inherited. +func (c *Client) DeleteAccessApprovalSettings(ctx context.Context, req *accessapprovalpb.DeleteAccessApprovalSettingsMessage, opts ...gax.CallOption) error { + return c.internalClient.DeleteAccessApprovalSettings(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Access Approval API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client accessapprovalpb.AccessApprovalClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new access approval client. +// NewClient creates a new access approval client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // This API allows a customer to manage accesses to cloud resources by // Google personnel. It defines the following resource model: @@ -159,8 +296,7 @@ type Client struct { // // If a request is not approved or dismissed, we call it pending. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -178,47 +314,47 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: accessapprovalpb.NewAccessApprovalClient(connPool), + client: accessapprovalpb.NewAccessApprovalClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListApprovalRequests lists approval requests associated with a project, folder, or organization. -// Approval requests can be filtered by state (pending, active, dismissed). -// The order is reverse chronological. -func (c *Client) ListApprovalRequests(ctx context.Context, req *accessapprovalpb.ListApprovalRequestsMessage, opts ...gax.CallOption) *ApprovalRequestIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ListApprovalRequests(ctx context.Context, req *accessapprovalpb.ListApprovalRequestsMessage, opts ...gax.CallOption) *ApprovalRequestIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListApprovalRequests[0:len(c.CallOptions.ListApprovalRequests):len(c.CallOptions.ListApprovalRequests)], opts...) + opts = append((*c.CallOptions).ListApprovalRequests[0:len((*c.CallOptions).ListApprovalRequests):len((*c.CallOptions).ListApprovalRequests)], opts...) it := &ApprovalRequestIterator{} req = proto.Clone(req).(*accessapprovalpb.ListApprovalRequestsMessage) it.InternalFetch = func(pageSize int, pageToken string) ([]*accessapprovalpb.ApprovalRequest, string, error) { @@ -255,8 +391,7 @@ func (c *Client) ListApprovalRequests(ctx context.Context, req *accessapprovalpb return it } -// GetApprovalRequest gets an approval request. Returns NOT_FOUND if the request does not exist. -func (c *Client) GetApprovalRequest(ctx context.Context, req *accessapprovalpb.GetApprovalRequestMessage, opts ...gax.CallOption) (*accessapprovalpb.ApprovalRequest, error) { +func (c *gRPCClient) GetApprovalRequest(ctx context.Context, req *accessapprovalpb.GetApprovalRequestMessage, opts ...gax.CallOption) (*accessapprovalpb.ApprovalRequest, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -264,7 +399,7 @@ func (c *Client) GetApprovalRequest(ctx context.Context, req *accessapprovalpb.G } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetApprovalRequest[0:len(c.CallOptions.GetApprovalRequest):len(c.CallOptions.GetApprovalRequest)], opts...) + opts = append((*c.CallOptions).GetApprovalRequest[0:len((*c.CallOptions).GetApprovalRequest):len((*c.CallOptions).GetApprovalRequest)], opts...) var resp *accessapprovalpb.ApprovalRequest err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -277,11 +412,7 @@ func (c *Client) GetApprovalRequest(ctx context.Context, req *accessapprovalpb.G return resp, nil } -// ApproveApprovalRequest approves a request and returns the updated ApprovalRequest. -// -// Returns NOT_FOUND if the request does not exist. Returns -// FAILED_PRECONDITION if the request exists but is not in a pending state. -func (c *Client) ApproveApprovalRequest(ctx context.Context, req *accessapprovalpb.ApproveApprovalRequestMessage, opts ...gax.CallOption) (*accessapprovalpb.ApprovalRequest, error) { +func (c *gRPCClient) ApproveApprovalRequest(ctx context.Context, req *accessapprovalpb.ApproveApprovalRequestMessage, opts ...gax.CallOption) (*accessapprovalpb.ApprovalRequest, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -289,7 +420,7 @@ func (c *Client) ApproveApprovalRequest(ctx context.Context, req *accessapproval } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ApproveApprovalRequest[0:len(c.CallOptions.ApproveApprovalRequest):len(c.CallOptions.ApproveApprovalRequest)], opts...) + opts = append((*c.CallOptions).ApproveApprovalRequest[0:len((*c.CallOptions).ApproveApprovalRequest):len((*c.CallOptions).ApproveApprovalRequest)], opts...) var resp *accessapprovalpb.ApprovalRequest err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -302,17 +433,7 @@ func (c *Client) ApproveApprovalRequest(ctx context.Context, req *accessapproval return resp, nil } -// DismissApprovalRequest dismisses a request. Returns the updated ApprovalRequest. -// -// NOTE: This does not deny access to the resource if another request has been -// made and approved. It is equivalent in effect to ignoring the request -// altogether. -// -// Returns NOT_FOUND if the request does not exist. -// -// Returns FAILED_PRECONDITION if the request exists but is not in a pending -// state. -func (c *Client) DismissApprovalRequest(ctx context.Context, req *accessapprovalpb.DismissApprovalRequestMessage, opts ...gax.CallOption) (*accessapprovalpb.ApprovalRequest, error) { +func (c *gRPCClient) DismissApprovalRequest(ctx context.Context, req *accessapprovalpb.DismissApprovalRequestMessage, opts ...gax.CallOption) (*accessapprovalpb.ApprovalRequest, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -320,7 +441,7 @@ func (c *Client) DismissApprovalRequest(ctx context.Context, req *accessapproval } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DismissApprovalRequest[0:len(c.CallOptions.DismissApprovalRequest):len(c.CallOptions.DismissApprovalRequest)], opts...) + opts = append((*c.CallOptions).DismissApprovalRequest[0:len((*c.CallOptions).DismissApprovalRequest):len((*c.CallOptions).DismissApprovalRequest)], opts...) var resp *accessapprovalpb.ApprovalRequest err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -333,8 +454,7 @@ func (c *Client) DismissApprovalRequest(ctx context.Context, req *accessapproval return resp, nil } -// GetAccessApprovalSettings gets the settings associated with a project, folder, or organization. -func (c *Client) GetAccessApprovalSettings(ctx context.Context, req *accessapprovalpb.GetAccessApprovalSettingsMessage, opts ...gax.CallOption) (*accessapprovalpb.AccessApprovalSettings, error) { +func (c *gRPCClient) GetAccessApprovalSettings(ctx context.Context, req *accessapprovalpb.GetAccessApprovalSettingsMessage, opts ...gax.CallOption) (*accessapprovalpb.AccessApprovalSettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -342,7 +462,7 @@ func (c *Client) GetAccessApprovalSettings(ctx context.Context, req *accessappro } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetAccessApprovalSettings[0:len(c.CallOptions.GetAccessApprovalSettings):len(c.CallOptions.GetAccessApprovalSettings)], opts...) + opts = append((*c.CallOptions).GetAccessApprovalSettings[0:len((*c.CallOptions).GetAccessApprovalSettings):len((*c.CallOptions).GetAccessApprovalSettings)], opts...) var resp *accessapprovalpb.AccessApprovalSettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -355,9 +475,7 @@ func (c *Client) GetAccessApprovalSettings(ctx context.Context, req *accessappro return resp, nil } -// UpdateAccessApprovalSettings updates the settings associated with a project, folder, or organization. -// Settings to update are determined by the value of field_mask. -func (c *Client) UpdateAccessApprovalSettings(ctx context.Context, req *accessapprovalpb.UpdateAccessApprovalSettingsMessage, opts ...gax.CallOption) (*accessapprovalpb.AccessApprovalSettings, error) { +func (c *gRPCClient) UpdateAccessApprovalSettings(ctx context.Context, req *accessapprovalpb.UpdateAccessApprovalSettingsMessage, opts ...gax.CallOption) (*accessapprovalpb.AccessApprovalSettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -365,7 +483,7 @@ func (c *Client) UpdateAccessApprovalSettings(ctx context.Context, req *accessap } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "settings.name", url.QueryEscape(req.GetSettings().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateAccessApprovalSettings[0:len(c.CallOptions.UpdateAccessApprovalSettings):len(c.CallOptions.UpdateAccessApprovalSettings)], opts...) + opts = append((*c.CallOptions).UpdateAccessApprovalSettings[0:len((*c.CallOptions).UpdateAccessApprovalSettings):len((*c.CallOptions).UpdateAccessApprovalSettings)], opts...) var resp *accessapprovalpb.AccessApprovalSettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -378,13 +496,7 @@ func (c *Client) UpdateAccessApprovalSettings(ctx context.Context, req *accessap return resp, nil } -// DeleteAccessApprovalSettings deletes the settings associated with a project, folder, or organization. -// This will have the effect of disabling Access Approval for the project, -// folder, or organization, but only if all ancestors also have Access -// Approval disabled. If Access Approval is enabled at a higher level of the -// hierarchy, then Access Approval will still be enabled at this level as -// the settings are inherited. -func (c *Client) DeleteAccessApprovalSettings(ctx context.Context, req *accessapprovalpb.DeleteAccessApprovalSettingsMessage, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteAccessApprovalSettings(ctx context.Context, req *accessapprovalpb.DeleteAccessApprovalSettingsMessage, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -392,7 +504,7 @@ func (c *Client) DeleteAccessApprovalSettings(ctx context.Context, req *accessap } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteAccessApprovalSettings[0:len(c.CallOptions.DeleteAccessApprovalSettings):len(c.CallOptions.DeleteAccessApprovalSettings)], opts...) + opts = append((*c.CallOptions).DeleteAccessApprovalSettings[0:len((*c.CallOptions).DeleteAccessApprovalSettings):len((*c.CallOptions).DeleteAccessApprovalSettings)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteAccessApprovalSettings(ctx, req, settings.GRPC...) diff --git a/accessapproval/apiv1/access_approval_client_example_test.go b/accessapproval/apiv1/access_approval_client_example_test.go index 73ef867bad68..2eb821d64ab0 100644 --- a/accessapproval/apiv1/access_approval_client_example_test.go +++ b/accessapproval/apiv1/access_approval_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ListApprovalRequests() { - // import accessapprovalpb "google.golang.org/genproto/googleapis/cloud/accessapproval/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := accessapproval.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &accessapprovalpb.ListApprovalRequestsMessage{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleClient_ListApprovalRequests() { } func ExampleClient_GetApprovalRequest() { - // import accessapprovalpb "google.golang.org/genproto/googleapis/cloud/accessapproval/v1" - ctx := context.Background() c, err := accessapproval.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &accessapprovalpb.GetApprovalRequestMessage{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleClient_GetApprovalRequest() { } func ExampleClient_ApproveApprovalRequest() { - // import accessapprovalpb "google.golang.org/genproto/googleapis/cloud/accessapproval/v1" - ctx := context.Background() c, err := accessapproval.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &accessapprovalpb.ApproveApprovalRequestMessage{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleClient_ApproveApprovalRequest() { } func ExampleClient_DismissApprovalRequest() { - // import accessapprovalpb "google.golang.org/genproto/googleapis/cloud/accessapproval/v1" - ctx := context.Background() c, err := accessapproval.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &accessapprovalpb.DismissApprovalRequestMessage{ // TODO: Fill request struct fields. @@ -122,13 +119,12 @@ func ExampleClient_DismissApprovalRequest() { } func ExampleClient_GetAccessApprovalSettings() { - // import accessapprovalpb "google.golang.org/genproto/googleapis/cloud/accessapproval/v1" - ctx := context.Background() c, err := accessapproval.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &accessapprovalpb.GetAccessApprovalSettingsMessage{ // TODO: Fill request struct fields. @@ -142,13 +138,12 @@ func ExampleClient_GetAccessApprovalSettings() { } func ExampleClient_UpdateAccessApprovalSettings() { - // import accessapprovalpb "google.golang.org/genproto/googleapis/cloud/accessapproval/v1" - ctx := context.Background() c, err := accessapproval.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &accessapprovalpb.UpdateAccessApprovalSettingsMessage{ // TODO: Fill request struct fields. @@ -167,6 +162,7 @@ func ExampleClient_DeleteAccessApprovalSettings() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &accessapprovalpb.DeleteAccessApprovalSettingsMessage{ // TODO: Fill request struct fields. diff --git a/accessapproval/apiv1/doc.go b/accessapproval/apiv1/doc.go index 3fbccad547b3..8a0faaa0dd93 100644 --- a/accessapproval/apiv1/doc.go +++ b/accessapproval/apiv1/doc.go @@ -28,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package accessapproval // import "cloud.google.com/go/accessapproval/apiv1" import ( @@ -48,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/analytics/admin/apiv1alpha/analytics_admin_client.go b/analytics/admin/apiv1alpha/analytics_admin_client.go index 9123b9fec42a..e1288fe6fe9b 100644 --- a/analytics/admin/apiv1alpha/analytics_admin_client.go +++ b/analytics/admin/apiv1alpha/analytics_admin_client.go @@ -88,7 +88,7 @@ type AnalyticsAdminCallOptions struct { SearchChangeHistoryEvents []gax.CallOption } -func defaultAnalyticsAdminClientOptions() []option.ClientOption { +func defaultAnalyticsAdminGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("analyticsadmin.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("analyticsadmin.mtls.googleapis.com:443"), @@ -196,32 +196,418 @@ func defaultAnalyticsAdminCallOptions() *AnalyticsAdminCallOptions { } } +// internalAnalyticsAdminClient is an interface that defines the methods availaible from Google Analytics Admin API. +type internalAnalyticsAdminClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + GetAccount(context.Context, *adminpb.GetAccountRequest, ...gax.CallOption) (*adminpb.Account, error) + ListAccounts(context.Context, *adminpb.ListAccountsRequest, ...gax.CallOption) *AccountIterator + DeleteAccount(context.Context, *adminpb.DeleteAccountRequest, ...gax.CallOption) error + UpdateAccount(context.Context, *adminpb.UpdateAccountRequest, ...gax.CallOption) (*adminpb.Account, error) + ProvisionAccountTicket(context.Context, *adminpb.ProvisionAccountTicketRequest, ...gax.CallOption) (*adminpb.ProvisionAccountTicketResponse, error) + ListAccountSummaries(context.Context, *adminpb.ListAccountSummariesRequest, ...gax.CallOption) *AccountSummaryIterator + GetProperty(context.Context, *adminpb.GetPropertyRequest, ...gax.CallOption) (*adminpb.Property, error) + ListProperties(context.Context, *adminpb.ListPropertiesRequest, ...gax.CallOption) *PropertyIterator + CreateProperty(context.Context, *adminpb.CreatePropertyRequest, ...gax.CallOption) (*adminpb.Property, error) + DeleteProperty(context.Context, *adminpb.DeletePropertyRequest, ...gax.CallOption) (*adminpb.Property, error) + UpdateProperty(context.Context, *adminpb.UpdatePropertyRequest, ...gax.CallOption) (*adminpb.Property, error) + GetUserLink(context.Context, *adminpb.GetUserLinkRequest, ...gax.CallOption) (*adminpb.UserLink, error) + BatchGetUserLinks(context.Context, *adminpb.BatchGetUserLinksRequest, ...gax.CallOption) (*adminpb.BatchGetUserLinksResponse, error) + ListUserLinks(context.Context, *adminpb.ListUserLinksRequest, ...gax.CallOption) *UserLinkIterator + AuditUserLinks(context.Context, *adminpb.AuditUserLinksRequest, ...gax.CallOption) *AuditUserLinkIterator + CreateUserLink(context.Context, *adminpb.CreateUserLinkRequest, ...gax.CallOption) (*adminpb.UserLink, error) + BatchCreateUserLinks(context.Context, *adminpb.BatchCreateUserLinksRequest, ...gax.CallOption) (*adminpb.BatchCreateUserLinksResponse, error) + UpdateUserLink(context.Context, *adminpb.UpdateUserLinkRequest, ...gax.CallOption) (*adminpb.UserLink, error) + BatchUpdateUserLinks(context.Context, *adminpb.BatchUpdateUserLinksRequest, ...gax.CallOption) (*adminpb.BatchUpdateUserLinksResponse, error) + DeleteUserLink(context.Context, *adminpb.DeleteUserLinkRequest, ...gax.CallOption) error + BatchDeleteUserLinks(context.Context, *adminpb.BatchDeleteUserLinksRequest, ...gax.CallOption) error + GetWebDataStream(context.Context, *adminpb.GetWebDataStreamRequest, ...gax.CallOption) (*adminpb.WebDataStream, error) + DeleteWebDataStream(context.Context, *adminpb.DeleteWebDataStreamRequest, ...gax.CallOption) error + UpdateWebDataStream(context.Context, *adminpb.UpdateWebDataStreamRequest, ...gax.CallOption) (*adminpb.WebDataStream, error) + CreateWebDataStream(context.Context, *adminpb.CreateWebDataStreamRequest, ...gax.CallOption) (*adminpb.WebDataStream, error) + ListWebDataStreams(context.Context, *adminpb.ListWebDataStreamsRequest, ...gax.CallOption) *WebDataStreamIterator + GetIosAppDataStream(context.Context, *adminpb.GetIosAppDataStreamRequest, ...gax.CallOption) (*adminpb.IosAppDataStream, error) + DeleteIosAppDataStream(context.Context, *adminpb.DeleteIosAppDataStreamRequest, ...gax.CallOption) error + UpdateIosAppDataStream(context.Context, *adminpb.UpdateIosAppDataStreamRequest, ...gax.CallOption) (*adminpb.IosAppDataStream, error) + ListIosAppDataStreams(context.Context, *adminpb.ListIosAppDataStreamsRequest, ...gax.CallOption) *IosAppDataStreamIterator + GetAndroidAppDataStream(context.Context, *adminpb.GetAndroidAppDataStreamRequest, ...gax.CallOption) (*adminpb.AndroidAppDataStream, error) + DeleteAndroidAppDataStream(context.Context, *adminpb.DeleteAndroidAppDataStreamRequest, ...gax.CallOption) error + UpdateAndroidAppDataStream(context.Context, *adminpb.UpdateAndroidAppDataStreamRequest, ...gax.CallOption) (*adminpb.AndroidAppDataStream, error) + ListAndroidAppDataStreams(context.Context, *adminpb.ListAndroidAppDataStreamsRequest, ...gax.CallOption) *AndroidAppDataStreamIterator + GetEnhancedMeasurementSettings(context.Context, *adminpb.GetEnhancedMeasurementSettingsRequest, ...gax.CallOption) (*adminpb.EnhancedMeasurementSettings, error) + UpdateEnhancedMeasurementSettings(context.Context, *adminpb.UpdateEnhancedMeasurementSettingsRequest, ...gax.CallOption) (*adminpb.EnhancedMeasurementSettings, error) + CreateFirebaseLink(context.Context, *adminpb.CreateFirebaseLinkRequest, ...gax.CallOption) (*adminpb.FirebaseLink, error) + UpdateFirebaseLink(context.Context, *adminpb.UpdateFirebaseLinkRequest, ...gax.CallOption) (*adminpb.FirebaseLink, error) + DeleteFirebaseLink(context.Context, *adminpb.DeleteFirebaseLinkRequest, ...gax.CallOption) error + ListFirebaseLinks(context.Context, *adminpb.ListFirebaseLinksRequest, ...gax.CallOption) *FirebaseLinkIterator + GetGlobalSiteTag(context.Context, *adminpb.GetGlobalSiteTagRequest, ...gax.CallOption) (*adminpb.GlobalSiteTag, error) + CreateGoogleAdsLink(context.Context, *adminpb.CreateGoogleAdsLinkRequest, ...gax.CallOption) (*adminpb.GoogleAdsLink, error) + UpdateGoogleAdsLink(context.Context, *adminpb.UpdateGoogleAdsLinkRequest, ...gax.CallOption) (*adminpb.GoogleAdsLink, error) + DeleteGoogleAdsLink(context.Context, *adminpb.DeleteGoogleAdsLinkRequest, ...gax.CallOption) error + ListGoogleAdsLinks(context.Context, *adminpb.ListGoogleAdsLinksRequest, ...gax.CallOption) *GoogleAdsLinkIterator + GetDataSharingSettings(context.Context, *adminpb.GetDataSharingSettingsRequest, ...gax.CallOption) (*adminpb.DataSharingSettings, error) + SearchChangeHistoryEvents(context.Context, *adminpb.SearchChangeHistoryEventsRequest, ...gax.CallOption) *ChangeHistoryEventIterator +} + // AnalyticsAdminClient is a client for interacting with Google Analytics Admin API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service Interface for the Analytics Admin API (GA4). type AnalyticsAdminClient struct { + // The internal transport-dependent client. + internalClient internalAnalyticsAdminClient + + // The call options for this service. + CallOptions *AnalyticsAdminCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *AnalyticsAdminClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *AnalyticsAdminClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *AnalyticsAdminClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// GetAccount lookup for a single Account. +func (c *AnalyticsAdminClient) GetAccount(ctx context.Context, req *adminpb.GetAccountRequest, opts ...gax.CallOption) (*adminpb.Account, error) { + return c.internalClient.GetAccount(ctx, req, opts...) +} + +// ListAccounts returns all accounts accessible by the caller. +// +// Note that these accounts might not currently have GA4 properties. +// Soft-deleted (ie: “trashed”) accounts are excluded by default. +// Returns an empty list if no relevant accounts are found. +func (c *AnalyticsAdminClient) ListAccounts(ctx context.Context, req *adminpb.ListAccountsRequest, opts ...gax.CallOption) *AccountIterator { + return c.internalClient.ListAccounts(ctx, req, opts...) +} + +// DeleteAccount marks target Account as soft-deleted (ie: “trashed”) and returns it. +// +// This API does not have a method to restore soft-deleted accounts. +// However, they can be restored using the Trash Can UI. +// +// If the accounts are not restored before the expiration time, the account +// and all child resources (eg: Properties, GoogleAdsLinks, Streams, +// UserLinks) will be permanently purged. +// https://support.google.com/analytics/answer/6154772 (at https://support.google.com/analytics/answer/6154772) +// +// Returns an error if the target is not found. +func (c *AnalyticsAdminClient) DeleteAccount(ctx context.Context, req *adminpb.DeleteAccountRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteAccount(ctx, req, opts...) +} + +// UpdateAccount updates an account. +func (c *AnalyticsAdminClient) UpdateAccount(ctx context.Context, req *adminpb.UpdateAccountRequest, opts ...gax.CallOption) (*adminpb.Account, error) { + return c.internalClient.UpdateAccount(ctx, req, opts...) +} + +// ProvisionAccountTicket requests a ticket for creating an account. +func (c *AnalyticsAdminClient) ProvisionAccountTicket(ctx context.Context, req *adminpb.ProvisionAccountTicketRequest, opts ...gax.CallOption) (*adminpb.ProvisionAccountTicketResponse, error) { + return c.internalClient.ProvisionAccountTicket(ctx, req, opts...) +} + +// ListAccountSummaries returns summaries of all accounts accessible by the caller. +func (c *AnalyticsAdminClient) ListAccountSummaries(ctx context.Context, req *adminpb.ListAccountSummariesRequest, opts ...gax.CallOption) *AccountSummaryIterator { + return c.internalClient.ListAccountSummaries(ctx, req, opts...) +} + +// GetProperty lookup for a single “GA4” Property. +func (c *AnalyticsAdminClient) GetProperty(ctx context.Context, req *adminpb.GetPropertyRequest, opts ...gax.CallOption) (*adminpb.Property, error) { + return c.internalClient.GetProperty(ctx, req, opts...) +} + +// ListProperties returns child Properties under the specified parent Account. +// +// Only “GA4” properties will be returned. +// Properties will be excluded if the caller does not have access. +// Soft-deleted (ie: “trashed”) properties are excluded by default. +// Returns an empty list if no relevant properties are found. +func (c *AnalyticsAdminClient) ListProperties(ctx context.Context, req *adminpb.ListPropertiesRequest, opts ...gax.CallOption) *PropertyIterator { + return c.internalClient.ListProperties(ctx, req, opts...) +} + +// CreateProperty creates an “GA4” property with the specified location and attributes. +func (c *AnalyticsAdminClient) CreateProperty(ctx context.Context, req *adminpb.CreatePropertyRequest, opts ...gax.CallOption) (*adminpb.Property, error) { + return c.internalClient.CreateProperty(ctx, req, opts...) +} + +// DeleteProperty marks target Property as soft-deleted (ie: “trashed”) and returns it. +// +// This API does not have a method to restore soft-deleted properties. +// However, they can be restored using the Trash Can UI. +// +// If the properties are not restored before the expiration time, the Property +// and all child resources (eg: GoogleAdsLinks, Streams, UserLinks) +// will be permanently purged. +// https://support.google.com/analytics/answer/6154772 (at https://support.google.com/analytics/answer/6154772) +// +// Returns an error if the target is not found, or is not an GA4 Property. +func (c *AnalyticsAdminClient) DeleteProperty(ctx context.Context, req *adminpb.DeletePropertyRequest, opts ...gax.CallOption) (*adminpb.Property, error) { + return c.internalClient.DeleteProperty(ctx, req, opts...) +} + +// UpdateProperty updates a property. +func (c *AnalyticsAdminClient) UpdateProperty(ctx context.Context, req *adminpb.UpdatePropertyRequest, opts ...gax.CallOption) (*adminpb.Property, error) { + return c.internalClient.UpdateProperty(ctx, req, opts...) +} + +// GetUserLink gets information about a user’s link to an account or property. +func (c *AnalyticsAdminClient) GetUserLink(ctx context.Context, req *adminpb.GetUserLinkRequest, opts ...gax.CallOption) (*adminpb.UserLink, error) { + return c.internalClient.GetUserLink(ctx, req, opts...) +} + +// BatchGetUserLinks gets information about multiple users’ links to an account or property. +func (c *AnalyticsAdminClient) BatchGetUserLinks(ctx context.Context, req *adminpb.BatchGetUserLinksRequest, opts ...gax.CallOption) (*adminpb.BatchGetUserLinksResponse, error) { + return c.internalClient.BatchGetUserLinks(ctx, req, opts...) +} + +// ListUserLinks lists all user links on an account or property. +func (c *AnalyticsAdminClient) ListUserLinks(ctx context.Context, req *adminpb.ListUserLinksRequest, opts ...gax.CallOption) *UserLinkIterator { + return c.internalClient.ListUserLinks(ctx, req, opts...) +} + +// AuditUserLinks lists all user links on an account or property, including implicit ones +// that come from effective permissions granted by groups or organization +// admin roles. +// +// If a returned user link does not have direct permissions, they cannot +// be removed from the account or property directly with the DeleteUserLink +// command. They have to be removed from the group/etc that gives them +// permissions, which is currently only usable/discoverable in the GA or GMP +// UIs. +func (c *AnalyticsAdminClient) AuditUserLinks(ctx context.Context, req *adminpb.AuditUserLinksRequest, opts ...gax.CallOption) *AuditUserLinkIterator { + return c.internalClient.AuditUserLinks(ctx, req, opts...) +} + +// CreateUserLink creates a user link on an account or property. +// +// If the user with the specified email already has permissions on the +// account or property, then the user’s existing permissions will be unioned +// with the permissions specified in the new UserLink. +func (c *AnalyticsAdminClient) CreateUserLink(ctx context.Context, req *adminpb.CreateUserLinkRequest, opts ...gax.CallOption) (*adminpb.UserLink, error) { + return c.internalClient.CreateUserLink(ctx, req, opts...) +} + +// BatchCreateUserLinks creates information about multiple users’ links to an account or property. +// +// This method is transactional. If any UserLink cannot be created, none of +// the UserLinks will be created. +func (c *AnalyticsAdminClient) BatchCreateUserLinks(ctx context.Context, req *adminpb.BatchCreateUserLinksRequest, opts ...gax.CallOption) (*adminpb.BatchCreateUserLinksResponse, error) { + return c.internalClient.BatchCreateUserLinks(ctx, req, opts...) +} + +// UpdateUserLink updates a user link on an account or property. +func (c *AnalyticsAdminClient) UpdateUserLink(ctx context.Context, req *adminpb.UpdateUserLinkRequest, opts ...gax.CallOption) (*adminpb.UserLink, error) { + return c.internalClient.UpdateUserLink(ctx, req, opts...) +} + +// BatchUpdateUserLinks updates information about multiple users’ links to an account or property. +func (c *AnalyticsAdminClient) BatchUpdateUserLinks(ctx context.Context, req *adminpb.BatchUpdateUserLinksRequest, opts ...gax.CallOption) (*adminpb.BatchUpdateUserLinksResponse, error) { + return c.internalClient.BatchUpdateUserLinks(ctx, req, opts...) +} + +// DeleteUserLink deletes a user link on an account or property. +func (c *AnalyticsAdminClient) DeleteUserLink(ctx context.Context, req *adminpb.DeleteUserLinkRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteUserLink(ctx, req, opts...) +} + +// BatchDeleteUserLinks deletes information about multiple users’ links to an account or property. +func (c *AnalyticsAdminClient) BatchDeleteUserLinks(ctx context.Context, req *adminpb.BatchDeleteUserLinksRequest, opts ...gax.CallOption) error { + return c.internalClient.BatchDeleteUserLinks(ctx, req, opts...) +} + +// GetWebDataStream lookup for a single WebDataStream +func (c *AnalyticsAdminClient) GetWebDataStream(ctx context.Context, req *adminpb.GetWebDataStreamRequest, opts ...gax.CallOption) (*adminpb.WebDataStream, error) { + return c.internalClient.GetWebDataStream(ctx, req, opts...) +} + +// DeleteWebDataStream deletes a web stream on a property. +func (c *AnalyticsAdminClient) DeleteWebDataStream(ctx context.Context, req *adminpb.DeleteWebDataStreamRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteWebDataStream(ctx, req, opts...) +} + +// UpdateWebDataStream updates a web stream on a property. +func (c *AnalyticsAdminClient) UpdateWebDataStream(ctx context.Context, req *adminpb.UpdateWebDataStreamRequest, opts ...gax.CallOption) (*adminpb.WebDataStream, error) { + return c.internalClient.UpdateWebDataStream(ctx, req, opts...) +} + +// CreateWebDataStream creates a web stream with the specified location and attributes. +func (c *AnalyticsAdminClient) CreateWebDataStream(ctx context.Context, req *adminpb.CreateWebDataStreamRequest, opts ...gax.CallOption) (*adminpb.WebDataStream, error) { + return c.internalClient.CreateWebDataStream(ctx, req, opts...) +} + +// ListWebDataStreams returns child web data streams under the specified parent property. +// +// Web data streams will be excluded if the caller does not have access. +// Returns an empty list if no relevant web data streams are found. +func (c *AnalyticsAdminClient) ListWebDataStreams(ctx context.Context, req *adminpb.ListWebDataStreamsRequest, opts ...gax.CallOption) *WebDataStreamIterator { + return c.internalClient.ListWebDataStreams(ctx, req, opts...) +} + +// GetIosAppDataStream lookup for a single IosAppDataStream +func (c *AnalyticsAdminClient) GetIosAppDataStream(ctx context.Context, req *adminpb.GetIosAppDataStreamRequest, opts ...gax.CallOption) (*adminpb.IosAppDataStream, error) { + return c.internalClient.GetIosAppDataStream(ctx, req, opts...) +} + +// DeleteIosAppDataStream deletes an iOS app stream on a property. +func (c *AnalyticsAdminClient) DeleteIosAppDataStream(ctx context.Context, req *adminpb.DeleteIosAppDataStreamRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteIosAppDataStream(ctx, req, opts...) +} + +// UpdateIosAppDataStream updates an iOS app stream on a property. +func (c *AnalyticsAdminClient) UpdateIosAppDataStream(ctx context.Context, req *adminpb.UpdateIosAppDataStreamRequest, opts ...gax.CallOption) (*adminpb.IosAppDataStream, error) { + return c.internalClient.UpdateIosAppDataStream(ctx, req, opts...) +} + +// ListIosAppDataStreams returns child iOS app data streams under the specified parent property. +// +// iOS app data streams will be excluded if the caller does not have access. +// Returns an empty list if no relevant iOS app data streams are found. +func (c *AnalyticsAdminClient) ListIosAppDataStreams(ctx context.Context, req *adminpb.ListIosAppDataStreamsRequest, opts ...gax.CallOption) *IosAppDataStreamIterator { + return c.internalClient.ListIosAppDataStreams(ctx, req, opts...) +} + +// GetAndroidAppDataStream lookup for a single AndroidAppDataStream +func (c *AnalyticsAdminClient) GetAndroidAppDataStream(ctx context.Context, req *adminpb.GetAndroidAppDataStreamRequest, opts ...gax.CallOption) (*adminpb.AndroidAppDataStream, error) { + return c.internalClient.GetAndroidAppDataStream(ctx, req, opts...) +} + +// DeleteAndroidAppDataStream deletes an android app stream on a property. +func (c *AnalyticsAdminClient) DeleteAndroidAppDataStream(ctx context.Context, req *adminpb.DeleteAndroidAppDataStreamRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteAndroidAppDataStream(ctx, req, opts...) +} + +// UpdateAndroidAppDataStream updates an android app stream on a property. +func (c *AnalyticsAdminClient) UpdateAndroidAppDataStream(ctx context.Context, req *adminpb.UpdateAndroidAppDataStreamRequest, opts ...gax.CallOption) (*adminpb.AndroidAppDataStream, error) { + return c.internalClient.UpdateAndroidAppDataStream(ctx, req, opts...) +} + +// ListAndroidAppDataStreams returns child android app streams under the specified parent property. +// +// Android app streams will be excluded if the caller does not have access. +// Returns an empty list if no relevant android app streams are found. +func (c *AnalyticsAdminClient) ListAndroidAppDataStreams(ctx context.Context, req *adminpb.ListAndroidAppDataStreamsRequest, opts ...gax.CallOption) *AndroidAppDataStreamIterator { + return c.internalClient.ListAndroidAppDataStreams(ctx, req, opts...) +} + +// GetEnhancedMeasurementSettings returns the singleton enhanced measurement settings for this web stream. +// Note that the stream must enable enhanced measurement for these settings to +// take effect. +func (c *AnalyticsAdminClient) GetEnhancedMeasurementSettings(ctx context.Context, req *adminpb.GetEnhancedMeasurementSettingsRequest, opts ...gax.CallOption) (*adminpb.EnhancedMeasurementSettings, error) { + return c.internalClient.GetEnhancedMeasurementSettings(ctx, req, opts...) +} + +// UpdateEnhancedMeasurementSettings updates the singleton enhanced measurement settings for this web stream. +// Note that the stream must enable enhanced measurement for these settings to +// take effect. +func (c *AnalyticsAdminClient) UpdateEnhancedMeasurementSettings(ctx context.Context, req *adminpb.UpdateEnhancedMeasurementSettingsRequest, opts ...gax.CallOption) (*adminpb.EnhancedMeasurementSettings, error) { + return c.internalClient.UpdateEnhancedMeasurementSettings(ctx, req, opts...) +} + +// CreateFirebaseLink creates a FirebaseLink. +// +// Properties can have at most one FirebaseLink. +func (c *AnalyticsAdminClient) CreateFirebaseLink(ctx context.Context, req *adminpb.CreateFirebaseLinkRequest, opts ...gax.CallOption) (*adminpb.FirebaseLink, error) { + return c.internalClient.CreateFirebaseLink(ctx, req, opts...) +} + +// UpdateFirebaseLink updates a FirebaseLink on a property +func (c *AnalyticsAdminClient) UpdateFirebaseLink(ctx context.Context, req *adminpb.UpdateFirebaseLinkRequest, opts ...gax.CallOption) (*adminpb.FirebaseLink, error) { + return c.internalClient.UpdateFirebaseLink(ctx, req, opts...) +} + +// DeleteFirebaseLink deletes a FirebaseLink on a property +func (c *AnalyticsAdminClient) DeleteFirebaseLink(ctx context.Context, req *adminpb.DeleteFirebaseLinkRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteFirebaseLink(ctx, req, opts...) +} + +// ListFirebaseLinks lists FirebaseLinks on a property. +// Properties can have at most one FirebaseLink. +func (c *AnalyticsAdminClient) ListFirebaseLinks(ctx context.Context, req *adminpb.ListFirebaseLinksRequest, opts ...gax.CallOption) *FirebaseLinkIterator { + return c.internalClient.ListFirebaseLinks(ctx, req, opts...) +} + +// GetGlobalSiteTag returns the Site Tag for the specified web stream. +// Site Tags are immutable singletons. +func (c *AnalyticsAdminClient) GetGlobalSiteTag(ctx context.Context, req *adminpb.GetGlobalSiteTagRequest, opts ...gax.CallOption) (*adminpb.GlobalSiteTag, error) { + return c.internalClient.GetGlobalSiteTag(ctx, req, opts...) +} + +// CreateGoogleAdsLink creates a GoogleAdsLink. +func (c *AnalyticsAdminClient) CreateGoogleAdsLink(ctx context.Context, req *adminpb.CreateGoogleAdsLinkRequest, opts ...gax.CallOption) (*adminpb.GoogleAdsLink, error) { + return c.internalClient.CreateGoogleAdsLink(ctx, req, opts...) +} + +// UpdateGoogleAdsLink updates a GoogleAdsLink on a property +func (c *AnalyticsAdminClient) UpdateGoogleAdsLink(ctx context.Context, req *adminpb.UpdateGoogleAdsLinkRequest, opts ...gax.CallOption) (*adminpb.GoogleAdsLink, error) { + return c.internalClient.UpdateGoogleAdsLink(ctx, req, opts...) +} + +// DeleteGoogleAdsLink deletes a GoogleAdsLink on a property +func (c *AnalyticsAdminClient) DeleteGoogleAdsLink(ctx context.Context, req *adminpb.DeleteGoogleAdsLinkRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteGoogleAdsLink(ctx, req, opts...) +} + +// ListGoogleAdsLinks lists GoogleAdsLinks on a property. +func (c *AnalyticsAdminClient) ListGoogleAdsLinks(ctx context.Context, req *adminpb.ListGoogleAdsLinksRequest, opts ...gax.CallOption) *GoogleAdsLinkIterator { + return c.internalClient.ListGoogleAdsLinks(ctx, req, opts...) +} + +// GetDataSharingSettings get data sharing settings on an account. +// Data sharing settings are singletons. +func (c *AnalyticsAdminClient) GetDataSharingSettings(ctx context.Context, req *adminpb.GetDataSharingSettingsRequest, opts ...gax.CallOption) (*adminpb.DataSharingSettings, error) { + return c.internalClient.GetDataSharingSettings(ctx, req, opts...) +} + +// SearchChangeHistoryEvents searches through all changes to an account or its children given the +// specified set of filters. +func (c *AnalyticsAdminClient) SearchChangeHistoryEvents(ctx context.Context, req *adminpb.SearchChangeHistoryEventsRequest, opts ...gax.CallOption) *ChangeHistoryEventIterator { + return c.internalClient.SearchChangeHistoryEvents(ctx, req, opts...) +} + +// analyticsAdminGRPCClient is a client for interacting with Google Analytics Admin API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type analyticsAdminGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing AnalyticsAdminClient + CallOptions **AnalyticsAdminCallOptions + // The gRPC API client. analyticsAdminClient adminpb.AnalyticsAdminServiceClient - // The call options for this service. - CallOptions *AnalyticsAdminCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewAnalyticsAdminClient creates a new analytics admin service client. +// NewAnalyticsAdminClient creates a new analytics admin service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service Interface for the Analytics Admin API (GA4). func NewAnalyticsAdminClient(ctx context.Context, opts ...option.ClientOption) (*AnalyticsAdminClient, error) { - clientOpts := defaultAnalyticsAdminClientOptions() - + clientOpts := defaultAnalyticsAdminGRPCClientOptions() if newAnalyticsAdminClientHook != nil { hookOpts, err := newAnalyticsAdminClientHook(ctx, clientHookParams{}) if err != nil { @@ -239,42 +625,44 @@ func NewAnalyticsAdminClient(ctx context.Context, opts ...option.ClientOption) ( if err != nil { return nil, err } - c := &AnalyticsAdminClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultAnalyticsAdminCallOptions(), + client := AnalyticsAdminClient{CallOptions: defaultAnalyticsAdminCallOptions()} + c := &analyticsAdminGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, analyticsAdminClient: adminpb.NewAnalyticsAdminServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *AnalyticsAdminClient) Connection() *grpc.ClientConn { +func (c *analyticsAdminGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *AnalyticsAdminClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *AnalyticsAdminClient) setGoogleClientInfo(keyval ...string) { +func (c *analyticsAdminGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// GetAccount lookup for a single Account. -func (c *AnalyticsAdminClient) GetAccount(ctx context.Context, req *adminpb.GetAccountRequest, opts ...gax.CallOption) (*adminpb.Account, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *analyticsAdminGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *analyticsAdminGRPCClient) GetAccount(ctx context.Context, req *adminpb.GetAccountRequest, opts ...gax.CallOption) (*adminpb.Account, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -282,7 +670,7 @@ func (c *AnalyticsAdminClient) GetAccount(ctx context.Context, req *adminpb.GetA } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetAccount[0:len(c.CallOptions.GetAccount):len(c.CallOptions.GetAccount)], opts...) + opts = append((*c.CallOptions).GetAccount[0:len((*c.CallOptions).GetAccount):len((*c.CallOptions).GetAccount)], opts...) var resp *adminpb.Account err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -295,14 +683,9 @@ func (c *AnalyticsAdminClient) GetAccount(ctx context.Context, req *adminpb.GetA return resp, nil } -// ListAccounts returns all accounts accessible by the caller. -// -// Note that these accounts might not currently have GA4 properties. -// Soft-deleted (ie: “trashed”) accounts are excluded by default. -// Returns an empty list if no relevant accounts are found. -func (c *AnalyticsAdminClient) ListAccounts(ctx context.Context, req *adminpb.ListAccountsRequest, opts ...gax.CallOption) *AccountIterator { +func (c *analyticsAdminGRPCClient) ListAccounts(ctx context.Context, req *adminpb.ListAccountsRequest, opts ...gax.CallOption) *AccountIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListAccounts[0:len(c.CallOptions.ListAccounts):len(c.CallOptions.ListAccounts)], opts...) + opts = append((*c.CallOptions).ListAccounts[0:len((*c.CallOptions).ListAccounts):len((*c.CallOptions).ListAccounts)], opts...) it := &AccountIterator{} req = proto.Clone(req).(*adminpb.ListAccountsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*adminpb.Account, string, error) { @@ -339,18 +722,7 @@ func (c *AnalyticsAdminClient) ListAccounts(ctx context.Context, req *adminpb.Li return it } -// DeleteAccount marks target Account as soft-deleted (ie: “trashed”) and returns it. -// -// This API does not have a method to restore soft-deleted accounts. -// However, they can be restored using the Trash Can UI. -// -// If the accounts are not restored before the expiration time, the account -// and all child resources (eg: Properties, GoogleAdsLinks, Streams, -// UserLinks) will be permanently purged. -// https://support.google.com/analytics/answer/6154772 (at https://support.google.com/analytics/answer/6154772) -// -// Returns an error if the target is not found. -func (c *AnalyticsAdminClient) DeleteAccount(ctx context.Context, req *adminpb.DeleteAccountRequest, opts ...gax.CallOption) error { +func (c *analyticsAdminGRPCClient) DeleteAccount(ctx context.Context, req *adminpb.DeleteAccountRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -358,7 +730,7 @@ func (c *AnalyticsAdminClient) DeleteAccount(ctx context.Context, req *adminpb.D } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteAccount[0:len(c.CallOptions.DeleteAccount):len(c.CallOptions.DeleteAccount)], opts...) + opts = append((*c.CallOptions).DeleteAccount[0:len((*c.CallOptions).DeleteAccount):len((*c.CallOptions).DeleteAccount)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.analyticsAdminClient.DeleteAccount(ctx, req, settings.GRPC...) @@ -367,8 +739,7 @@ func (c *AnalyticsAdminClient) DeleteAccount(ctx context.Context, req *adminpb.D return err } -// UpdateAccount updates an account. -func (c *AnalyticsAdminClient) UpdateAccount(ctx context.Context, req *adminpb.UpdateAccountRequest, opts ...gax.CallOption) (*adminpb.Account, error) { +func (c *analyticsAdminGRPCClient) UpdateAccount(ctx context.Context, req *adminpb.UpdateAccountRequest, opts ...gax.CallOption) (*adminpb.Account, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -376,7 +747,7 @@ func (c *AnalyticsAdminClient) UpdateAccount(ctx context.Context, req *adminpb.U } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "account.name", url.QueryEscape(req.GetAccount().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateAccount[0:len(c.CallOptions.UpdateAccount):len(c.CallOptions.UpdateAccount)], opts...) + opts = append((*c.CallOptions).UpdateAccount[0:len((*c.CallOptions).UpdateAccount):len((*c.CallOptions).UpdateAccount)], opts...) var resp *adminpb.Account err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -389,15 +760,14 @@ func (c *AnalyticsAdminClient) UpdateAccount(ctx context.Context, req *adminpb.U return resp, nil } -// ProvisionAccountTicket requests a ticket for creating an account. -func (c *AnalyticsAdminClient) ProvisionAccountTicket(ctx context.Context, req *adminpb.ProvisionAccountTicketRequest, opts ...gax.CallOption) (*adminpb.ProvisionAccountTicketResponse, error) { +func (c *analyticsAdminGRPCClient) ProvisionAccountTicket(ctx context.Context, req *adminpb.ProvisionAccountTicketRequest, opts ...gax.CallOption) (*adminpb.ProvisionAccountTicketResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ProvisionAccountTicket[0:len(c.CallOptions.ProvisionAccountTicket):len(c.CallOptions.ProvisionAccountTicket)], opts...) + opts = append((*c.CallOptions).ProvisionAccountTicket[0:len((*c.CallOptions).ProvisionAccountTicket):len((*c.CallOptions).ProvisionAccountTicket)], opts...) var resp *adminpb.ProvisionAccountTicketResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -410,10 +780,9 @@ func (c *AnalyticsAdminClient) ProvisionAccountTicket(ctx context.Context, req * return resp, nil } -// ListAccountSummaries returns summaries of all accounts accessible by the caller. -func (c *AnalyticsAdminClient) ListAccountSummaries(ctx context.Context, req *adminpb.ListAccountSummariesRequest, opts ...gax.CallOption) *AccountSummaryIterator { +func (c *analyticsAdminGRPCClient) ListAccountSummaries(ctx context.Context, req *adminpb.ListAccountSummariesRequest, opts ...gax.CallOption) *AccountSummaryIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListAccountSummaries[0:len(c.CallOptions.ListAccountSummaries):len(c.CallOptions.ListAccountSummaries)], opts...) + opts = append((*c.CallOptions).ListAccountSummaries[0:len((*c.CallOptions).ListAccountSummaries):len((*c.CallOptions).ListAccountSummaries)], opts...) it := &AccountSummaryIterator{} req = proto.Clone(req).(*adminpb.ListAccountSummariesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*adminpb.AccountSummary, string, error) { @@ -450,8 +819,7 @@ func (c *AnalyticsAdminClient) ListAccountSummaries(ctx context.Context, req *ad return it } -// GetProperty lookup for a single “GA4” Property. -func (c *AnalyticsAdminClient) GetProperty(ctx context.Context, req *adminpb.GetPropertyRequest, opts ...gax.CallOption) (*adminpb.Property, error) { +func (c *analyticsAdminGRPCClient) GetProperty(ctx context.Context, req *adminpb.GetPropertyRequest, opts ...gax.CallOption) (*adminpb.Property, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -459,7 +827,7 @@ func (c *AnalyticsAdminClient) GetProperty(ctx context.Context, req *adminpb.Get } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetProperty[0:len(c.CallOptions.GetProperty):len(c.CallOptions.GetProperty)], opts...) + opts = append((*c.CallOptions).GetProperty[0:len((*c.CallOptions).GetProperty):len((*c.CallOptions).GetProperty)], opts...) var resp *adminpb.Property err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -472,15 +840,9 @@ func (c *AnalyticsAdminClient) GetProperty(ctx context.Context, req *adminpb.Get return resp, nil } -// ListProperties returns child Properties under the specified parent Account. -// -// Only “GA4” properties will be returned. -// Properties will be excluded if the caller does not have access. -// Soft-deleted (ie: “trashed”) properties are excluded by default. -// Returns an empty list if no relevant properties are found. -func (c *AnalyticsAdminClient) ListProperties(ctx context.Context, req *adminpb.ListPropertiesRequest, opts ...gax.CallOption) *PropertyIterator { +func (c *analyticsAdminGRPCClient) ListProperties(ctx context.Context, req *adminpb.ListPropertiesRequest, opts ...gax.CallOption) *PropertyIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListProperties[0:len(c.CallOptions.ListProperties):len(c.CallOptions.ListProperties)], opts...) + opts = append((*c.CallOptions).ListProperties[0:len((*c.CallOptions).ListProperties):len((*c.CallOptions).ListProperties)], opts...) it := &PropertyIterator{} req = proto.Clone(req).(*adminpb.ListPropertiesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*adminpb.Property, string, error) { @@ -517,15 +879,14 @@ func (c *AnalyticsAdminClient) ListProperties(ctx context.Context, req *adminpb. return it } -// CreateProperty creates an “GA4” property with the specified location and attributes. -func (c *AnalyticsAdminClient) CreateProperty(ctx context.Context, req *adminpb.CreatePropertyRequest, opts ...gax.CallOption) (*adminpb.Property, error) { +func (c *analyticsAdminGRPCClient) CreateProperty(ctx context.Context, req *adminpb.CreatePropertyRequest, opts ...gax.CallOption) (*adminpb.Property, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.CreateProperty[0:len(c.CallOptions.CreateProperty):len(c.CallOptions.CreateProperty)], opts...) + opts = append((*c.CallOptions).CreateProperty[0:len((*c.CallOptions).CreateProperty):len((*c.CallOptions).CreateProperty)], opts...) var resp *adminpb.Property err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -538,18 +899,7 @@ func (c *AnalyticsAdminClient) CreateProperty(ctx context.Context, req *adminpb. return resp, nil } -// DeleteProperty marks target Property as soft-deleted (ie: “trashed”) and returns it. -// -// This API does not have a method to restore soft-deleted properties. -// However, they can be restored using the Trash Can UI. -// -// If the properties are not restored before the expiration time, the Property -// and all child resources (eg: GoogleAdsLinks, Streams, UserLinks) -// will be permanently purged. -// https://support.google.com/analytics/answer/6154772 (at https://support.google.com/analytics/answer/6154772) -// -// Returns an error if the target is not found, or is not an GA4 Property. -func (c *AnalyticsAdminClient) DeleteProperty(ctx context.Context, req *adminpb.DeletePropertyRequest, opts ...gax.CallOption) (*adminpb.Property, error) { +func (c *analyticsAdminGRPCClient) DeleteProperty(ctx context.Context, req *adminpb.DeletePropertyRequest, opts ...gax.CallOption) (*adminpb.Property, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -557,7 +907,7 @@ func (c *AnalyticsAdminClient) DeleteProperty(ctx context.Context, req *adminpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteProperty[0:len(c.CallOptions.DeleteProperty):len(c.CallOptions.DeleteProperty)], opts...) + opts = append((*c.CallOptions).DeleteProperty[0:len((*c.CallOptions).DeleteProperty):len((*c.CallOptions).DeleteProperty)], opts...) var resp *adminpb.Property err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -570,8 +920,7 @@ func (c *AnalyticsAdminClient) DeleteProperty(ctx context.Context, req *adminpb. return resp, nil } -// UpdateProperty updates a property. -func (c *AnalyticsAdminClient) UpdateProperty(ctx context.Context, req *adminpb.UpdatePropertyRequest, opts ...gax.CallOption) (*adminpb.Property, error) { +func (c *analyticsAdminGRPCClient) UpdateProperty(ctx context.Context, req *adminpb.UpdatePropertyRequest, opts ...gax.CallOption) (*adminpb.Property, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -579,7 +928,7 @@ func (c *AnalyticsAdminClient) UpdateProperty(ctx context.Context, req *adminpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "property.name", url.QueryEscape(req.GetProperty().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateProperty[0:len(c.CallOptions.UpdateProperty):len(c.CallOptions.UpdateProperty)], opts...) + opts = append((*c.CallOptions).UpdateProperty[0:len((*c.CallOptions).UpdateProperty):len((*c.CallOptions).UpdateProperty)], opts...) var resp *adminpb.Property err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -592,8 +941,7 @@ func (c *AnalyticsAdminClient) UpdateProperty(ctx context.Context, req *adminpb. return resp, nil } -// GetUserLink gets information about a user’s link to an account or property. -func (c *AnalyticsAdminClient) GetUserLink(ctx context.Context, req *adminpb.GetUserLinkRequest, opts ...gax.CallOption) (*adminpb.UserLink, error) { +func (c *analyticsAdminGRPCClient) GetUserLink(ctx context.Context, req *adminpb.GetUserLinkRequest, opts ...gax.CallOption) (*adminpb.UserLink, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -601,7 +949,7 @@ func (c *AnalyticsAdminClient) GetUserLink(ctx context.Context, req *adminpb.Get } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetUserLink[0:len(c.CallOptions.GetUserLink):len(c.CallOptions.GetUserLink)], opts...) + opts = append((*c.CallOptions).GetUserLink[0:len((*c.CallOptions).GetUserLink):len((*c.CallOptions).GetUserLink)], opts...) var resp *adminpb.UserLink err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -614,8 +962,7 @@ func (c *AnalyticsAdminClient) GetUserLink(ctx context.Context, req *adminpb.Get return resp, nil } -// BatchGetUserLinks gets information about multiple users’ links to an account or property. -func (c *AnalyticsAdminClient) BatchGetUserLinks(ctx context.Context, req *adminpb.BatchGetUserLinksRequest, opts ...gax.CallOption) (*adminpb.BatchGetUserLinksResponse, error) { +func (c *analyticsAdminGRPCClient) BatchGetUserLinks(ctx context.Context, req *adminpb.BatchGetUserLinksRequest, opts ...gax.CallOption) (*adminpb.BatchGetUserLinksResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -623,7 +970,7 @@ func (c *AnalyticsAdminClient) BatchGetUserLinks(ctx context.Context, req *admin } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchGetUserLinks[0:len(c.CallOptions.BatchGetUserLinks):len(c.CallOptions.BatchGetUserLinks)], opts...) + opts = append((*c.CallOptions).BatchGetUserLinks[0:len((*c.CallOptions).BatchGetUserLinks):len((*c.CallOptions).BatchGetUserLinks)], opts...) var resp *adminpb.BatchGetUserLinksResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -636,11 +983,10 @@ func (c *AnalyticsAdminClient) BatchGetUserLinks(ctx context.Context, req *admin return resp, nil } -// ListUserLinks lists all user links on an account or property. -func (c *AnalyticsAdminClient) ListUserLinks(ctx context.Context, req *adminpb.ListUserLinksRequest, opts ...gax.CallOption) *UserLinkIterator { +func (c *analyticsAdminGRPCClient) ListUserLinks(ctx context.Context, req *adminpb.ListUserLinksRequest, opts ...gax.CallOption) *UserLinkIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListUserLinks[0:len(c.CallOptions.ListUserLinks):len(c.CallOptions.ListUserLinks)], opts...) + opts = append((*c.CallOptions).ListUserLinks[0:len((*c.CallOptions).ListUserLinks):len((*c.CallOptions).ListUserLinks)], opts...) it := &UserLinkIterator{} req = proto.Clone(req).(*adminpb.ListUserLinksRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*adminpb.UserLink, string, error) { @@ -677,19 +1023,10 @@ func (c *AnalyticsAdminClient) ListUserLinks(ctx context.Context, req *adminpb.L return it } -// AuditUserLinks lists all user links on an account or property, including implicit ones -// that come from effective permissions granted by groups or organization -// admin roles. -// -// If a returned user link does not have direct permissions, they cannot -// be removed from the account or property directly with the DeleteUserLink -// command. They have to be removed from the group/etc that gives them -// permissions, which is currently only usable/discoverable in the GA or GMP -// UIs. -func (c *AnalyticsAdminClient) AuditUserLinks(ctx context.Context, req *adminpb.AuditUserLinksRequest, opts ...gax.CallOption) *AuditUserLinkIterator { +func (c *analyticsAdminGRPCClient) AuditUserLinks(ctx context.Context, req *adminpb.AuditUserLinksRequest, opts ...gax.CallOption) *AuditUserLinkIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AuditUserLinks[0:len(c.CallOptions.AuditUserLinks):len(c.CallOptions.AuditUserLinks)], opts...) + opts = append((*c.CallOptions).AuditUserLinks[0:len((*c.CallOptions).AuditUserLinks):len((*c.CallOptions).AuditUserLinks)], opts...) it := &AuditUserLinkIterator{} req = proto.Clone(req).(*adminpb.AuditUserLinksRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*adminpb.AuditUserLink, string, error) { @@ -726,12 +1063,7 @@ func (c *AnalyticsAdminClient) AuditUserLinks(ctx context.Context, req *adminpb. return it } -// CreateUserLink creates a user link on an account or property. -// -// If the user with the specified email already has permissions on the -// account or property, then the user’s existing permissions will be unioned -// with the permissions specified in the new UserLink. -func (c *AnalyticsAdminClient) CreateUserLink(ctx context.Context, req *adminpb.CreateUserLinkRequest, opts ...gax.CallOption) (*adminpb.UserLink, error) { +func (c *analyticsAdminGRPCClient) CreateUserLink(ctx context.Context, req *adminpb.CreateUserLinkRequest, opts ...gax.CallOption) (*adminpb.UserLink, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -739,7 +1071,7 @@ func (c *AnalyticsAdminClient) CreateUserLink(ctx context.Context, req *adminpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateUserLink[0:len(c.CallOptions.CreateUserLink):len(c.CallOptions.CreateUserLink)], opts...) + opts = append((*c.CallOptions).CreateUserLink[0:len((*c.CallOptions).CreateUserLink):len((*c.CallOptions).CreateUserLink)], opts...) var resp *adminpb.UserLink err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -752,11 +1084,7 @@ func (c *AnalyticsAdminClient) CreateUserLink(ctx context.Context, req *adminpb. return resp, nil } -// BatchCreateUserLinks creates information about multiple users’ links to an account or property. -// -// This method is transactional. If any UserLink cannot be created, none of -// the UserLinks will be created. -func (c *AnalyticsAdminClient) BatchCreateUserLinks(ctx context.Context, req *adminpb.BatchCreateUserLinksRequest, opts ...gax.CallOption) (*adminpb.BatchCreateUserLinksResponse, error) { +func (c *analyticsAdminGRPCClient) BatchCreateUserLinks(ctx context.Context, req *adminpb.BatchCreateUserLinksRequest, opts ...gax.CallOption) (*adminpb.BatchCreateUserLinksResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -764,7 +1092,7 @@ func (c *AnalyticsAdminClient) BatchCreateUserLinks(ctx context.Context, req *ad } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchCreateUserLinks[0:len(c.CallOptions.BatchCreateUserLinks):len(c.CallOptions.BatchCreateUserLinks)], opts...) + opts = append((*c.CallOptions).BatchCreateUserLinks[0:len((*c.CallOptions).BatchCreateUserLinks):len((*c.CallOptions).BatchCreateUserLinks)], opts...) var resp *adminpb.BatchCreateUserLinksResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -777,8 +1105,7 @@ func (c *AnalyticsAdminClient) BatchCreateUserLinks(ctx context.Context, req *ad return resp, nil } -// UpdateUserLink updates a user link on an account or property. -func (c *AnalyticsAdminClient) UpdateUserLink(ctx context.Context, req *adminpb.UpdateUserLinkRequest, opts ...gax.CallOption) (*adminpb.UserLink, error) { +func (c *analyticsAdminGRPCClient) UpdateUserLink(ctx context.Context, req *adminpb.UpdateUserLinkRequest, opts ...gax.CallOption) (*adminpb.UserLink, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -786,7 +1113,7 @@ func (c *AnalyticsAdminClient) UpdateUserLink(ctx context.Context, req *adminpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "user_link.name", url.QueryEscape(req.GetUserLink().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateUserLink[0:len(c.CallOptions.UpdateUserLink):len(c.CallOptions.UpdateUserLink)], opts...) + opts = append((*c.CallOptions).UpdateUserLink[0:len((*c.CallOptions).UpdateUserLink):len((*c.CallOptions).UpdateUserLink)], opts...) var resp *adminpb.UserLink err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -799,8 +1126,7 @@ func (c *AnalyticsAdminClient) UpdateUserLink(ctx context.Context, req *adminpb. return resp, nil } -// BatchUpdateUserLinks updates information about multiple users’ links to an account or property. -func (c *AnalyticsAdminClient) BatchUpdateUserLinks(ctx context.Context, req *adminpb.BatchUpdateUserLinksRequest, opts ...gax.CallOption) (*adminpb.BatchUpdateUserLinksResponse, error) { +func (c *analyticsAdminGRPCClient) BatchUpdateUserLinks(ctx context.Context, req *adminpb.BatchUpdateUserLinksRequest, opts ...gax.CallOption) (*adminpb.BatchUpdateUserLinksResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -808,7 +1134,7 @@ func (c *AnalyticsAdminClient) BatchUpdateUserLinks(ctx context.Context, req *ad } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchUpdateUserLinks[0:len(c.CallOptions.BatchUpdateUserLinks):len(c.CallOptions.BatchUpdateUserLinks)], opts...) + opts = append((*c.CallOptions).BatchUpdateUserLinks[0:len((*c.CallOptions).BatchUpdateUserLinks):len((*c.CallOptions).BatchUpdateUserLinks)], opts...) var resp *adminpb.BatchUpdateUserLinksResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -821,8 +1147,7 @@ func (c *AnalyticsAdminClient) BatchUpdateUserLinks(ctx context.Context, req *ad return resp, nil } -// DeleteUserLink deletes a user link on an account or property. -func (c *AnalyticsAdminClient) DeleteUserLink(ctx context.Context, req *adminpb.DeleteUserLinkRequest, opts ...gax.CallOption) error { +func (c *analyticsAdminGRPCClient) DeleteUserLink(ctx context.Context, req *adminpb.DeleteUserLinkRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -830,7 +1155,7 @@ func (c *AnalyticsAdminClient) DeleteUserLink(ctx context.Context, req *adminpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteUserLink[0:len(c.CallOptions.DeleteUserLink):len(c.CallOptions.DeleteUserLink)], opts...) + opts = append((*c.CallOptions).DeleteUserLink[0:len((*c.CallOptions).DeleteUserLink):len((*c.CallOptions).DeleteUserLink)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.analyticsAdminClient.DeleteUserLink(ctx, req, settings.GRPC...) @@ -839,8 +1164,7 @@ func (c *AnalyticsAdminClient) DeleteUserLink(ctx context.Context, req *adminpb. return err } -// BatchDeleteUserLinks deletes information about multiple users’ links to an account or property. -func (c *AnalyticsAdminClient) BatchDeleteUserLinks(ctx context.Context, req *adminpb.BatchDeleteUserLinksRequest, opts ...gax.CallOption) error { +func (c *analyticsAdminGRPCClient) BatchDeleteUserLinks(ctx context.Context, req *adminpb.BatchDeleteUserLinksRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -848,7 +1172,7 @@ func (c *AnalyticsAdminClient) BatchDeleteUserLinks(ctx context.Context, req *ad } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchDeleteUserLinks[0:len(c.CallOptions.BatchDeleteUserLinks):len(c.CallOptions.BatchDeleteUserLinks)], opts...) + opts = append((*c.CallOptions).BatchDeleteUserLinks[0:len((*c.CallOptions).BatchDeleteUserLinks):len((*c.CallOptions).BatchDeleteUserLinks)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.analyticsAdminClient.BatchDeleteUserLinks(ctx, req, settings.GRPC...) @@ -857,8 +1181,7 @@ func (c *AnalyticsAdminClient) BatchDeleteUserLinks(ctx context.Context, req *ad return err } -// GetWebDataStream lookup for a single WebDataStream -func (c *AnalyticsAdminClient) GetWebDataStream(ctx context.Context, req *adminpb.GetWebDataStreamRequest, opts ...gax.CallOption) (*adminpb.WebDataStream, error) { +func (c *analyticsAdminGRPCClient) GetWebDataStream(ctx context.Context, req *adminpb.GetWebDataStreamRequest, opts ...gax.CallOption) (*adminpb.WebDataStream, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -866,7 +1189,7 @@ func (c *AnalyticsAdminClient) GetWebDataStream(ctx context.Context, req *adminp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetWebDataStream[0:len(c.CallOptions.GetWebDataStream):len(c.CallOptions.GetWebDataStream)], opts...) + opts = append((*c.CallOptions).GetWebDataStream[0:len((*c.CallOptions).GetWebDataStream):len((*c.CallOptions).GetWebDataStream)], opts...) var resp *adminpb.WebDataStream err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -879,8 +1202,7 @@ func (c *AnalyticsAdminClient) GetWebDataStream(ctx context.Context, req *adminp return resp, nil } -// DeleteWebDataStream deletes a web stream on a property. -func (c *AnalyticsAdminClient) DeleteWebDataStream(ctx context.Context, req *adminpb.DeleteWebDataStreamRequest, opts ...gax.CallOption) error { +func (c *analyticsAdminGRPCClient) DeleteWebDataStream(ctx context.Context, req *adminpb.DeleteWebDataStreamRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -888,7 +1210,7 @@ func (c *AnalyticsAdminClient) DeleteWebDataStream(ctx context.Context, req *adm } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteWebDataStream[0:len(c.CallOptions.DeleteWebDataStream):len(c.CallOptions.DeleteWebDataStream)], opts...) + opts = append((*c.CallOptions).DeleteWebDataStream[0:len((*c.CallOptions).DeleteWebDataStream):len((*c.CallOptions).DeleteWebDataStream)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.analyticsAdminClient.DeleteWebDataStream(ctx, req, settings.GRPC...) @@ -897,8 +1219,7 @@ func (c *AnalyticsAdminClient) DeleteWebDataStream(ctx context.Context, req *adm return err } -// UpdateWebDataStream updates a web stream on a property. -func (c *AnalyticsAdminClient) UpdateWebDataStream(ctx context.Context, req *adminpb.UpdateWebDataStreamRequest, opts ...gax.CallOption) (*adminpb.WebDataStream, error) { +func (c *analyticsAdminGRPCClient) UpdateWebDataStream(ctx context.Context, req *adminpb.UpdateWebDataStreamRequest, opts ...gax.CallOption) (*adminpb.WebDataStream, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -906,7 +1227,7 @@ func (c *AnalyticsAdminClient) UpdateWebDataStream(ctx context.Context, req *adm } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "web_data_stream.name", url.QueryEscape(req.GetWebDataStream().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateWebDataStream[0:len(c.CallOptions.UpdateWebDataStream):len(c.CallOptions.UpdateWebDataStream)], opts...) + opts = append((*c.CallOptions).UpdateWebDataStream[0:len((*c.CallOptions).UpdateWebDataStream):len((*c.CallOptions).UpdateWebDataStream)], opts...) var resp *adminpb.WebDataStream err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -919,8 +1240,7 @@ func (c *AnalyticsAdminClient) UpdateWebDataStream(ctx context.Context, req *adm return resp, nil } -// CreateWebDataStream creates a web stream with the specified location and attributes. -func (c *AnalyticsAdminClient) CreateWebDataStream(ctx context.Context, req *adminpb.CreateWebDataStreamRequest, opts ...gax.CallOption) (*adminpb.WebDataStream, error) { +func (c *analyticsAdminGRPCClient) CreateWebDataStream(ctx context.Context, req *adminpb.CreateWebDataStreamRequest, opts ...gax.CallOption) (*adminpb.WebDataStream, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -928,7 +1248,7 @@ func (c *AnalyticsAdminClient) CreateWebDataStream(ctx context.Context, req *adm } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateWebDataStream[0:len(c.CallOptions.CreateWebDataStream):len(c.CallOptions.CreateWebDataStream)], opts...) + opts = append((*c.CallOptions).CreateWebDataStream[0:len((*c.CallOptions).CreateWebDataStream):len((*c.CallOptions).CreateWebDataStream)], opts...) var resp *adminpb.WebDataStream err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -941,14 +1261,10 @@ func (c *AnalyticsAdminClient) CreateWebDataStream(ctx context.Context, req *adm return resp, nil } -// ListWebDataStreams returns child web data streams under the specified parent property. -// -// Web data streams will be excluded if the caller does not have access. -// Returns an empty list if no relevant web data streams are found. -func (c *AnalyticsAdminClient) ListWebDataStreams(ctx context.Context, req *adminpb.ListWebDataStreamsRequest, opts ...gax.CallOption) *WebDataStreamIterator { +func (c *analyticsAdminGRPCClient) ListWebDataStreams(ctx context.Context, req *adminpb.ListWebDataStreamsRequest, opts ...gax.CallOption) *WebDataStreamIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListWebDataStreams[0:len(c.CallOptions.ListWebDataStreams):len(c.CallOptions.ListWebDataStreams)], opts...) + opts = append((*c.CallOptions).ListWebDataStreams[0:len((*c.CallOptions).ListWebDataStreams):len((*c.CallOptions).ListWebDataStreams)], opts...) it := &WebDataStreamIterator{} req = proto.Clone(req).(*adminpb.ListWebDataStreamsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*adminpb.WebDataStream, string, error) { @@ -985,8 +1301,7 @@ func (c *AnalyticsAdminClient) ListWebDataStreams(ctx context.Context, req *admi return it } -// GetIosAppDataStream lookup for a single IosAppDataStream -func (c *AnalyticsAdminClient) GetIosAppDataStream(ctx context.Context, req *adminpb.GetIosAppDataStreamRequest, opts ...gax.CallOption) (*adminpb.IosAppDataStream, error) { +func (c *analyticsAdminGRPCClient) GetIosAppDataStream(ctx context.Context, req *adminpb.GetIosAppDataStreamRequest, opts ...gax.CallOption) (*adminpb.IosAppDataStream, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -994,7 +1309,7 @@ func (c *AnalyticsAdminClient) GetIosAppDataStream(ctx context.Context, req *adm } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIosAppDataStream[0:len(c.CallOptions.GetIosAppDataStream):len(c.CallOptions.GetIosAppDataStream)], opts...) + opts = append((*c.CallOptions).GetIosAppDataStream[0:len((*c.CallOptions).GetIosAppDataStream):len((*c.CallOptions).GetIosAppDataStream)], opts...) var resp *adminpb.IosAppDataStream err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1007,8 +1322,7 @@ func (c *AnalyticsAdminClient) GetIosAppDataStream(ctx context.Context, req *adm return resp, nil } -// DeleteIosAppDataStream deletes an iOS app stream on a property. -func (c *AnalyticsAdminClient) DeleteIosAppDataStream(ctx context.Context, req *adminpb.DeleteIosAppDataStreamRequest, opts ...gax.CallOption) error { +func (c *analyticsAdminGRPCClient) DeleteIosAppDataStream(ctx context.Context, req *adminpb.DeleteIosAppDataStreamRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1016,7 +1330,7 @@ func (c *AnalyticsAdminClient) DeleteIosAppDataStream(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteIosAppDataStream[0:len(c.CallOptions.DeleteIosAppDataStream):len(c.CallOptions.DeleteIosAppDataStream)], opts...) + opts = append((*c.CallOptions).DeleteIosAppDataStream[0:len((*c.CallOptions).DeleteIosAppDataStream):len((*c.CallOptions).DeleteIosAppDataStream)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.analyticsAdminClient.DeleteIosAppDataStream(ctx, req, settings.GRPC...) @@ -1025,8 +1339,7 @@ func (c *AnalyticsAdminClient) DeleteIosAppDataStream(ctx context.Context, req * return err } -// UpdateIosAppDataStream updates an iOS app stream on a property. -func (c *AnalyticsAdminClient) UpdateIosAppDataStream(ctx context.Context, req *adminpb.UpdateIosAppDataStreamRequest, opts ...gax.CallOption) (*adminpb.IosAppDataStream, error) { +func (c *analyticsAdminGRPCClient) UpdateIosAppDataStream(ctx context.Context, req *adminpb.UpdateIosAppDataStreamRequest, opts ...gax.CallOption) (*adminpb.IosAppDataStream, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1034,7 +1347,7 @@ func (c *AnalyticsAdminClient) UpdateIosAppDataStream(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "ios_app_data_stream.name", url.QueryEscape(req.GetIosAppDataStream().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateIosAppDataStream[0:len(c.CallOptions.UpdateIosAppDataStream):len(c.CallOptions.UpdateIosAppDataStream)], opts...) + opts = append((*c.CallOptions).UpdateIosAppDataStream[0:len((*c.CallOptions).UpdateIosAppDataStream):len((*c.CallOptions).UpdateIosAppDataStream)], opts...) var resp *adminpb.IosAppDataStream err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1047,14 +1360,10 @@ func (c *AnalyticsAdminClient) UpdateIosAppDataStream(ctx context.Context, req * return resp, nil } -// ListIosAppDataStreams returns child iOS app data streams under the specified parent property. -// -// iOS app data streams will be excluded if the caller does not have access. -// Returns an empty list if no relevant iOS app data streams are found. -func (c *AnalyticsAdminClient) ListIosAppDataStreams(ctx context.Context, req *adminpb.ListIosAppDataStreamsRequest, opts ...gax.CallOption) *IosAppDataStreamIterator { +func (c *analyticsAdminGRPCClient) ListIosAppDataStreams(ctx context.Context, req *adminpb.ListIosAppDataStreamsRequest, opts ...gax.CallOption) *IosAppDataStreamIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListIosAppDataStreams[0:len(c.CallOptions.ListIosAppDataStreams):len(c.CallOptions.ListIosAppDataStreams)], opts...) + opts = append((*c.CallOptions).ListIosAppDataStreams[0:len((*c.CallOptions).ListIosAppDataStreams):len((*c.CallOptions).ListIosAppDataStreams)], opts...) it := &IosAppDataStreamIterator{} req = proto.Clone(req).(*adminpb.ListIosAppDataStreamsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*adminpb.IosAppDataStream, string, error) { @@ -1091,8 +1400,7 @@ func (c *AnalyticsAdminClient) ListIosAppDataStreams(ctx context.Context, req *a return it } -// GetAndroidAppDataStream lookup for a single AndroidAppDataStream -func (c *AnalyticsAdminClient) GetAndroidAppDataStream(ctx context.Context, req *adminpb.GetAndroidAppDataStreamRequest, opts ...gax.CallOption) (*adminpb.AndroidAppDataStream, error) { +func (c *analyticsAdminGRPCClient) GetAndroidAppDataStream(ctx context.Context, req *adminpb.GetAndroidAppDataStreamRequest, opts ...gax.CallOption) (*adminpb.AndroidAppDataStream, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1100,7 +1408,7 @@ func (c *AnalyticsAdminClient) GetAndroidAppDataStream(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetAndroidAppDataStream[0:len(c.CallOptions.GetAndroidAppDataStream):len(c.CallOptions.GetAndroidAppDataStream)], opts...) + opts = append((*c.CallOptions).GetAndroidAppDataStream[0:len((*c.CallOptions).GetAndroidAppDataStream):len((*c.CallOptions).GetAndroidAppDataStream)], opts...) var resp *adminpb.AndroidAppDataStream err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1113,8 +1421,7 @@ func (c *AnalyticsAdminClient) GetAndroidAppDataStream(ctx context.Context, req return resp, nil } -// DeleteAndroidAppDataStream deletes an android app stream on a property. -func (c *AnalyticsAdminClient) DeleteAndroidAppDataStream(ctx context.Context, req *adminpb.DeleteAndroidAppDataStreamRequest, opts ...gax.CallOption) error { +func (c *analyticsAdminGRPCClient) DeleteAndroidAppDataStream(ctx context.Context, req *adminpb.DeleteAndroidAppDataStreamRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1122,7 +1429,7 @@ func (c *AnalyticsAdminClient) DeleteAndroidAppDataStream(ctx context.Context, r } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteAndroidAppDataStream[0:len(c.CallOptions.DeleteAndroidAppDataStream):len(c.CallOptions.DeleteAndroidAppDataStream)], opts...) + opts = append((*c.CallOptions).DeleteAndroidAppDataStream[0:len((*c.CallOptions).DeleteAndroidAppDataStream):len((*c.CallOptions).DeleteAndroidAppDataStream)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.analyticsAdminClient.DeleteAndroidAppDataStream(ctx, req, settings.GRPC...) @@ -1131,8 +1438,7 @@ func (c *AnalyticsAdminClient) DeleteAndroidAppDataStream(ctx context.Context, r return err } -// UpdateAndroidAppDataStream updates an android app stream on a property. -func (c *AnalyticsAdminClient) UpdateAndroidAppDataStream(ctx context.Context, req *adminpb.UpdateAndroidAppDataStreamRequest, opts ...gax.CallOption) (*adminpb.AndroidAppDataStream, error) { +func (c *analyticsAdminGRPCClient) UpdateAndroidAppDataStream(ctx context.Context, req *adminpb.UpdateAndroidAppDataStreamRequest, opts ...gax.CallOption) (*adminpb.AndroidAppDataStream, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1140,7 +1446,7 @@ func (c *AnalyticsAdminClient) UpdateAndroidAppDataStream(ctx context.Context, r } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "android_app_data_stream.name", url.QueryEscape(req.GetAndroidAppDataStream().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateAndroidAppDataStream[0:len(c.CallOptions.UpdateAndroidAppDataStream):len(c.CallOptions.UpdateAndroidAppDataStream)], opts...) + opts = append((*c.CallOptions).UpdateAndroidAppDataStream[0:len((*c.CallOptions).UpdateAndroidAppDataStream):len((*c.CallOptions).UpdateAndroidAppDataStream)], opts...) var resp *adminpb.AndroidAppDataStream err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1153,14 +1459,10 @@ func (c *AnalyticsAdminClient) UpdateAndroidAppDataStream(ctx context.Context, r return resp, nil } -// ListAndroidAppDataStreams returns child android app streams under the specified parent property. -// -// Android app streams will be excluded if the caller does not have access. -// Returns an empty list if no relevant android app streams are found. -func (c *AnalyticsAdminClient) ListAndroidAppDataStreams(ctx context.Context, req *adminpb.ListAndroidAppDataStreamsRequest, opts ...gax.CallOption) *AndroidAppDataStreamIterator { +func (c *analyticsAdminGRPCClient) ListAndroidAppDataStreams(ctx context.Context, req *adminpb.ListAndroidAppDataStreamsRequest, opts ...gax.CallOption) *AndroidAppDataStreamIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAndroidAppDataStreams[0:len(c.CallOptions.ListAndroidAppDataStreams):len(c.CallOptions.ListAndroidAppDataStreams)], opts...) + opts = append((*c.CallOptions).ListAndroidAppDataStreams[0:len((*c.CallOptions).ListAndroidAppDataStreams):len((*c.CallOptions).ListAndroidAppDataStreams)], opts...) it := &AndroidAppDataStreamIterator{} req = proto.Clone(req).(*adminpb.ListAndroidAppDataStreamsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*adminpb.AndroidAppDataStream, string, error) { @@ -1197,10 +1499,7 @@ func (c *AnalyticsAdminClient) ListAndroidAppDataStreams(ctx context.Context, re return it } -// GetEnhancedMeasurementSettings returns the singleton enhanced measurement settings for this web stream. -// Note that the stream must enable enhanced measurement for these settings to -// take effect. -func (c *AnalyticsAdminClient) GetEnhancedMeasurementSettings(ctx context.Context, req *adminpb.GetEnhancedMeasurementSettingsRequest, opts ...gax.CallOption) (*adminpb.EnhancedMeasurementSettings, error) { +func (c *analyticsAdminGRPCClient) GetEnhancedMeasurementSettings(ctx context.Context, req *adminpb.GetEnhancedMeasurementSettingsRequest, opts ...gax.CallOption) (*adminpb.EnhancedMeasurementSettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1208,7 +1507,7 @@ func (c *AnalyticsAdminClient) GetEnhancedMeasurementSettings(ctx context.Contex } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEnhancedMeasurementSettings[0:len(c.CallOptions.GetEnhancedMeasurementSettings):len(c.CallOptions.GetEnhancedMeasurementSettings)], opts...) + opts = append((*c.CallOptions).GetEnhancedMeasurementSettings[0:len((*c.CallOptions).GetEnhancedMeasurementSettings):len((*c.CallOptions).GetEnhancedMeasurementSettings)], opts...) var resp *adminpb.EnhancedMeasurementSettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1221,10 +1520,7 @@ func (c *AnalyticsAdminClient) GetEnhancedMeasurementSettings(ctx context.Contex return resp, nil } -// UpdateEnhancedMeasurementSettings updates the singleton enhanced measurement settings for this web stream. -// Note that the stream must enable enhanced measurement for these settings to -// take effect. -func (c *AnalyticsAdminClient) UpdateEnhancedMeasurementSettings(ctx context.Context, req *adminpb.UpdateEnhancedMeasurementSettingsRequest, opts ...gax.CallOption) (*adminpb.EnhancedMeasurementSettings, error) { +func (c *analyticsAdminGRPCClient) UpdateEnhancedMeasurementSettings(ctx context.Context, req *adminpb.UpdateEnhancedMeasurementSettingsRequest, opts ...gax.CallOption) (*adminpb.EnhancedMeasurementSettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1232,7 +1528,7 @@ func (c *AnalyticsAdminClient) UpdateEnhancedMeasurementSettings(ctx context.Con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "enhanced_measurement_settings.name", url.QueryEscape(req.GetEnhancedMeasurementSettings().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateEnhancedMeasurementSettings[0:len(c.CallOptions.UpdateEnhancedMeasurementSettings):len(c.CallOptions.UpdateEnhancedMeasurementSettings)], opts...) + opts = append((*c.CallOptions).UpdateEnhancedMeasurementSettings[0:len((*c.CallOptions).UpdateEnhancedMeasurementSettings):len((*c.CallOptions).UpdateEnhancedMeasurementSettings)], opts...) var resp *adminpb.EnhancedMeasurementSettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1245,10 +1541,7 @@ func (c *AnalyticsAdminClient) UpdateEnhancedMeasurementSettings(ctx context.Con return resp, nil } -// CreateFirebaseLink creates a FirebaseLink. -// -// Properties can have at most one FirebaseLink. -func (c *AnalyticsAdminClient) CreateFirebaseLink(ctx context.Context, req *adminpb.CreateFirebaseLinkRequest, opts ...gax.CallOption) (*adminpb.FirebaseLink, error) { +func (c *analyticsAdminGRPCClient) CreateFirebaseLink(ctx context.Context, req *adminpb.CreateFirebaseLinkRequest, opts ...gax.CallOption) (*adminpb.FirebaseLink, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1256,7 +1549,7 @@ func (c *AnalyticsAdminClient) CreateFirebaseLink(ctx context.Context, req *admi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateFirebaseLink[0:len(c.CallOptions.CreateFirebaseLink):len(c.CallOptions.CreateFirebaseLink)], opts...) + opts = append((*c.CallOptions).CreateFirebaseLink[0:len((*c.CallOptions).CreateFirebaseLink):len((*c.CallOptions).CreateFirebaseLink)], opts...) var resp *adminpb.FirebaseLink err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1269,8 +1562,7 @@ func (c *AnalyticsAdminClient) CreateFirebaseLink(ctx context.Context, req *admi return resp, nil } -// UpdateFirebaseLink updates a FirebaseLink on a property -func (c *AnalyticsAdminClient) UpdateFirebaseLink(ctx context.Context, req *adminpb.UpdateFirebaseLinkRequest, opts ...gax.CallOption) (*adminpb.FirebaseLink, error) { +func (c *analyticsAdminGRPCClient) UpdateFirebaseLink(ctx context.Context, req *adminpb.UpdateFirebaseLinkRequest, opts ...gax.CallOption) (*adminpb.FirebaseLink, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1278,7 +1570,7 @@ func (c *AnalyticsAdminClient) UpdateFirebaseLink(ctx context.Context, req *admi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "firebase_link.name", url.QueryEscape(req.GetFirebaseLink().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateFirebaseLink[0:len(c.CallOptions.UpdateFirebaseLink):len(c.CallOptions.UpdateFirebaseLink)], opts...) + opts = append((*c.CallOptions).UpdateFirebaseLink[0:len((*c.CallOptions).UpdateFirebaseLink):len((*c.CallOptions).UpdateFirebaseLink)], opts...) var resp *adminpb.FirebaseLink err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1291,8 +1583,7 @@ func (c *AnalyticsAdminClient) UpdateFirebaseLink(ctx context.Context, req *admi return resp, nil } -// DeleteFirebaseLink deletes a FirebaseLink on a property -func (c *AnalyticsAdminClient) DeleteFirebaseLink(ctx context.Context, req *adminpb.DeleteFirebaseLinkRequest, opts ...gax.CallOption) error { +func (c *analyticsAdminGRPCClient) DeleteFirebaseLink(ctx context.Context, req *adminpb.DeleteFirebaseLinkRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1300,7 +1591,7 @@ func (c *AnalyticsAdminClient) DeleteFirebaseLink(ctx context.Context, req *admi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteFirebaseLink[0:len(c.CallOptions.DeleteFirebaseLink):len(c.CallOptions.DeleteFirebaseLink)], opts...) + opts = append((*c.CallOptions).DeleteFirebaseLink[0:len((*c.CallOptions).DeleteFirebaseLink):len((*c.CallOptions).DeleteFirebaseLink)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.analyticsAdminClient.DeleteFirebaseLink(ctx, req, settings.GRPC...) @@ -1309,12 +1600,10 @@ func (c *AnalyticsAdminClient) DeleteFirebaseLink(ctx context.Context, req *admi return err } -// ListFirebaseLinks lists FirebaseLinks on a property. -// Properties can have at most one FirebaseLink. -func (c *AnalyticsAdminClient) ListFirebaseLinks(ctx context.Context, req *adminpb.ListFirebaseLinksRequest, opts ...gax.CallOption) *FirebaseLinkIterator { +func (c *analyticsAdminGRPCClient) ListFirebaseLinks(ctx context.Context, req *adminpb.ListFirebaseLinksRequest, opts ...gax.CallOption) *FirebaseLinkIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListFirebaseLinks[0:len(c.CallOptions.ListFirebaseLinks):len(c.CallOptions.ListFirebaseLinks)], opts...) + opts = append((*c.CallOptions).ListFirebaseLinks[0:len((*c.CallOptions).ListFirebaseLinks):len((*c.CallOptions).ListFirebaseLinks)], opts...) it := &FirebaseLinkIterator{} req = proto.Clone(req).(*adminpb.ListFirebaseLinksRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*adminpb.FirebaseLink, string, error) { @@ -1351,9 +1640,7 @@ func (c *AnalyticsAdminClient) ListFirebaseLinks(ctx context.Context, req *admin return it } -// GetGlobalSiteTag returns the Site Tag for the specified web stream. -// Site Tags are immutable singletons. -func (c *AnalyticsAdminClient) GetGlobalSiteTag(ctx context.Context, req *adminpb.GetGlobalSiteTagRequest, opts ...gax.CallOption) (*adminpb.GlobalSiteTag, error) { +func (c *analyticsAdminGRPCClient) GetGlobalSiteTag(ctx context.Context, req *adminpb.GetGlobalSiteTagRequest, opts ...gax.CallOption) (*adminpb.GlobalSiteTag, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1361,7 +1648,7 @@ func (c *AnalyticsAdminClient) GetGlobalSiteTag(ctx context.Context, req *adminp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetGlobalSiteTag[0:len(c.CallOptions.GetGlobalSiteTag):len(c.CallOptions.GetGlobalSiteTag)], opts...) + opts = append((*c.CallOptions).GetGlobalSiteTag[0:len((*c.CallOptions).GetGlobalSiteTag):len((*c.CallOptions).GetGlobalSiteTag)], opts...) var resp *adminpb.GlobalSiteTag err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1374,8 +1661,7 @@ func (c *AnalyticsAdminClient) GetGlobalSiteTag(ctx context.Context, req *adminp return resp, nil } -// CreateGoogleAdsLink creates a GoogleAdsLink. -func (c *AnalyticsAdminClient) CreateGoogleAdsLink(ctx context.Context, req *adminpb.CreateGoogleAdsLinkRequest, opts ...gax.CallOption) (*adminpb.GoogleAdsLink, error) { +func (c *analyticsAdminGRPCClient) CreateGoogleAdsLink(ctx context.Context, req *adminpb.CreateGoogleAdsLinkRequest, opts ...gax.CallOption) (*adminpb.GoogleAdsLink, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1383,7 +1669,7 @@ func (c *AnalyticsAdminClient) CreateGoogleAdsLink(ctx context.Context, req *adm } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateGoogleAdsLink[0:len(c.CallOptions.CreateGoogleAdsLink):len(c.CallOptions.CreateGoogleAdsLink)], opts...) + opts = append((*c.CallOptions).CreateGoogleAdsLink[0:len((*c.CallOptions).CreateGoogleAdsLink):len((*c.CallOptions).CreateGoogleAdsLink)], opts...) var resp *adminpb.GoogleAdsLink err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1396,8 +1682,7 @@ func (c *AnalyticsAdminClient) CreateGoogleAdsLink(ctx context.Context, req *adm return resp, nil } -// UpdateGoogleAdsLink updates a GoogleAdsLink on a property -func (c *AnalyticsAdminClient) UpdateGoogleAdsLink(ctx context.Context, req *adminpb.UpdateGoogleAdsLinkRequest, opts ...gax.CallOption) (*adminpb.GoogleAdsLink, error) { +func (c *analyticsAdminGRPCClient) UpdateGoogleAdsLink(ctx context.Context, req *adminpb.UpdateGoogleAdsLinkRequest, opts ...gax.CallOption) (*adminpb.GoogleAdsLink, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1405,7 +1690,7 @@ func (c *AnalyticsAdminClient) UpdateGoogleAdsLink(ctx context.Context, req *adm } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "google_ads_link.name", url.QueryEscape(req.GetGoogleAdsLink().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateGoogleAdsLink[0:len(c.CallOptions.UpdateGoogleAdsLink):len(c.CallOptions.UpdateGoogleAdsLink)], opts...) + opts = append((*c.CallOptions).UpdateGoogleAdsLink[0:len((*c.CallOptions).UpdateGoogleAdsLink):len((*c.CallOptions).UpdateGoogleAdsLink)], opts...) var resp *adminpb.GoogleAdsLink err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1418,8 +1703,7 @@ func (c *AnalyticsAdminClient) UpdateGoogleAdsLink(ctx context.Context, req *adm return resp, nil } -// DeleteGoogleAdsLink deletes a GoogleAdsLink on a property -func (c *AnalyticsAdminClient) DeleteGoogleAdsLink(ctx context.Context, req *adminpb.DeleteGoogleAdsLinkRequest, opts ...gax.CallOption) error { +func (c *analyticsAdminGRPCClient) DeleteGoogleAdsLink(ctx context.Context, req *adminpb.DeleteGoogleAdsLinkRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1427,7 +1711,7 @@ func (c *AnalyticsAdminClient) DeleteGoogleAdsLink(ctx context.Context, req *adm } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteGoogleAdsLink[0:len(c.CallOptions.DeleteGoogleAdsLink):len(c.CallOptions.DeleteGoogleAdsLink)], opts...) + opts = append((*c.CallOptions).DeleteGoogleAdsLink[0:len((*c.CallOptions).DeleteGoogleAdsLink):len((*c.CallOptions).DeleteGoogleAdsLink)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.analyticsAdminClient.DeleteGoogleAdsLink(ctx, req, settings.GRPC...) @@ -1436,11 +1720,10 @@ func (c *AnalyticsAdminClient) DeleteGoogleAdsLink(ctx context.Context, req *adm return err } -// ListGoogleAdsLinks lists GoogleAdsLinks on a property. -func (c *AnalyticsAdminClient) ListGoogleAdsLinks(ctx context.Context, req *adminpb.ListGoogleAdsLinksRequest, opts ...gax.CallOption) *GoogleAdsLinkIterator { +func (c *analyticsAdminGRPCClient) ListGoogleAdsLinks(ctx context.Context, req *adminpb.ListGoogleAdsLinksRequest, opts ...gax.CallOption) *GoogleAdsLinkIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListGoogleAdsLinks[0:len(c.CallOptions.ListGoogleAdsLinks):len(c.CallOptions.ListGoogleAdsLinks)], opts...) + opts = append((*c.CallOptions).ListGoogleAdsLinks[0:len((*c.CallOptions).ListGoogleAdsLinks):len((*c.CallOptions).ListGoogleAdsLinks)], opts...) it := &GoogleAdsLinkIterator{} req = proto.Clone(req).(*adminpb.ListGoogleAdsLinksRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*adminpb.GoogleAdsLink, string, error) { @@ -1477,9 +1760,7 @@ func (c *AnalyticsAdminClient) ListGoogleAdsLinks(ctx context.Context, req *admi return it } -// GetDataSharingSettings get data sharing settings on an account. -// Data sharing settings are singletons. -func (c *AnalyticsAdminClient) GetDataSharingSettings(ctx context.Context, req *adminpb.GetDataSharingSettingsRequest, opts ...gax.CallOption) (*adminpb.DataSharingSettings, error) { +func (c *analyticsAdminGRPCClient) GetDataSharingSettings(ctx context.Context, req *adminpb.GetDataSharingSettingsRequest, opts ...gax.CallOption) (*adminpb.DataSharingSettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1487,7 +1768,7 @@ func (c *AnalyticsAdminClient) GetDataSharingSettings(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetDataSharingSettings[0:len(c.CallOptions.GetDataSharingSettings):len(c.CallOptions.GetDataSharingSettings)], opts...) + opts = append((*c.CallOptions).GetDataSharingSettings[0:len((*c.CallOptions).GetDataSharingSettings):len((*c.CallOptions).GetDataSharingSettings)], opts...) var resp *adminpb.DataSharingSettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1500,12 +1781,10 @@ func (c *AnalyticsAdminClient) GetDataSharingSettings(ctx context.Context, req * return resp, nil } -// SearchChangeHistoryEvents searches through all changes to an account or its children given the -// specified set of filters. -func (c *AnalyticsAdminClient) SearchChangeHistoryEvents(ctx context.Context, req *adminpb.SearchChangeHistoryEventsRequest, opts ...gax.CallOption) *ChangeHistoryEventIterator { +func (c *analyticsAdminGRPCClient) SearchChangeHistoryEvents(ctx context.Context, req *adminpb.SearchChangeHistoryEventsRequest, opts ...gax.CallOption) *ChangeHistoryEventIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "account", url.QueryEscape(req.GetAccount()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SearchChangeHistoryEvents[0:len(c.CallOptions.SearchChangeHistoryEvents):len(c.CallOptions.SearchChangeHistoryEvents)], opts...) + opts = append((*c.CallOptions).SearchChangeHistoryEvents[0:len((*c.CallOptions).SearchChangeHistoryEvents):len((*c.CallOptions).SearchChangeHistoryEvents)], opts...) it := &ChangeHistoryEventIterator{} req = proto.Clone(req).(*adminpb.SearchChangeHistoryEventsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*adminpb.ChangeHistoryEvent, string, error) { diff --git a/analytics/admin/apiv1alpha/analytics_admin_client_example_test.go b/analytics/admin/apiv1alpha/analytics_admin_client_example_test.go index d7fdb2b4395a..708f03276dbe 100644 --- a/analytics/admin/apiv1alpha/analytics_admin_client_example_test.go +++ b/analytics/admin/apiv1alpha/analytics_admin_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewAnalyticsAdminClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleAnalyticsAdminClient_GetAccount() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetAccountRequest{ // TODO: Fill request struct fields. @@ -55,14 +56,12 @@ func ExampleAnalyticsAdminClient_GetAccount() { } func ExampleAnalyticsAdminClient_ListAccounts() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListAccountsRequest{ // TODO: Fill request struct fields. @@ -87,6 +86,7 @@ func ExampleAnalyticsAdminClient_DeleteAccount() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteAccountRequest{ // TODO: Fill request struct fields. @@ -98,13 +98,12 @@ func ExampleAnalyticsAdminClient_DeleteAccount() { } func ExampleAnalyticsAdminClient_UpdateAccount() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateAccountRequest{ // TODO: Fill request struct fields. @@ -118,13 +117,12 @@ func ExampleAnalyticsAdminClient_UpdateAccount() { } func ExampleAnalyticsAdminClient_ProvisionAccountTicket() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ProvisionAccountTicketRequest{ // TODO: Fill request struct fields. @@ -138,14 +136,12 @@ func ExampleAnalyticsAdminClient_ProvisionAccountTicket() { } func ExampleAnalyticsAdminClient_ListAccountSummaries() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListAccountSummariesRequest{ // TODO: Fill request struct fields. @@ -165,13 +161,12 @@ func ExampleAnalyticsAdminClient_ListAccountSummaries() { } func ExampleAnalyticsAdminClient_GetProperty() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetPropertyRequest{ // TODO: Fill request struct fields. @@ -185,14 +180,12 @@ func ExampleAnalyticsAdminClient_GetProperty() { } func ExampleAnalyticsAdminClient_ListProperties() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListPropertiesRequest{ // TODO: Fill request struct fields. @@ -212,13 +205,12 @@ func ExampleAnalyticsAdminClient_ListProperties() { } func ExampleAnalyticsAdminClient_CreateProperty() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.CreatePropertyRequest{ // TODO: Fill request struct fields. @@ -232,13 +224,12 @@ func ExampleAnalyticsAdminClient_CreateProperty() { } func ExampleAnalyticsAdminClient_DeleteProperty() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeletePropertyRequest{ // TODO: Fill request struct fields. @@ -252,13 +243,12 @@ func ExampleAnalyticsAdminClient_DeleteProperty() { } func ExampleAnalyticsAdminClient_UpdateProperty() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdatePropertyRequest{ // TODO: Fill request struct fields. @@ -272,13 +262,12 @@ func ExampleAnalyticsAdminClient_UpdateProperty() { } func ExampleAnalyticsAdminClient_GetUserLink() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetUserLinkRequest{ // TODO: Fill request struct fields. @@ -292,13 +281,12 @@ func ExampleAnalyticsAdminClient_GetUserLink() { } func ExampleAnalyticsAdminClient_BatchGetUserLinks() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.BatchGetUserLinksRequest{ // TODO: Fill request struct fields. @@ -312,14 +300,12 @@ func ExampleAnalyticsAdminClient_BatchGetUserLinks() { } func ExampleAnalyticsAdminClient_ListUserLinks() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListUserLinksRequest{ // TODO: Fill request struct fields. @@ -339,14 +325,12 @@ func ExampleAnalyticsAdminClient_ListUserLinks() { } func ExampleAnalyticsAdminClient_AuditUserLinks() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.AuditUserLinksRequest{ // TODO: Fill request struct fields. @@ -366,13 +350,12 @@ func ExampleAnalyticsAdminClient_AuditUserLinks() { } func ExampleAnalyticsAdminClient_CreateUserLink() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.CreateUserLinkRequest{ // TODO: Fill request struct fields. @@ -386,13 +369,12 @@ func ExampleAnalyticsAdminClient_CreateUserLink() { } func ExampleAnalyticsAdminClient_BatchCreateUserLinks() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.BatchCreateUserLinksRequest{ // TODO: Fill request struct fields. @@ -406,13 +388,12 @@ func ExampleAnalyticsAdminClient_BatchCreateUserLinks() { } func ExampleAnalyticsAdminClient_UpdateUserLink() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateUserLinkRequest{ // TODO: Fill request struct fields. @@ -426,13 +407,12 @@ func ExampleAnalyticsAdminClient_UpdateUserLink() { } func ExampleAnalyticsAdminClient_BatchUpdateUserLinks() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.BatchUpdateUserLinksRequest{ // TODO: Fill request struct fields. @@ -451,6 +431,7 @@ func ExampleAnalyticsAdminClient_DeleteUserLink() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteUserLinkRequest{ // TODO: Fill request struct fields. @@ -467,6 +448,7 @@ func ExampleAnalyticsAdminClient_BatchDeleteUserLinks() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.BatchDeleteUserLinksRequest{ // TODO: Fill request struct fields. @@ -478,13 +460,12 @@ func ExampleAnalyticsAdminClient_BatchDeleteUserLinks() { } func ExampleAnalyticsAdminClient_GetWebDataStream() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetWebDataStreamRequest{ // TODO: Fill request struct fields. @@ -503,6 +484,7 @@ func ExampleAnalyticsAdminClient_DeleteWebDataStream() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteWebDataStreamRequest{ // TODO: Fill request struct fields. @@ -514,13 +496,12 @@ func ExampleAnalyticsAdminClient_DeleteWebDataStream() { } func ExampleAnalyticsAdminClient_UpdateWebDataStream() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateWebDataStreamRequest{ // TODO: Fill request struct fields. @@ -534,13 +515,12 @@ func ExampleAnalyticsAdminClient_UpdateWebDataStream() { } func ExampleAnalyticsAdminClient_CreateWebDataStream() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.CreateWebDataStreamRequest{ // TODO: Fill request struct fields. @@ -554,14 +534,12 @@ func ExampleAnalyticsAdminClient_CreateWebDataStream() { } func ExampleAnalyticsAdminClient_ListWebDataStreams() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListWebDataStreamsRequest{ // TODO: Fill request struct fields. @@ -581,13 +559,12 @@ func ExampleAnalyticsAdminClient_ListWebDataStreams() { } func ExampleAnalyticsAdminClient_GetIosAppDataStream() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetIosAppDataStreamRequest{ // TODO: Fill request struct fields. @@ -606,6 +583,7 @@ func ExampleAnalyticsAdminClient_DeleteIosAppDataStream() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteIosAppDataStreamRequest{ // TODO: Fill request struct fields. @@ -617,13 +595,12 @@ func ExampleAnalyticsAdminClient_DeleteIosAppDataStream() { } func ExampleAnalyticsAdminClient_UpdateIosAppDataStream() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateIosAppDataStreamRequest{ // TODO: Fill request struct fields. @@ -637,14 +614,12 @@ func ExampleAnalyticsAdminClient_UpdateIosAppDataStream() { } func ExampleAnalyticsAdminClient_ListIosAppDataStreams() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListIosAppDataStreamsRequest{ // TODO: Fill request struct fields. @@ -664,13 +639,12 @@ func ExampleAnalyticsAdminClient_ListIosAppDataStreams() { } func ExampleAnalyticsAdminClient_GetAndroidAppDataStream() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetAndroidAppDataStreamRequest{ // TODO: Fill request struct fields. @@ -689,6 +663,7 @@ func ExampleAnalyticsAdminClient_DeleteAndroidAppDataStream() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteAndroidAppDataStreamRequest{ // TODO: Fill request struct fields. @@ -700,13 +675,12 @@ func ExampleAnalyticsAdminClient_DeleteAndroidAppDataStream() { } func ExampleAnalyticsAdminClient_UpdateAndroidAppDataStream() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateAndroidAppDataStreamRequest{ // TODO: Fill request struct fields. @@ -720,14 +694,12 @@ func ExampleAnalyticsAdminClient_UpdateAndroidAppDataStream() { } func ExampleAnalyticsAdminClient_ListAndroidAppDataStreams() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListAndroidAppDataStreamsRequest{ // TODO: Fill request struct fields. @@ -747,13 +719,12 @@ func ExampleAnalyticsAdminClient_ListAndroidAppDataStreams() { } func ExampleAnalyticsAdminClient_GetEnhancedMeasurementSettings() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetEnhancedMeasurementSettingsRequest{ // TODO: Fill request struct fields. @@ -767,13 +738,12 @@ func ExampleAnalyticsAdminClient_GetEnhancedMeasurementSettings() { } func ExampleAnalyticsAdminClient_UpdateEnhancedMeasurementSettings() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateEnhancedMeasurementSettingsRequest{ // TODO: Fill request struct fields. @@ -787,13 +757,12 @@ func ExampleAnalyticsAdminClient_UpdateEnhancedMeasurementSettings() { } func ExampleAnalyticsAdminClient_CreateFirebaseLink() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.CreateFirebaseLinkRequest{ // TODO: Fill request struct fields. @@ -807,13 +776,12 @@ func ExampleAnalyticsAdminClient_CreateFirebaseLink() { } func ExampleAnalyticsAdminClient_UpdateFirebaseLink() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateFirebaseLinkRequest{ // TODO: Fill request struct fields. @@ -832,6 +800,7 @@ func ExampleAnalyticsAdminClient_DeleteFirebaseLink() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteFirebaseLinkRequest{ // TODO: Fill request struct fields. @@ -843,14 +812,12 @@ func ExampleAnalyticsAdminClient_DeleteFirebaseLink() { } func ExampleAnalyticsAdminClient_ListFirebaseLinks() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListFirebaseLinksRequest{ // TODO: Fill request struct fields. @@ -870,13 +837,12 @@ func ExampleAnalyticsAdminClient_ListFirebaseLinks() { } func ExampleAnalyticsAdminClient_GetGlobalSiteTag() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetGlobalSiteTagRequest{ // TODO: Fill request struct fields. @@ -890,13 +856,12 @@ func ExampleAnalyticsAdminClient_GetGlobalSiteTag() { } func ExampleAnalyticsAdminClient_CreateGoogleAdsLink() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.CreateGoogleAdsLinkRequest{ // TODO: Fill request struct fields. @@ -910,13 +875,12 @@ func ExampleAnalyticsAdminClient_CreateGoogleAdsLink() { } func ExampleAnalyticsAdminClient_UpdateGoogleAdsLink() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateGoogleAdsLinkRequest{ // TODO: Fill request struct fields. @@ -935,6 +899,7 @@ func ExampleAnalyticsAdminClient_DeleteGoogleAdsLink() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteGoogleAdsLinkRequest{ // TODO: Fill request struct fields. @@ -946,14 +911,12 @@ func ExampleAnalyticsAdminClient_DeleteGoogleAdsLink() { } func ExampleAnalyticsAdminClient_ListGoogleAdsLinks() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListGoogleAdsLinksRequest{ // TODO: Fill request struct fields. @@ -973,13 +936,12 @@ func ExampleAnalyticsAdminClient_ListGoogleAdsLinks() { } func ExampleAnalyticsAdminClient_GetDataSharingSettings() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetDataSharingSettingsRequest{ // TODO: Fill request struct fields. @@ -993,14 +955,12 @@ func ExampleAnalyticsAdminClient_GetDataSharingSettings() { } func ExampleAnalyticsAdminClient_SearchChangeHistoryEvents() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.SearchChangeHistoryEventsRequest{ // TODO: Fill request struct fields. diff --git a/analytics/admin/apiv1alpha/doc.go b/analytics/admin/apiv1alpha/doc.go index c3e007864496..4af05d1a2e72 100644 --- a/analytics/admin/apiv1alpha/doc.go +++ b/analytics/admin/apiv1alpha/doc.go @@ -17,6 +17,8 @@ // Package admin is an auto-generated package for the // Google Analytics Admin API. // +// NOTE: This package is in alpha. It is not stable, and is likely to change. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -26,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package admin // import "cloud.google.com/go/analytics/admin/apiv1alpha" import ( @@ -46,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/analytics/data/apiv1alpha/alpha_analytics_data_client.go b/analytics/data/apiv1alpha/alpha_analytics_data_client.go index 004db29e6b40..cd84bf3737cc 100644 --- a/analytics/data/apiv1alpha/alpha_analytics_data_client.go +++ b/analytics/data/apiv1alpha/alpha_analytics_data_client.go @@ -45,7 +45,7 @@ type AlphaAnalyticsDataCallOptions struct { RunRealtimeReport []gax.CallOption } -func defaultAlphaAnalyticsDataClientOptions() []option.ClientOption { +func defaultAlphaAnalyticsDataGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("analyticsdata.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("analyticsdata.mtls.googleapis.com:443"), @@ -88,32 +88,132 @@ func defaultAlphaAnalyticsDataCallOptions() *AlphaAnalyticsDataCallOptions { } } +// internalAlphaAnalyticsDataClient is an interface that defines the methods availaible from Google Analytics Data API. +type internalAlphaAnalyticsDataClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + RunReport(context.Context, *datapb.RunReportRequest, ...gax.CallOption) (*datapb.RunReportResponse, error) + RunPivotReport(context.Context, *datapb.RunPivotReportRequest, ...gax.CallOption) (*datapb.RunPivotReportResponse, error) + BatchRunReports(context.Context, *datapb.BatchRunReportsRequest, ...gax.CallOption) (*datapb.BatchRunReportsResponse, error) + BatchRunPivotReports(context.Context, *datapb.BatchRunPivotReportsRequest, ...gax.CallOption) (*datapb.BatchRunPivotReportsResponse, error) + GetMetadata(context.Context, *datapb.GetMetadataRequest, ...gax.CallOption) (*datapb.Metadata, error) + RunRealtimeReport(context.Context, *datapb.RunRealtimeReportRequest, ...gax.CallOption) (*datapb.RunRealtimeReportResponse, error) +} + // AlphaAnalyticsDataClient is a client for interacting with Google Analytics Data API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Google Analytics reporting data service. type AlphaAnalyticsDataClient struct { + // The internal transport-dependent client. + internalClient internalAlphaAnalyticsDataClient + + // The call options for this service. + CallOptions *AlphaAnalyticsDataCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *AlphaAnalyticsDataClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *AlphaAnalyticsDataClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *AlphaAnalyticsDataClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// RunReport returns a customized report of your Google Analytics event data. Reports +// contain statistics derived from data collected by the Google Analytics +// tracking code. The data returned from the API is as a table with columns +// for the requested dimensions and metrics. Metrics are individual +// measurements of user activity on your property, such as active users or +// event count. Dimensions break down metrics across some common criteria, +// such as country or event name. +func (c *AlphaAnalyticsDataClient) RunReport(ctx context.Context, req *datapb.RunReportRequest, opts ...gax.CallOption) (*datapb.RunReportResponse, error) { + return c.internalClient.RunReport(ctx, req, opts...) +} + +// RunPivotReport returns a customized pivot report of your Google Analytics event data. +// Pivot reports are more advanced and expressive formats than regular +// reports. In a pivot report, dimensions are only visible if they are +// included in a pivot. Multiple pivots can be specified to further dissect +// your data. +func (c *AlphaAnalyticsDataClient) RunPivotReport(ctx context.Context, req *datapb.RunPivotReportRequest, opts ...gax.CallOption) (*datapb.RunPivotReportResponse, error) { + return c.internalClient.RunPivotReport(ctx, req, opts...) +} + +// BatchRunReports returns multiple reports in a batch. All reports must be for the same +// Entity. +func (c *AlphaAnalyticsDataClient) BatchRunReports(ctx context.Context, req *datapb.BatchRunReportsRequest, opts ...gax.CallOption) (*datapb.BatchRunReportsResponse, error) { + return c.internalClient.BatchRunReports(ctx, req, opts...) +} + +// BatchRunPivotReports returns multiple pivot reports in a batch. All reports must be for the same +// Entity. +func (c *AlphaAnalyticsDataClient) BatchRunPivotReports(ctx context.Context, req *datapb.BatchRunPivotReportsRequest, opts ...gax.CallOption) (*datapb.BatchRunPivotReportsResponse, error) { + return c.internalClient.BatchRunPivotReports(ctx, req, opts...) +} + +// GetMetadata returns metadata for dimensions and metrics available in reporting methods. +// Used to explore the dimensions and metrics. In this method, a Google +// Analytics GA4 Property Identifier is specified in the request, and +// the metadata response includes Custom dimensions and metrics as well as +// Universal metadata. +// +// For example if a custom metric with parameter name levels_unlocked is +// registered to a property, the Metadata response will contain +// customEvent:levels_unlocked. Universal metadata are dimensions and +// metrics applicable to any property such as country and totalUsers. +func (c *AlphaAnalyticsDataClient) GetMetadata(ctx context.Context, req *datapb.GetMetadataRequest, opts ...gax.CallOption) (*datapb.Metadata, error) { + return c.internalClient.GetMetadata(ctx, req, opts...) +} + +// RunRealtimeReport the Google Analytics Realtime API returns a customized report of realtime +// event data for your property. These reports show events and usage from the +// last 30 minutes. +func (c *AlphaAnalyticsDataClient) RunRealtimeReport(ctx context.Context, req *datapb.RunRealtimeReportRequest, opts ...gax.CallOption) (*datapb.RunRealtimeReportResponse, error) { + return c.internalClient.RunRealtimeReport(ctx, req, opts...) +} + +// alphaAnalyticsDataGRPCClient is a client for interacting with Google Analytics Data API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type alphaAnalyticsDataGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing AlphaAnalyticsDataClient + CallOptions **AlphaAnalyticsDataCallOptions + // The gRPC API client. alphaAnalyticsDataClient datapb.AlphaAnalyticsDataClient - // The call options for this service. - CallOptions *AlphaAnalyticsDataCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewAlphaAnalyticsDataClient creates a new alpha analytics data client. +// NewAlphaAnalyticsDataClient creates a new alpha analytics data client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Google Analytics reporting data service. func NewAlphaAnalyticsDataClient(ctx context.Context, opts ...option.ClientOption) (*AlphaAnalyticsDataClient, error) { - clientOpts := defaultAlphaAnalyticsDataClientOptions() - + clientOpts := defaultAlphaAnalyticsDataGRPCClientOptions() if newAlphaAnalyticsDataClientHook != nil { hookOpts, err := newAlphaAnalyticsDataClientHook(ctx, clientHookParams{}) if err != nil { @@ -131,55 +231,51 @@ func NewAlphaAnalyticsDataClient(ctx context.Context, opts ...option.ClientOptio if err != nil { return nil, err } - c := &AlphaAnalyticsDataClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultAlphaAnalyticsDataCallOptions(), + client := AlphaAnalyticsDataClient{CallOptions: defaultAlphaAnalyticsDataCallOptions()} + c := &alphaAnalyticsDataGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, alphaAnalyticsDataClient: datapb.NewAlphaAnalyticsDataClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *AlphaAnalyticsDataClient) Connection() *grpc.ClientConn { +func (c *alphaAnalyticsDataGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *AlphaAnalyticsDataClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *AlphaAnalyticsDataClient) setGoogleClientInfo(keyval ...string) { +func (c *alphaAnalyticsDataGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// RunReport returns a customized report of your Google Analytics event data. Reports -// contain statistics derived from data collected by the Google Analytics -// tracking code. The data returned from the API is as a table with columns -// for the requested dimensions and metrics. Metrics are individual -// measurements of user activity on your property, such as active users or -// event count. Dimensions break down metrics across some common criteria, -// such as country or event name. -func (c *AlphaAnalyticsDataClient) RunReport(ctx context.Context, req *datapb.RunReportRequest, opts ...gax.CallOption) (*datapb.RunReportResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *alphaAnalyticsDataGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *alphaAnalyticsDataGRPCClient) RunReport(ctx context.Context, req *datapb.RunReportRequest, opts ...gax.CallOption) (*datapb.RunReportResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.RunReport[0:len(c.CallOptions.RunReport):len(c.CallOptions.RunReport)], opts...) + opts = append((*c.CallOptions).RunReport[0:len((*c.CallOptions).RunReport):len((*c.CallOptions).RunReport)], opts...) var resp *datapb.RunReportResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -192,19 +288,14 @@ func (c *AlphaAnalyticsDataClient) RunReport(ctx context.Context, req *datapb.Ru return resp, nil } -// RunPivotReport returns a customized pivot report of your Google Analytics event data. -// Pivot reports are more advanced and expressive formats than regular -// reports. In a pivot report, dimensions are only visible if they are -// included in a pivot. Multiple pivots can be specified to further dissect -// your data. -func (c *AlphaAnalyticsDataClient) RunPivotReport(ctx context.Context, req *datapb.RunPivotReportRequest, opts ...gax.CallOption) (*datapb.RunPivotReportResponse, error) { +func (c *alphaAnalyticsDataGRPCClient) RunPivotReport(ctx context.Context, req *datapb.RunPivotReportRequest, opts ...gax.CallOption) (*datapb.RunPivotReportResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.RunPivotReport[0:len(c.CallOptions.RunPivotReport):len(c.CallOptions.RunPivotReport)], opts...) + opts = append((*c.CallOptions).RunPivotReport[0:len((*c.CallOptions).RunPivotReport):len((*c.CallOptions).RunPivotReport)], opts...) var resp *datapb.RunPivotReportResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -217,16 +308,14 @@ func (c *AlphaAnalyticsDataClient) RunPivotReport(ctx context.Context, req *data return resp, nil } -// BatchRunReports returns multiple reports in a batch. All reports must be for the same -// Entity. -func (c *AlphaAnalyticsDataClient) BatchRunReports(ctx context.Context, req *datapb.BatchRunReportsRequest, opts ...gax.CallOption) (*datapb.BatchRunReportsResponse, error) { +func (c *alphaAnalyticsDataGRPCClient) BatchRunReports(ctx context.Context, req *datapb.BatchRunReportsRequest, opts ...gax.CallOption) (*datapb.BatchRunReportsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.BatchRunReports[0:len(c.CallOptions.BatchRunReports):len(c.CallOptions.BatchRunReports)], opts...) + opts = append((*c.CallOptions).BatchRunReports[0:len((*c.CallOptions).BatchRunReports):len((*c.CallOptions).BatchRunReports)], opts...) var resp *datapb.BatchRunReportsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -239,16 +328,14 @@ func (c *AlphaAnalyticsDataClient) BatchRunReports(ctx context.Context, req *dat return resp, nil } -// BatchRunPivotReports returns multiple pivot reports in a batch. All reports must be for the same -// Entity. -func (c *AlphaAnalyticsDataClient) BatchRunPivotReports(ctx context.Context, req *datapb.BatchRunPivotReportsRequest, opts ...gax.CallOption) (*datapb.BatchRunPivotReportsResponse, error) { +func (c *alphaAnalyticsDataGRPCClient) BatchRunPivotReports(ctx context.Context, req *datapb.BatchRunPivotReportsRequest, opts ...gax.CallOption) (*datapb.BatchRunPivotReportsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.BatchRunPivotReports[0:len(c.CallOptions.BatchRunPivotReports):len(c.CallOptions.BatchRunPivotReports)], opts...) + opts = append((*c.CallOptions).BatchRunPivotReports[0:len((*c.CallOptions).BatchRunPivotReports):len((*c.CallOptions).BatchRunPivotReports)], opts...) var resp *datapb.BatchRunPivotReportsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -261,17 +348,7 @@ func (c *AlphaAnalyticsDataClient) BatchRunPivotReports(ctx context.Context, req return resp, nil } -// GetMetadata returns metadata for dimensions and metrics available in reporting methods. -// Used to explore the dimensions and metrics. In this method, a Google -// Analytics GA4 Property Identifier is specified in the request, and -// the metadata response includes Custom dimensions and metrics as well as -// Universal metadata. -// -// For example if a custom metric with parameter name levels_unlocked is -// registered to a property, the Metadata response will contain -// customEvent:levels_unlocked. Universal metadata are dimensions and -// metrics applicable to any property such as country and totalUsers. -func (c *AlphaAnalyticsDataClient) GetMetadata(ctx context.Context, req *datapb.GetMetadataRequest, opts ...gax.CallOption) (*datapb.Metadata, error) { +func (c *alphaAnalyticsDataGRPCClient) GetMetadata(ctx context.Context, req *datapb.GetMetadataRequest, opts ...gax.CallOption) (*datapb.Metadata, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -279,7 +356,7 @@ func (c *AlphaAnalyticsDataClient) GetMetadata(ctx context.Context, req *datapb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetMetadata[0:len(c.CallOptions.GetMetadata):len(c.CallOptions.GetMetadata)], opts...) + opts = append((*c.CallOptions).GetMetadata[0:len((*c.CallOptions).GetMetadata):len((*c.CallOptions).GetMetadata)], opts...) var resp *datapb.Metadata err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -292,10 +369,7 @@ func (c *AlphaAnalyticsDataClient) GetMetadata(ctx context.Context, req *datapb. return resp, nil } -// RunRealtimeReport the Google Analytics Realtime API returns a customized report of realtime -// event data for your property. These reports show events and usage from the -// last 30 minutes. -func (c *AlphaAnalyticsDataClient) RunRealtimeReport(ctx context.Context, req *datapb.RunRealtimeReportRequest, opts ...gax.CallOption) (*datapb.RunRealtimeReportResponse, error) { +func (c *alphaAnalyticsDataGRPCClient) RunRealtimeReport(ctx context.Context, req *datapb.RunRealtimeReportRequest, opts ...gax.CallOption) (*datapb.RunRealtimeReportResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -303,7 +377,7 @@ func (c *AlphaAnalyticsDataClient) RunRealtimeReport(ctx context.Context, req *d } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "property", url.QueryEscape(req.GetProperty()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RunRealtimeReport[0:len(c.CallOptions.RunRealtimeReport):len(c.CallOptions.RunRealtimeReport)], opts...) + opts = append((*c.CallOptions).RunRealtimeReport[0:len((*c.CallOptions).RunRealtimeReport):len((*c.CallOptions).RunRealtimeReport)], opts...) var resp *datapb.RunRealtimeReportResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/analytics/data/apiv1alpha/alpha_analytics_data_client_example_test.go b/analytics/data/apiv1alpha/alpha_analytics_data_client_example_test.go index e9aace66e20e..3a52a996fe9b 100644 --- a/analytics/data/apiv1alpha/alpha_analytics_data_client_example_test.go +++ b/analytics/data/apiv1alpha/alpha_analytics_data_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewAlphaAnalyticsDataClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleAlphaAnalyticsDataClient_RunReport() { - // import datapb "google.golang.org/genproto/googleapis/analytics/data/v1alpha" - ctx := context.Background() c, err := data.NewAlphaAnalyticsDataClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datapb.RunReportRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleAlphaAnalyticsDataClient_RunReport() { } func ExampleAlphaAnalyticsDataClient_RunPivotReport() { - // import datapb "google.golang.org/genproto/googleapis/analytics/data/v1alpha" - ctx := context.Background() c, err := data.NewAlphaAnalyticsDataClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datapb.RunPivotReportRequest{ // TODO: Fill request struct fields. @@ -74,13 +74,12 @@ func ExampleAlphaAnalyticsDataClient_RunPivotReport() { } func ExampleAlphaAnalyticsDataClient_BatchRunReports() { - // import datapb "google.golang.org/genproto/googleapis/analytics/data/v1alpha" - ctx := context.Background() c, err := data.NewAlphaAnalyticsDataClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datapb.BatchRunReportsRequest{ // TODO: Fill request struct fields. @@ -94,13 +93,12 @@ func ExampleAlphaAnalyticsDataClient_BatchRunReports() { } func ExampleAlphaAnalyticsDataClient_BatchRunPivotReports() { - // import datapb "google.golang.org/genproto/googleapis/analytics/data/v1alpha" - ctx := context.Background() c, err := data.NewAlphaAnalyticsDataClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datapb.BatchRunPivotReportsRequest{ // TODO: Fill request struct fields. @@ -114,13 +112,12 @@ func ExampleAlphaAnalyticsDataClient_BatchRunPivotReports() { } func ExampleAlphaAnalyticsDataClient_GetMetadata() { - // import datapb "google.golang.org/genproto/googleapis/analytics/data/v1alpha" - ctx := context.Background() c, err := data.NewAlphaAnalyticsDataClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datapb.GetMetadataRequest{ // TODO: Fill request struct fields. @@ -134,13 +131,12 @@ func ExampleAlphaAnalyticsDataClient_GetMetadata() { } func ExampleAlphaAnalyticsDataClient_RunRealtimeReport() { - // import datapb "google.golang.org/genproto/googleapis/analytics/data/v1alpha" - ctx := context.Background() c, err := data.NewAlphaAnalyticsDataClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datapb.RunRealtimeReportRequest{ // TODO: Fill request struct fields. diff --git a/analytics/data/apiv1alpha/doc.go b/analytics/data/apiv1alpha/doc.go index 0d735d9b1692..2dc1be291477 100644 --- a/analytics/data/apiv1alpha/doc.go +++ b/analytics/data/apiv1alpha/doc.go @@ -19,6 +19,8 @@ // // Accesses report data in Google Analytics. // +// NOTE: This package is in alpha. It is not stable, and is likely to change. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -28,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package data // import "cloud.google.com/go/analytics/data/apiv1alpha" import ( @@ -48,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/apigateway/apiv1/api_gateway_client.go b/apigateway/apiv1/api_gateway_client.go index 464a81c9bb28..130ea9b66e85 100644 --- a/apigateway/apiv1/api_gateway_client.go +++ b/apigateway/apiv1/api_gateway_client.go @@ -59,7 +59,7 @@ type CallOptions struct { DeleteApiConfig []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("apigateway.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("apigateway.mtls.googleapis.com:443"), @@ -190,37 +190,236 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from API Gateway API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListGateways(context.Context, *apigatewaypb.ListGatewaysRequest, ...gax.CallOption) *GatewayIterator + GetGateway(context.Context, *apigatewaypb.GetGatewayRequest, ...gax.CallOption) (*apigatewaypb.Gateway, error) + CreateGateway(context.Context, *apigatewaypb.CreateGatewayRequest, ...gax.CallOption) (*CreateGatewayOperation, error) + CreateGatewayOperation(name string) *CreateGatewayOperation + UpdateGateway(context.Context, *apigatewaypb.UpdateGatewayRequest, ...gax.CallOption) (*UpdateGatewayOperation, error) + UpdateGatewayOperation(name string) *UpdateGatewayOperation + DeleteGateway(context.Context, *apigatewaypb.DeleteGatewayRequest, ...gax.CallOption) (*DeleteGatewayOperation, error) + DeleteGatewayOperation(name string) *DeleteGatewayOperation + ListApis(context.Context, *apigatewaypb.ListApisRequest, ...gax.CallOption) *ApiIterator + GetApi(context.Context, *apigatewaypb.GetApiRequest, ...gax.CallOption) (*apigatewaypb.Api, error) + CreateApi(context.Context, *apigatewaypb.CreateApiRequest, ...gax.CallOption) (*CreateApiOperation, error) + CreateApiOperation(name string) *CreateApiOperation + UpdateApi(context.Context, *apigatewaypb.UpdateApiRequest, ...gax.CallOption) (*UpdateApiOperation, error) + UpdateApiOperation(name string) *UpdateApiOperation + DeleteApi(context.Context, *apigatewaypb.DeleteApiRequest, ...gax.CallOption) (*DeleteApiOperation, error) + DeleteApiOperation(name string) *DeleteApiOperation + ListApiConfigs(context.Context, *apigatewaypb.ListApiConfigsRequest, ...gax.CallOption) *ApiConfigIterator + GetApiConfig(context.Context, *apigatewaypb.GetApiConfigRequest, ...gax.CallOption) (*apigatewaypb.ApiConfig, error) + CreateApiConfig(context.Context, *apigatewaypb.CreateApiConfigRequest, ...gax.CallOption) (*CreateApiConfigOperation, error) + CreateApiConfigOperation(name string) *CreateApiConfigOperation + UpdateApiConfig(context.Context, *apigatewaypb.UpdateApiConfigRequest, ...gax.CallOption) (*UpdateApiConfigOperation, error) + UpdateApiConfigOperation(name string) *UpdateApiConfigOperation + DeleteApiConfig(context.Context, *apigatewaypb.DeleteApiConfigRequest, ...gax.CallOption) (*DeleteApiConfigOperation, error) + DeleteApiConfigOperation(name string) *DeleteApiConfigOperation +} + // Client is a client for interacting with API Gateway API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The API Gateway Service is the interface for managing API Gateways. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListGateways lists Gateways in a given project and location. +func (c *Client) ListGateways(ctx context.Context, req *apigatewaypb.ListGatewaysRequest, opts ...gax.CallOption) *GatewayIterator { + return c.internalClient.ListGateways(ctx, req, opts...) +} + +// GetGateway gets details of a single Gateway. +func (c *Client) GetGateway(ctx context.Context, req *apigatewaypb.GetGatewayRequest, opts ...gax.CallOption) (*apigatewaypb.Gateway, error) { + return c.internalClient.GetGateway(ctx, req, opts...) +} + +// CreateGateway creates a new Gateway in a given project and location. +func (c *Client) CreateGateway(ctx context.Context, req *apigatewaypb.CreateGatewayRequest, opts ...gax.CallOption) (*CreateGatewayOperation, error) { + return c.internalClient.CreateGateway(ctx, req, opts...) +} + +// CreateGatewayOperation returns a new CreateGatewayOperation from a given name. +// The name must be that of a previously created CreateGatewayOperation, possibly from a different process. +func (c *Client) CreateGatewayOperation(name string) *CreateGatewayOperation { + return c.internalClient.CreateGatewayOperation(name) +} + +// UpdateGateway updates the parameters of a single Gateway. +func (c *Client) UpdateGateway(ctx context.Context, req *apigatewaypb.UpdateGatewayRequest, opts ...gax.CallOption) (*UpdateGatewayOperation, error) { + return c.internalClient.UpdateGateway(ctx, req, opts...) +} + +// UpdateGatewayOperation returns a new UpdateGatewayOperation from a given name. +// The name must be that of a previously created UpdateGatewayOperation, possibly from a different process. +func (c *Client) UpdateGatewayOperation(name string) *UpdateGatewayOperation { + return c.internalClient.UpdateGatewayOperation(name) +} + +// DeleteGateway deletes a single Gateway. +func (c *Client) DeleteGateway(ctx context.Context, req *apigatewaypb.DeleteGatewayRequest, opts ...gax.CallOption) (*DeleteGatewayOperation, error) { + return c.internalClient.DeleteGateway(ctx, req, opts...) +} + +// DeleteGatewayOperation returns a new DeleteGatewayOperation from a given name. +// The name must be that of a previously created DeleteGatewayOperation, possibly from a different process. +func (c *Client) DeleteGatewayOperation(name string) *DeleteGatewayOperation { + return c.internalClient.DeleteGatewayOperation(name) +} + +// ListApis lists Apis in a given project and location. +func (c *Client) ListApis(ctx context.Context, req *apigatewaypb.ListApisRequest, opts ...gax.CallOption) *ApiIterator { + return c.internalClient.ListApis(ctx, req, opts...) +} + +// GetApi gets details of a single Api. +func (c *Client) GetApi(ctx context.Context, req *apigatewaypb.GetApiRequest, opts ...gax.CallOption) (*apigatewaypb.Api, error) { + return c.internalClient.GetApi(ctx, req, opts...) +} + +// CreateApi creates a new Api in a given project and location. +func (c *Client) CreateApi(ctx context.Context, req *apigatewaypb.CreateApiRequest, opts ...gax.CallOption) (*CreateApiOperation, error) { + return c.internalClient.CreateApi(ctx, req, opts...) +} + +// CreateApiOperation returns a new CreateApiOperation from a given name. +// The name must be that of a previously created CreateApiOperation, possibly from a different process. +func (c *Client) CreateApiOperation(name string) *CreateApiOperation { + return c.internalClient.CreateApiOperation(name) +} + +// UpdateApi updates the parameters of a single Api. +func (c *Client) UpdateApi(ctx context.Context, req *apigatewaypb.UpdateApiRequest, opts ...gax.CallOption) (*UpdateApiOperation, error) { + return c.internalClient.UpdateApi(ctx, req, opts...) +} + +// UpdateApiOperation returns a new UpdateApiOperation from a given name. +// The name must be that of a previously created UpdateApiOperation, possibly from a different process. +func (c *Client) UpdateApiOperation(name string) *UpdateApiOperation { + return c.internalClient.UpdateApiOperation(name) +} + +// DeleteApi deletes a single Api. +func (c *Client) DeleteApi(ctx context.Context, req *apigatewaypb.DeleteApiRequest, opts ...gax.CallOption) (*DeleteApiOperation, error) { + return c.internalClient.DeleteApi(ctx, req, opts...) +} + +// DeleteApiOperation returns a new DeleteApiOperation from a given name. +// The name must be that of a previously created DeleteApiOperation, possibly from a different process. +func (c *Client) DeleteApiOperation(name string) *DeleteApiOperation { + return c.internalClient.DeleteApiOperation(name) +} + +// ListApiConfigs lists ApiConfigs in a given project and location. +func (c *Client) ListApiConfigs(ctx context.Context, req *apigatewaypb.ListApiConfigsRequest, opts ...gax.CallOption) *ApiConfigIterator { + return c.internalClient.ListApiConfigs(ctx, req, opts...) +} + +// GetApiConfig gets details of a single ApiConfig. +func (c *Client) GetApiConfig(ctx context.Context, req *apigatewaypb.GetApiConfigRequest, opts ...gax.CallOption) (*apigatewaypb.ApiConfig, error) { + return c.internalClient.GetApiConfig(ctx, req, opts...) +} + +// CreateApiConfig creates a new ApiConfig in a given project and location. +func (c *Client) CreateApiConfig(ctx context.Context, req *apigatewaypb.CreateApiConfigRequest, opts ...gax.CallOption) (*CreateApiConfigOperation, error) { + return c.internalClient.CreateApiConfig(ctx, req, opts...) +} + +// CreateApiConfigOperation returns a new CreateApiConfigOperation from a given name. +// The name must be that of a previously created CreateApiConfigOperation, possibly from a different process. +func (c *Client) CreateApiConfigOperation(name string) *CreateApiConfigOperation { + return c.internalClient.CreateApiConfigOperation(name) +} + +// UpdateApiConfig updates the parameters of a single ApiConfig. +func (c *Client) UpdateApiConfig(ctx context.Context, req *apigatewaypb.UpdateApiConfigRequest, opts ...gax.CallOption) (*UpdateApiConfigOperation, error) { + return c.internalClient.UpdateApiConfig(ctx, req, opts...) +} + +// UpdateApiConfigOperation returns a new UpdateApiConfigOperation from a given name. +// The name must be that of a previously created UpdateApiConfigOperation, possibly from a different process. +func (c *Client) UpdateApiConfigOperation(name string) *UpdateApiConfigOperation { + return c.internalClient.UpdateApiConfigOperation(name) +} + +// DeleteApiConfig deletes a single ApiConfig. +func (c *Client) DeleteApiConfig(ctx context.Context, req *apigatewaypb.DeleteApiConfigRequest, opts ...gax.CallOption) (*DeleteApiConfigOperation, error) { + return c.internalClient.DeleteApiConfig(ctx, req, opts...) +} + +// DeleteApiConfigOperation returns a new DeleteApiConfigOperation from a given name. +// The name must be that of a previously created DeleteApiConfigOperation, possibly from a different process. +func (c *Client) DeleteApiConfigOperation(name string) *DeleteApiConfigOperation { + return c.internalClient.DeleteApiConfigOperation(name) +} + +// gRPCClient is a client for interacting with API Gateway API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client apigatewaypb.ApiGatewayServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new api gateway service client. +// NewClient creates a new api gateway service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The API Gateway Service is the interface for managing API Gateways. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -238,16 +437,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: apigatewaypb.NewApiGatewayServiceClient(connPool), + client: apigatewaypb.NewApiGatewayServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -257,36 +459,36 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListGateways lists Gateways in a given project and location. -func (c *Client) ListGateways(ctx context.Context, req *apigatewaypb.ListGatewaysRequest, opts ...gax.CallOption) *GatewayIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ListGateways(ctx context.Context, req *apigatewaypb.ListGatewaysRequest, opts ...gax.CallOption) *GatewayIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListGateways[0:len(c.CallOptions.ListGateways):len(c.CallOptions.ListGateways)], opts...) + opts = append((*c.CallOptions).ListGateways[0:len((*c.CallOptions).ListGateways):len((*c.CallOptions).ListGateways)], opts...) it := &GatewayIterator{} req = proto.Clone(req).(*apigatewaypb.ListGatewaysRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*apigatewaypb.Gateway, string, error) { @@ -323,11 +525,10 @@ func (c *Client) ListGateways(ctx context.Context, req *apigatewaypb.ListGateway return it } -// GetGateway gets details of a single Gateway. -func (c *Client) GetGateway(ctx context.Context, req *apigatewaypb.GetGatewayRequest, opts ...gax.CallOption) (*apigatewaypb.Gateway, error) { +func (c *gRPCClient) GetGateway(ctx context.Context, req *apigatewaypb.GetGatewayRequest, opts ...gax.CallOption) (*apigatewaypb.Gateway, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetGateway[0:len(c.CallOptions.GetGateway):len(c.CallOptions.GetGateway)], opts...) + opts = append((*c.CallOptions).GetGateway[0:len((*c.CallOptions).GetGateway):len((*c.CallOptions).GetGateway)], opts...) var resp *apigatewaypb.Gateway err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -340,8 +541,7 @@ func (c *Client) GetGateway(ctx context.Context, req *apigatewaypb.GetGatewayReq return resp, nil } -// CreateGateway creates a new Gateway in a given project and location. -func (c *Client) CreateGateway(ctx context.Context, req *apigatewaypb.CreateGatewayRequest, opts ...gax.CallOption) (*CreateGatewayOperation, error) { +func (c *gRPCClient) CreateGateway(ctx context.Context, req *apigatewaypb.CreateGatewayRequest, opts ...gax.CallOption) (*CreateGatewayOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -349,7 +549,7 @@ func (c *Client) CreateGateway(ctx context.Context, req *apigatewaypb.CreateGate } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateGateway[0:len(c.CallOptions.CreateGateway):len(c.CallOptions.CreateGateway)], opts...) + opts = append((*c.CallOptions).CreateGateway[0:len((*c.CallOptions).CreateGateway):len((*c.CallOptions).CreateGateway)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -360,12 +560,11 @@ func (c *Client) CreateGateway(ctx context.Context, req *apigatewaypb.CreateGate return nil, err } return &CreateGatewayOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateGateway updates the parameters of a single Gateway. -func (c *Client) UpdateGateway(ctx context.Context, req *apigatewaypb.UpdateGatewayRequest, opts ...gax.CallOption) (*UpdateGatewayOperation, error) { +func (c *gRPCClient) UpdateGateway(ctx context.Context, req *apigatewaypb.UpdateGatewayRequest, opts ...gax.CallOption) (*UpdateGatewayOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -373,7 +572,7 @@ func (c *Client) UpdateGateway(ctx context.Context, req *apigatewaypb.UpdateGate } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "gateway.name", url.QueryEscape(req.GetGateway().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateGateway[0:len(c.CallOptions.UpdateGateway):len(c.CallOptions.UpdateGateway)], opts...) + opts = append((*c.CallOptions).UpdateGateway[0:len((*c.CallOptions).UpdateGateway):len((*c.CallOptions).UpdateGateway)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -384,12 +583,11 @@ func (c *Client) UpdateGateway(ctx context.Context, req *apigatewaypb.UpdateGate return nil, err } return &UpdateGatewayOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteGateway deletes a single Gateway. -func (c *Client) DeleteGateway(ctx context.Context, req *apigatewaypb.DeleteGatewayRequest, opts ...gax.CallOption) (*DeleteGatewayOperation, error) { +func (c *gRPCClient) DeleteGateway(ctx context.Context, req *apigatewaypb.DeleteGatewayRequest, opts ...gax.CallOption) (*DeleteGatewayOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -397,7 +595,7 @@ func (c *Client) DeleteGateway(ctx context.Context, req *apigatewaypb.DeleteGate } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteGateway[0:len(c.CallOptions.DeleteGateway):len(c.CallOptions.DeleteGateway)], opts...) + opts = append((*c.CallOptions).DeleteGateway[0:len((*c.CallOptions).DeleteGateway):len((*c.CallOptions).DeleteGateway)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -408,15 +606,14 @@ func (c *Client) DeleteGateway(ctx context.Context, req *apigatewaypb.DeleteGate return nil, err } return &DeleteGatewayOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListApis lists Apis in a given project and location. -func (c *Client) ListApis(ctx context.Context, req *apigatewaypb.ListApisRequest, opts ...gax.CallOption) *ApiIterator { +func (c *gRPCClient) ListApis(ctx context.Context, req *apigatewaypb.ListApisRequest, opts ...gax.CallOption) *ApiIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListApis[0:len(c.CallOptions.ListApis):len(c.CallOptions.ListApis)], opts...) + opts = append((*c.CallOptions).ListApis[0:len((*c.CallOptions).ListApis):len((*c.CallOptions).ListApis)], opts...) it := &ApiIterator{} req = proto.Clone(req).(*apigatewaypb.ListApisRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*apigatewaypb.Api, string, error) { @@ -453,11 +650,10 @@ func (c *Client) ListApis(ctx context.Context, req *apigatewaypb.ListApisRequest return it } -// GetApi gets details of a single Api. -func (c *Client) GetApi(ctx context.Context, req *apigatewaypb.GetApiRequest, opts ...gax.CallOption) (*apigatewaypb.Api, error) { +func (c *gRPCClient) GetApi(ctx context.Context, req *apigatewaypb.GetApiRequest, opts ...gax.CallOption) (*apigatewaypb.Api, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetApi[0:len(c.CallOptions.GetApi):len(c.CallOptions.GetApi)], opts...) + opts = append((*c.CallOptions).GetApi[0:len((*c.CallOptions).GetApi):len((*c.CallOptions).GetApi)], opts...) var resp *apigatewaypb.Api err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -470,8 +666,7 @@ func (c *Client) GetApi(ctx context.Context, req *apigatewaypb.GetApiRequest, op return resp, nil } -// CreateApi creates a new Api in a given project and location. -func (c *Client) CreateApi(ctx context.Context, req *apigatewaypb.CreateApiRequest, opts ...gax.CallOption) (*CreateApiOperation, error) { +func (c *gRPCClient) CreateApi(ctx context.Context, req *apigatewaypb.CreateApiRequest, opts ...gax.CallOption) (*CreateApiOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -479,7 +674,7 @@ func (c *Client) CreateApi(ctx context.Context, req *apigatewaypb.CreateApiReque } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateApi[0:len(c.CallOptions.CreateApi):len(c.CallOptions.CreateApi)], opts...) + opts = append((*c.CallOptions).CreateApi[0:len((*c.CallOptions).CreateApi):len((*c.CallOptions).CreateApi)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -490,12 +685,11 @@ func (c *Client) CreateApi(ctx context.Context, req *apigatewaypb.CreateApiReque return nil, err } return &CreateApiOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateApi updates the parameters of a single Api. -func (c *Client) UpdateApi(ctx context.Context, req *apigatewaypb.UpdateApiRequest, opts ...gax.CallOption) (*UpdateApiOperation, error) { +func (c *gRPCClient) UpdateApi(ctx context.Context, req *apigatewaypb.UpdateApiRequest, opts ...gax.CallOption) (*UpdateApiOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -503,7 +697,7 @@ func (c *Client) UpdateApi(ctx context.Context, req *apigatewaypb.UpdateApiReque } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "api.name", url.QueryEscape(req.GetApi().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateApi[0:len(c.CallOptions.UpdateApi):len(c.CallOptions.UpdateApi)], opts...) + opts = append((*c.CallOptions).UpdateApi[0:len((*c.CallOptions).UpdateApi):len((*c.CallOptions).UpdateApi)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -514,12 +708,11 @@ func (c *Client) UpdateApi(ctx context.Context, req *apigatewaypb.UpdateApiReque return nil, err } return &UpdateApiOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteApi deletes a single Api. -func (c *Client) DeleteApi(ctx context.Context, req *apigatewaypb.DeleteApiRequest, opts ...gax.CallOption) (*DeleteApiOperation, error) { +func (c *gRPCClient) DeleteApi(ctx context.Context, req *apigatewaypb.DeleteApiRequest, opts ...gax.CallOption) (*DeleteApiOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -527,7 +720,7 @@ func (c *Client) DeleteApi(ctx context.Context, req *apigatewaypb.DeleteApiReque } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteApi[0:len(c.CallOptions.DeleteApi):len(c.CallOptions.DeleteApi)], opts...) + opts = append((*c.CallOptions).DeleteApi[0:len((*c.CallOptions).DeleteApi):len((*c.CallOptions).DeleteApi)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -538,15 +731,14 @@ func (c *Client) DeleteApi(ctx context.Context, req *apigatewaypb.DeleteApiReque return nil, err } return &DeleteApiOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListApiConfigs lists ApiConfigs in a given project and location. -func (c *Client) ListApiConfigs(ctx context.Context, req *apigatewaypb.ListApiConfigsRequest, opts ...gax.CallOption) *ApiConfigIterator { +func (c *gRPCClient) ListApiConfigs(ctx context.Context, req *apigatewaypb.ListApiConfigsRequest, opts ...gax.CallOption) *ApiConfigIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListApiConfigs[0:len(c.CallOptions.ListApiConfigs):len(c.CallOptions.ListApiConfigs)], opts...) + opts = append((*c.CallOptions).ListApiConfigs[0:len((*c.CallOptions).ListApiConfigs):len((*c.CallOptions).ListApiConfigs)], opts...) it := &ApiConfigIterator{} req = proto.Clone(req).(*apigatewaypb.ListApiConfigsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*apigatewaypb.ApiConfig, string, error) { @@ -583,11 +775,10 @@ func (c *Client) ListApiConfigs(ctx context.Context, req *apigatewaypb.ListApiCo return it } -// GetApiConfig gets details of a single ApiConfig. -func (c *Client) GetApiConfig(ctx context.Context, req *apigatewaypb.GetApiConfigRequest, opts ...gax.CallOption) (*apigatewaypb.ApiConfig, error) { +func (c *gRPCClient) GetApiConfig(ctx context.Context, req *apigatewaypb.GetApiConfigRequest, opts ...gax.CallOption) (*apigatewaypb.ApiConfig, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetApiConfig[0:len(c.CallOptions.GetApiConfig):len(c.CallOptions.GetApiConfig)], opts...) + opts = append((*c.CallOptions).GetApiConfig[0:len((*c.CallOptions).GetApiConfig):len((*c.CallOptions).GetApiConfig)], opts...) var resp *apigatewaypb.ApiConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -600,8 +791,7 @@ func (c *Client) GetApiConfig(ctx context.Context, req *apigatewaypb.GetApiConfi return resp, nil } -// CreateApiConfig creates a new ApiConfig in a given project and location. -func (c *Client) CreateApiConfig(ctx context.Context, req *apigatewaypb.CreateApiConfigRequest, opts ...gax.CallOption) (*CreateApiConfigOperation, error) { +func (c *gRPCClient) CreateApiConfig(ctx context.Context, req *apigatewaypb.CreateApiConfigRequest, opts ...gax.CallOption) (*CreateApiConfigOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -609,7 +799,7 @@ func (c *Client) CreateApiConfig(ctx context.Context, req *apigatewaypb.CreateAp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateApiConfig[0:len(c.CallOptions.CreateApiConfig):len(c.CallOptions.CreateApiConfig)], opts...) + opts = append((*c.CallOptions).CreateApiConfig[0:len((*c.CallOptions).CreateApiConfig):len((*c.CallOptions).CreateApiConfig)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -620,12 +810,11 @@ func (c *Client) CreateApiConfig(ctx context.Context, req *apigatewaypb.CreateAp return nil, err } return &CreateApiConfigOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateApiConfig updates the parameters of a single ApiConfig. -func (c *Client) UpdateApiConfig(ctx context.Context, req *apigatewaypb.UpdateApiConfigRequest, opts ...gax.CallOption) (*UpdateApiConfigOperation, error) { +func (c *gRPCClient) UpdateApiConfig(ctx context.Context, req *apigatewaypb.UpdateApiConfigRequest, opts ...gax.CallOption) (*UpdateApiConfigOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -633,7 +822,7 @@ func (c *Client) UpdateApiConfig(ctx context.Context, req *apigatewaypb.UpdateAp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "api_config.name", url.QueryEscape(req.GetApiConfig().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateApiConfig[0:len(c.CallOptions.UpdateApiConfig):len(c.CallOptions.UpdateApiConfig)], opts...) + opts = append((*c.CallOptions).UpdateApiConfig[0:len((*c.CallOptions).UpdateApiConfig):len((*c.CallOptions).UpdateApiConfig)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -644,12 +833,11 @@ func (c *Client) UpdateApiConfig(ctx context.Context, req *apigatewaypb.UpdateAp return nil, err } return &UpdateApiConfigOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteApiConfig deletes a single ApiConfig. -func (c *Client) DeleteApiConfig(ctx context.Context, req *apigatewaypb.DeleteApiConfigRequest, opts ...gax.CallOption) (*DeleteApiConfigOperation, error) { +func (c *gRPCClient) DeleteApiConfig(ctx context.Context, req *apigatewaypb.DeleteApiConfigRequest, opts ...gax.CallOption) (*DeleteApiConfigOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -657,7 +845,7 @@ func (c *Client) DeleteApiConfig(ctx context.Context, req *apigatewaypb.DeleteAp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteApiConfig[0:len(c.CallOptions.DeleteApiConfig):len(c.CallOptions.DeleteApiConfig)], opts...) + opts = append((*c.CallOptions).DeleteApiConfig[0:len((*c.CallOptions).DeleteApiConfig):len((*c.CallOptions).DeleteApiConfig)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -668,7 +856,7 @@ func (c *Client) DeleteApiConfig(ctx context.Context, req *apigatewaypb.DeleteAp return nil, err } return &DeleteApiConfigOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -679,9 +867,9 @@ type CreateApiOperation struct { // CreateApiOperation returns a new CreateApiOperation from a given name. // The name must be that of a previously created CreateApiOperation, possibly from a different process. -func (c *Client) CreateApiOperation(name string) *CreateApiOperation { +func (c *gRPCClient) CreateApiOperation(name string) *CreateApiOperation { return &CreateApiOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -748,9 +936,9 @@ type CreateApiConfigOperation struct { // CreateApiConfigOperation returns a new CreateApiConfigOperation from a given name. // The name must be that of a previously created CreateApiConfigOperation, possibly from a different process. -func (c *Client) CreateApiConfigOperation(name string) *CreateApiConfigOperation { +func (c *gRPCClient) CreateApiConfigOperation(name string) *CreateApiConfigOperation { return &CreateApiConfigOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -817,9 +1005,9 @@ type CreateGatewayOperation struct { // CreateGatewayOperation returns a new CreateGatewayOperation from a given name. // The name must be that of a previously created CreateGatewayOperation, possibly from a different process. -func (c *Client) CreateGatewayOperation(name string) *CreateGatewayOperation { +func (c *gRPCClient) CreateGatewayOperation(name string) *CreateGatewayOperation { return &CreateGatewayOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -886,9 +1074,9 @@ type DeleteApiOperation struct { // DeleteApiOperation returns a new DeleteApiOperation from a given name. // The name must be that of a previously created DeleteApiOperation, possibly from a different process. -func (c *Client) DeleteApiOperation(name string) *DeleteApiOperation { +func (c *gRPCClient) DeleteApiOperation(name string) *DeleteApiOperation { return &DeleteApiOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -944,9 +1132,9 @@ type DeleteApiConfigOperation struct { // DeleteApiConfigOperation returns a new DeleteApiConfigOperation from a given name. // The name must be that of a previously created DeleteApiConfigOperation, possibly from a different process. -func (c *Client) DeleteApiConfigOperation(name string) *DeleteApiConfigOperation { +func (c *gRPCClient) DeleteApiConfigOperation(name string) *DeleteApiConfigOperation { return &DeleteApiConfigOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1002,9 +1190,9 @@ type DeleteGatewayOperation struct { // DeleteGatewayOperation returns a new DeleteGatewayOperation from a given name. // The name must be that of a previously created DeleteGatewayOperation, possibly from a different process. -func (c *Client) DeleteGatewayOperation(name string) *DeleteGatewayOperation { +func (c *gRPCClient) DeleteGatewayOperation(name string) *DeleteGatewayOperation { return &DeleteGatewayOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1060,9 +1248,9 @@ type UpdateApiOperation struct { // UpdateApiOperation returns a new UpdateApiOperation from a given name. // The name must be that of a previously created UpdateApiOperation, possibly from a different process. -func (c *Client) UpdateApiOperation(name string) *UpdateApiOperation { +func (c *gRPCClient) UpdateApiOperation(name string) *UpdateApiOperation { return &UpdateApiOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1129,9 +1317,9 @@ type UpdateApiConfigOperation struct { // UpdateApiConfigOperation returns a new UpdateApiConfigOperation from a given name. // The name must be that of a previously created UpdateApiConfigOperation, possibly from a different process. -func (c *Client) UpdateApiConfigOperation(name string) *UpdateApiConfigOperation { +func (c *gRPCClient) UpdateApiConfigOperation(name string) *UpdateApiConfigOperation { return &UpdateApiConfigOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1198,9 +1386,9 @@ type UpdateGatewayOperation struct { // UpdateGatewayOperation returns a new UpdateGatewayOperation from a given name. // The name must be that of a previously created UpdateGatewayOperation, possibly from a different process. -func (c *Client) UpdateGatewayOperation(name string) *UpdateGatewayOperation { +func (c *gRPCClient) UpdateGatewayOperation(name string) *UpdateGatewayOperation { return &UpdateGatewayOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/apigateway/apiv1/api_gateway_client_example_test.go b/apigateway/apiv1/api_gateway_client_example_test.go index 6c1d060ec546..1b54e5acabf8 100644 --- a/apigateway/apiv1/api_gateway_client_example_test.go +++ b/apigateway/apiv1/api_gateway_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ListGateways() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.ListGatewaysRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleClient_ListGateways() { } func ExampleClient_GetGateway() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.GetGatewayRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleClient_GetGateway() { } func ExampleClient_CreateGateway() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.CreateGatewayRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleClient_CreateGateway() { } func ExampleClient_UpdateGateway() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.UpdateGatewayRequest{ // TODO: Fill request struct fields. @@ -132,13 +129,12 @@ func ExampleClient_UpdateGateway() { } func ExampleClient_DeleteGateway() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.DeleteGatewayRequest{ // TODO: Fill request struct fields. @@ -155,14 +151,12 @@ func ExampleClient_DeleteGateway() { } func ExampleClient_ListApis() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.ListApisRequest{ // TODO: Fill request struct fields. @@ -182,13 +176,12 @@ func ExampleClient_ListApis() { } func ExampleClient_GetApi() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.GetApiRequest{ // TODO: Fill request struct fields. @@ -202,13 +195,12 @@ func ExampleClient_GetApi() { } func ExampleClient_CreateApi() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.CreateApiRequest{ // TODO: Fill request struct fields. @@ -227,13 +219,12 @@ func ExampleClient_CreateApi() { } func ExampleClient_UpdateApi() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.UpdateApiRequest{ // TODO: Fill request struct fields. @@ -252,13 +243,12 @@ func ExampleClient_UpdateApi() { } func ExampleClient_DeleteApi() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.DeleteApiRequest{ // TODO: Fill request struct fields. @@ -275,14 +265,12 @@ func ExampleClient_DeleteApi() { } func ExampleClient_ListApiConfigs() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.ListApiConfigsRequest{ // TODO: Fill request struct fields. @@ -302,13 +290,12 @@ func ExampleClient_ListApiConfigs() { } func ExampleClient_GetApiConfig() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.GetApiConfigRequest{ // TODO: Fill request struct fields. @@ -322,13 +309,12 @@ func ExampleClient_GetApiConfig() { } func ExampleClient_CreateApiConfig() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.CreateApiConfigRequest{ // TODO: Fill request struct fields. @@ -347,13 +333,12 @@ func ExampleClient_CreateApiConfig() { } func ExampleClient_UpdateApiConfig() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.UpdateApiConfigRequest{ // TODO: Fill request struct fields. @@ -372,13 +357,12 @@ func ExampleClient_UpdateApiConfig() { } func ExampleClient_DeleteApiConfig() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.DeleteApiConfigRequest{ // TODO: Fill request struct fields. diff --git a/apigateway/apiv1/doc.go b/apigateway/apiv1/doc.go index 733c6d69e995..cf2cd93e9751 100644 --- a/apigateway/apiv1/doc.go +++ b/apigateway/apiv1/doc.go @@ -26,7 +26,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package apigateway // import "cloud.google.com/go/apigateway/apiv1" import ( @@ -46,7 +46,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/appengine/apiv1/applications_client.go b/appengine/apiv1/applications_client.go index 8a50b21d5125..ad2e51849a13 100644 --- a/appengine/apiv1/applications_client.go +++ b/appengine/apiv1/applications_client.go @@ -45,7 +45,7 @@ type ApplicationsCallOptions struct { RepairApplication []gax.CallOption } -func defaultApplicationsClientOptions() []option.ClientOption { +func defaultApplicationsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("appengine.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("appengine.mtls.googleapis.com:443"), @@ -66,37 +66,149 @@ func defaultApplicationsCallOptions() *ApplicationsCallOptions { } } +// internalApplicationsClient is an interface that defines the methods availaible from App Engine Admin API. +type internalApplicationsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + GetApplication(context.Context, *appenginepb.GetApplicationRequest, ...gax.CallOption) (*appenginepb.Application, error) + CreateApplication(context.Context, *appenginepb.CreateApplicationRequest, ...gax.CallOption) (*CreateApplicationOperation, error) + CreateApplicationOperation(name string) *CreateApplicationOperation + UpdateApplication(context.Context, *appenginepb.UpdateApplicationRequest, ...gax.CallOption) (*UpdateApplicationOperation, error) + UpdateApplicationOperation(name string) *UpdateApplicationOperation + RepairApplication(context.Context, *appenginepb.RepairApplicationRequest, ...gax.CallOption) (*RepairApplicationOperation, error) + RepairApplicationOperation(name string) *RepairApplicationOperation +} + // ApplicationsClient is a client for interacting with App Engine Admin API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Manages App Engine applications. type ApplicationsClient struct { + // The internal transport-dependent client. + internalClient internalApplicationsClient + + // The call options for this service. + CallOptions *ApplicationsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ApplicationsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ApplicationsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ApplicationsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// GetApplication gets information about an application. +func (c *ApplicationsClient) GetApplication(ctx context.Context, req *appenginepb.GetApplicationRequest, opts ...gax.CallOption) (*appenginepb.Application, error) { + return c.internalClient.GetApplication(ctx, req, opts...) +} + +// CreateApplication creates an App Engine application for a Google Cloud Platform project. +// Required fields: +// +// id - The ID of the target Cloud Platform project. +// +// location - The region (at https://cloud.google.com/appengine/docs/locations) where you want the App Engine application located. +// +// For more information about App Engine applications, see Managing Projects, Applications, and Billing (at https://cloud.google.com/appengine/docs/standard/python/console/). +func (c *ApplicationsClient) CreateApplication(ctx context.Context, req *appenginepb.CreateApplicationRequest, opts ...gax.CallOption) (*CreateApplicationOperation, error) { + return c.internalClient.CreateApplication(ctx, req, opts...) +} + +// CreateApplicationOperation returns a new CreateApplicationOperation from a given name. +// The name must be that of a previously created CreateApplicationOperation, possibly from a different process. +func (c *ApplicationsClient) CreateApplicationOperation(name string) *CreateApplicationOperation { + return c.internalClient.CreateApplicationOperation(name) +} + +// UpdateApplication updates the specified Application resource. +// You can update the following fields: +// +// auth_domain - Google authentication domain for controlling user access to the application. +// +// default_cookie_expiration - Cookie expiration policy for the application. +func (c *ApplicationsClient) UpdateApplication(ctx context.Context, req *appenginepb.UpdateApplicationRequest, opts ...gax.CallOption) (*UpdateApplicationOperation, error) { + return c.internalClient.UpdateApplication(ctx, req, opts...) +} + +// UpdateApplicationOperation returns a new UpdateApplicationOperation from a given name. +// The name must be that of a previously created UpdateApplicationOperation, possibly from a different process. +func (c *ApplicationsClient) UpdateApplicationOperation(name string) *UpdateApplicationOperation { + return c.internalClient.UpdateApplicationOperation(name) +} + +// RepairApplication recreates the required App Engine features for the specified App Engine +// application, for example a Cloud Storage bucket or App Engine service +// account. +// Use this method if you receive an error message about a missing feature, +// for example, Error retrieving the App Engine service account. +// If you have deleted your App Engine service account, this will +// not be able to recreate it. Instead, you should attempt to use the +// IAM undelete API if possible at https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params={ (at https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B)“name”%3A"projects%2F-%2FserviceAccounts%2Funique_id"%2C"resource"%3A%7B%7D%7D . +// If the deletion was recent, the numeric ID can be found in the Cloud +// Console Activity Log. +func (c *ApplicationsClient) RepairApplication(ctx context.Context, req *appenginepb.RepairApplicationRequest, opts ...gax.CallOption) (*RepairApplicationOperation, error) { + return c.internalClient.RepairApplication(ctx, req, opts...) +} + +// RepairApplicationOperation returns a new RepairApplicationOperation from a given name. +// The name must be that of a previously created RepairApplicationOperation, possibly from a different process. +func (c *ApplicationsClient) RepairApplicationOperation(name string) *RepairApplicationOperation { + return c.internalClient.RepairApplicationOperation(name) +} + +// applicationsGRPCClient is a client for interacting with App Engine Admin API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type applicationsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ApplicationsClient + CallOptions **ApplicationsCallOptions + // The gRPC API client. applicationsClient appenginepb.ApplicationsClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *ApplicationsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewApplicationsClient creates a new applications client. +// NewApplicationsClient creates a new applications client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Manages App Engine applications. func NewApplicationsClient(ctx context.Context, opts ...option.ClientOption) (*ApplicationsClient, error) { - clientOpts := defaultApplicationsClientOptions() - + clientOpts := defaultApplicationsGRPCClientOptions() if newApplicationsClientHook != nil { hookOpts, err := newApplicationsClientHook(ctx, clientHookParams{}) if err != nil { @@ -114,16 +226,19 @@ func NewApplicationsClient(ctx context.Context, opts ...option.ClientOption) (*A if err != nil { return nil, err } - c := &ApplicationsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultApplicationsCallOptions(), + client := ApplicationsClient{CallOptions: defaultApplicationsCallOptions()} + c := &applicationsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, applicationsClient: appenginepb.NewApplicationsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -133,36 +248,36 @@ func NewApplicationsClient(ctx context.Context, opts ...option.ClientOption) (*A // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ApplicationsClient) Connection() *grpc.ClientConn { +func (c *applicationsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ApplicationsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ApplicationsClient) setGoogleClientInfo(keyval ...string) { +func (c *applicationsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// GetApplication gets information about an application. -func (c *ApplicationsClient) GetApplication(ctx context.Context, req *appenginepb.GetApplicationRequest, opts ...gax.CallOption) (*appenginepb.Application, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *applicationsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *applicationsGRPCClient) GetApplication(ctx context.Context, req *appenginepb.GetApplicationRequest, opts ...gax.CallOption) (*appenginepb.Application, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetApplication[0:len(c.CallOptions.GetApplication):len(c.CallOptions.GetApplication)], opts...) + opts = append((*c.CallOptions).GetApplication[0:len((*c.CallOptions).GetApplication):len((*c.CallOptions).GetApplication)], opts...) var resp *appenginepb.Application err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -175,17 +290,9 @@ func (c *ApplicationsClient) GetApplication(ctx context.Context, req *appenginep return resp, nil } -// CreateApplication creates an App Engine application for a Google Cloud Platform project. -// Required fields: -// -// id - The ID of the target Cloud Platform project. -// -// location - The region (at https://cloud.google.com/appengine/docs/locations) where you want the App Engine application located. -// -// For more information about App Engine applications, see Managing Projects, Applications, and Billing (at https://cloud.google.com/appengine/docs/standard/python/console/). -func (c *ApplicationsClient) CreateApplication(ctx context.Context, req *appenginepb.CreateApplicationRequest, opts ...gax.CallOption) (*CreateApplicationOperation, error) { +func (c *applicationsGRPCClient) CreateApplication(ctx context.Context, req *appenginepb.CreateApplicationRequest, opts ...gax.CallOption) (*CreateApplicationOperation, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.CreateApplication[0:len(c.CallOptions.CreateApplication):len(c.CallOptions.CreateApplication)], opts...) + opts = append((*c.CallOptions).CreateApplication[0:len((*c.CallOptions).CreateApplication):len((*c.CallOptions).CreateApplication)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -196,20 +303,14 @@ func (c *ApplicationsClient) CreateApplication(ctx context.Context, req *appengi return nil, err } return &CreateApplicationOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateApplication updates the specified Application resource. -// You can update the following fields: -// -// auth_domain - Google authentication domain for controlling user access to the application. -// -// default_cookie_expiration - Cookie expiration policy for the application. -func (c *ApplicationsClient) UpdateApplication(ctx context.Context, req *appenginepb.UpdateApplicationRequest, opts ...gax.CallOption) (*UpdateApplicationOperation, error) { +func (c *applicationsGRPCClient) UpdateApplication(ctx context.Context, req *appenginepb.UpdateApplicationRequest, opts ...gax.CallOption) (*UpdateApplicationOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateApplication[0:len(c.CallOptions.UpdateApplication):len(c.CallOptions.UpdateApplication)], opts...) + opts = append((*c.CallOptions).UpdateApplication[0:len((*c.CallOptions).UpdateApplication):len((*c.CallOptions).UpdateApplication)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -220,24 +321,14 @@ func (c *ApplicationsClient) UpdateApplication(ctx context.Context, req *appengi return nil, err } return &UpdateApplicationOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// RepairApplication recreates the required App Engine features for the specified App Engine -// application, for example a Cloud Storage bucket or App Engine service -// account. -// Use this method if you receive an error message about a missing feature, -// for example, Error retrieving the App Engine service account. -// If you have deleted your App Engine service account, this will -// not be able to recreate it. Instead, you should attempt to use the -// IAM undelete API if possible at https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params={ (at https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B)“name”%3A"projects%2F-%2FserviceAccounts%2Funique_id"%2C"resource"%3A%7B%7D%7D . -// If the deletion was recent, the numeric ID can be found in the Cloud -// Console Activity Log. -func (c *ApplicationsClient) RepairApplication(ctx context.Context, req *appenginepb.RepairApplicationRequest, opts ...gax.CallOption) (*RepairApplicationOperation, error) { +func (c *applicationsGRPCClient) RepairApplication(ctx context.Context, req *appenginepb.RepairApplicationRequest, opts ...gax.CallOption) (*RepairApplicationOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RepairApplication[0:len(c.CallOptions.RepairApplication):len(c.CallOptions.RepairApplication)], opts...) + opts = append((*c.CallOptions).RepairApplication[0:len((*c.CallOptions).RepairApplication):len((*c.CallOptions).RepairApplication)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -248,7 +339,7 @@ func (c *ApplicationsClient) RepairApplication(ctx context.Context, req *appengi return nil, err } return &RepairApplicationOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -259,9 +350,9 @@ type CreateApplicationOperation struct { // CreateApplicationOperation returns a new CreateApplicationOperation from a given name. // The name must be that of a previously created CreateApplicationOperation, possibly from a different process. -func (c *ApplicationsClient) CreateApplicationOperation(name string) *CreateApplicationOperation { +func (c *applicationsGRPCClient) CreateApplicationOperation(name string) *CreateApplicationOperation { return &CreateApplicationOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -328,9 +419,9 @@ type RepairApplicationOperation struct { // RepairApplicationOperation returns a new RepairApplicationOperation from a given name. // The name must be that of a previously created RepairApplicationOperation, possibly from a different process. -func (c *ApplicationsClient) RepairApplicationOperation(name string) *RepairApplicationOperation { +func (c *applicationsGRPCClient) RepairApplicationOperation(name string) *RepairApplicationOperation { return &RepairApplicationOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -397,9 +488,9 @@ type UpdateApplicationOperation struct { // UpdateApplicationOperation returns a new UpdateApplicationOperation from a given name. // The name must be that of a previously created UpdateApplicationOperation, possibly from a different process. -func (c *ApplicationsClient) UpdateApplicationOperation(name string) *UpdateApplicationOperation { +func (c *applicationsGRPCClient) UpdateApplicationOperation(name string) *UpdateApplicationOperation { return &UpdateApplicationOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/appengine/apiv1/applications_client_example_test.go b/appengine/apiv1/applications_client_example_test.go index 59566c9c2d72..bb3d9d2aa318 100644 --- a/appengine/apiv1/applications_client_example_test.go +++ b/appengine/apiv1/applications_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewApplicationsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleApplicationsClient_GetApplication() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewApplicationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.GetApplicationRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleApplicationsClient_GetApplication() { } func ExampleApplicationsClient_CreateApplication() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewApplicationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.CreateApplicationRequest{ // TODO: Fill request struct fields. @@ -79,13 +79,12 @@ func ExampleApplicationsClient_CreateApplication() { } func ExampleApplicationsClient_UpdateApplication() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewApplicationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.UpdateApplicationRequest{ // TODO: Fill request struct fields. @@ -104,13 +103,12 @@ func ExampleApplicationsClient_UpdateApplication() { } func ExampleApplicationsClient_RepairApplication() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewApplicationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.RepairApplicationRequest{ // TODO: Fill request struct fields. diff --git a/appengine/apiv1/authorized_certificates_client.go b/appengine/apiv1/authorized_certificates_client.go index db30bfcf6588..755a7bbb2691 100644 --- a/appengine/apiv1/authorized_certificates_client.go +++ b/appengine/apiv1/authorized_certificates_client.go @@ -44,7 +44,7 @@ type AuthorizedCertificatesCallOptions struct { DeleteAuthorizedCertificate []gax.CallOption } -func defaultAuthorizedCertificatesClientOptions() []option.ClientOption { +func defaultAuthorizedCertificatesGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("appengine.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("appengine.mtls.googleapis.com:443"), @@ -66,33 +66,109 @@ func defaultAuthorizedCertificatesCallOptions() *AuthorizedCertificatesCallOptio } } +// internalAuthorizedCertificatesClient is an interface that defines the methods availaible from App Engine Admin API. +type internalAuthorizedCertificatesClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListAuthorizedCertificates(context.Context, *appenginepb.ListAuthorizedCertificatesRequest, ...gax.CallOption) *AuthorizedCertificateIterator + GetAuthorizedCertificate(context.Context, *appenginepb.GetAuthorizedCertificateRequest, ...gax.CallOption) (*appenginepb.AuthorizedCertificate, error) + CreateAuthorizedCertificate(context.Context, *appenginepb.CreateAuthorizedCertificateRequest, ...gax.CallOption) (*appenginepb.AuthorizedCertificate, error) + UpdateAuthorizedCertificate(context.Context, *appenginepb.UpdateAuthorizedCertificateRequest, ...gax.CallOption) (*appenginepb.AuthorizedCertificate, error) + DeleteAuthorizedCertificate(context.Context, *appenginepb.DeleteAuthorizedCertificateRequest, ...gax.CallOption) error +} + // AuthorizedCertificatesClient is a client for interacting with App Engine Admin API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Manages SSL certificates a user is authorized to administer. A user can +// administer any SSL certificates applicable to their authorized domains. type AuthorizedCertificatesClient struct { + // The internal transport-dependent client. + internalClient internalAuthorizedCertificatesClient + + // The call options for this service. + CallOptions *AuthorizedCertificatesCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *AuthorizedCertificatesClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *AuthorizedCertificatesClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *AuthorizedCertificatesClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListAuthorizedCertificates lists all SSL certificates the user is authorized to administer. +func (c *AuthorizedCertificatesClient) ListAuthorizedCertificates(ctx context.Context, req *appenginepb.ListAuthorizedCertificatesRequest, opts ...gax.CallOption) *AuthorizedCertificateIterator { + return c.internalClient.ListAuthorizedCertificates(ctx, req, opts...) +} + +// GetAuthorizedCertificate gets the specified SSL certificate. +func (c *AuthorizedCertificatesClient) GetAuthorizedCertificate(ctx context.Context, req *appenginepb.GetAuthorizedCertificateRequest, opts ...gax.CallOption) (*appenginepb.AuthorizedCertificate, error) { + return c.internalClient.GetAuthorizedCertificate(ctx, req, opts...) +} + +// CreateAuthorizedCertificate uploads the specified SSL certificate. +func (c *AuthorizedCertificatesClient) CreateAuthorizedCertificate(ctx context.Context, req *appenginepb.CreateAuthorizedCertificateRequest, opts ...gax.CallOption) (*appenginepb.AuthorizedCertificate, error) { + return c.internalClient.CreateAuthorizedCertificate(ctx, req, opts...) +} + +// UpdateAuthorizedCertificate updates the specified SSL certificate. To renew a certificate and maintain +// its existing domain mappings, update certificate_data with a new +// certificate. The new certificate must be applicable to the same domains as +// the original certificate. The certificate display_name may also be +// updated. +func (c *AuthorizedCertificatesClient) UpdateAuthorizedCertificate(ctx context.Context, req *appenginepb.UpdateAuthorizedCertificateRequest, opts ...gax.CallOption) (*appenginepb.AuthorizedCertificate, error) { + return c.internalClient.UpdateAuthorizedCertificate(ctx, req, opts...) +} + +// DeleteAuthorizedCertificate deletes the specified SSL certificate. +func (c *AuthorizedCertificatesClient) DeleteAuthorizedCertificate(ctx context.Context, req *appenginepb.DeleteAuthorizedCertificateRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteAuthorizedCertificate(ctx, req, opts...) +} + +// authorizedCertificatesGRPCClient is a client for interacting with App Engine Admin API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type authorizedCertificatesGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing AuthorizedCertificatesClient + CallOptions **AuthorizedCertificatesCallOptions + // The gRPC API client. authorizedCertificatesClient appenginepb.AuthorizedCertificatesClient - // The call options for this service. - CallOptions *AuthorizedCertificatesCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewAuthorizedCertificatesClient creates a new authorized certificates client. +// NewAuthorizedCertificatesClient creates a new authorized certificates client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Manages SSL certificates a user is authorized to administer. A user can // administer any SSL certificates applicable to their authorized domains. func NewAuthorizedCertificatesClient(ctx context.Context, opts ...option.ClientOption) (*AuthorizedCertificatesClient, error) { - clientOpts := defaultAuthorizedCertificatesClientOptions() - + clientOpts := defaultAuthorizedCertificatesGRPCClientOptions() if newAuthorizedCertificatesClientHook != nil { hookOpts, err := newAuthorizedCertificatesClientHook(ctx, clientHookParams{}) if err != nil { @@ -110,45 +186,47 @@ func NewAuthorizedCertificatesClient(ctx context.Context, opts ...option.ClientO if err != nil { return nil, err } - c := &AuthorizedCertificatesClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultAuthorizedCertificatesCallOptions(), + client := AuthorizedCertificatesClient{CallOptions: defaultAuthorizedCertificatesCallOptions()} + c := &authorizedCertificatesGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, authorizedCertificatesClient: appenginepb.NewAuthorizedCertificatesClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *AuthorizedCertificatesClient) Connection() *grpc.ClientConn { +func (c *authorizedCertificatesGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *AuthorizedCertificatesClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *AuthorizedCertificatesClient) setGoogleClientInfo(keyval ...string) { +func (c *authorizedCertificatesGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListAuthorizedCertificates lists all SSL certificates the user is authorized to administer. -func (c *AuthorizedCertificatesClient) ListAuthorizedCertificates(ctx context.Context, req *appenginepb.ListAuthorizedCertificatesRequest, opts ...gax.CallOption) *AuthorizedCertificateIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *authorizedCertificatesGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *authorizedCertificatesGRPCClient) ListAuthorizedCertificates(ctx context.Context, req *appenginepb.ListAuthorizedCertificatesRequest, opts ...gax.CallOption) *AuthorizedCertificateIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAuthorizedCertificates[0:len(c.CallOptions.ListAuthorizedCertificates):len(c.CallOptions.ListAuthorizedCertificates)], opts...) + opts = append((*c.CallOptions).ListAuthorizedCertificates[0:len((*c.CallOptions).ListAuthorizedCertificates):len((*c.CallOptions).ListAuthorizedCertificates)], opts...) it := &AuthorizedCertificateIterator{} req = proto.Clone(req).(*appenginepb.ListAuthorizedCertificatesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*appenginepb.AuthorizedCertificate, string, error) { @@ -185,11 +263,10 @@ func (c *AuthorizedCertificatesClient) ListAuthorizedCertificates(ctx context.Co return it } -// GetAuthorizedCertificate gets the specified SSL certificate. -func (c *AuthorizedCertificatesClient) GetAuthorizedCertificate(ctx context.Context, req *appenginepb.GetAuthorizedCertificateRequest, opts ...gax.CallOption) (*appenginepb.AuthorizedCertificate, error) { +func (c *authorizedCertificatesGRPCClient) GetAuthorizedCertificate(ctx context.Context, req *appenginepb.GetAuthorizedCertificateRequest, opts ...gax.CallOption) (*appenginepb.AuthorizedCertificate, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetAuthorizedCertificate[0:len(c.CallOptions.GetAuthorizedCertificate):len(c.CallOptions.GetAuthorizedCertificate)], opts...) + opts = append((*c.CallOptions).GetAuthorizedCertificate[0:len((*c.CallOptions).GetAuthorizedCertificate):len((*c.CallOptions).GetAuthorizedCertificate)], opts...) var resp *appenginepb.AuthorizedCertificate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -202,11 +279,10 @@ func (c *AuthorizedCertificatesClient) GetAuthorizedCertificate(ctx context.Cont return resp, nil } -// CreateAuthorizedCertificate uploads the specified SSL certificate. -func (c *AuthorizedCertificatesClient) CreateAuthorizedCertificate(ctx context.Context, req *appenginepb.CreateAuthorizedCertificateRequest, opts ...gax.CallOption) (*appenginepb.AuthorizedCertificate, error) { +func (c *authorizedCertificatesGRPCClient) CreateAuthorizedCertificate(ctx context.Context, req *appenginepb.CreateAuthorizedCertificateRequest, opts ...gax.CallOption) (*appenginepb.AuthorizedCertificate, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateAuthorizedCertificate[0:len(c.CallOptions.CreateAuthorizedCertificate):len(c.CallOptions.CreateAuthorizedCertificate)], opts...) + opts = append((*c.CallOptions).CreateAuthorizedCertificate[0:len((*c.CallOptions).CreateAuthorizedCertificate):len((*c.CallOptions).CreateAuthorizedCertificate)], opts...) var resp *appenginepb.AuthorizedCertificate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -219,15 +295,10 @@ func (c *AuthorizedCertificatesClient) CreateAuthorizedCertificate(ctx context.C return resp, nil } -// UpdateAuthorizedCertificate updates the specified SSL certificate. To renew a certificate and maintain -// its existing domain mappings, update certificate_data with a new -// certificate. The new certificate must be applicable to the same domains as -// the original certificate. The certificate display_name may also be -// updated. -func (c *AuthorizedCertificatesClient) UpdateAuthorizedCertificate(ctx context.Context, req *appenginepb.UpdateAuthorizedCertificateRequest, opts ...gax.CallOption) (*appenginepb.AuthorizedCertificate, error) { +func (c *authorizedCertificatesGRPCClient) UpdateAuthorizedCertificate(ctx context.Context, req *appenginepb.UpdateAuthorizedCertificateRequest, opts ...gax.CallOption) (*appenginepb.AuthorizedCertificate, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateAuthorizedCertificate[0:len(c.CallOptions.UpdateAuthorizedCertificate):len(c.CallOptions.UpdateAuthorizedCertificate)], opts...) + opts = append((*c.CallOptions).UpdateAuthorizedCertificate[0:len((*c.CallOptions).UpdateAuthorizedCertificate):len((*c.CallOptions).UpdateAuthorizedCertificate)], opts...) var resp *appenginepb.AuthorizedCertificate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -240,11 +311,10 @@ func (c *AuthorizedCertificatesClient) UpdateAuthorizedCertificate(ctx context.C return resp, nil } -// DeleteAuthorizedCertificate deletes the specified SSL certificate. -func (c *AuthorizedCertificatesClient) DeleteAuthorizedCertificate(ctx context.Context, req *appenginepb.DeleteAuthorizedCertificateRequest, opts ...gax.CallOption) error { +func (c *authorizedCertificatesGRPCClient) DeleteAuthorizedCertificate(ctx context.Context, req *appenginepb.DeleteAuthorizedCertificateRequest, opts ...gax.CallOption) error { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteAuthorizedCertificate[0:len(c.CallOptions.DeleteAuthorizedCertificate):len(c.CallOptions.DeleteAuthorizedCertificate)], opts...) + opts = append((*c.CallOptions).DeleteAuthorizedCertificate[0:len((*c.CallOptions).DeleteAuthorizedCertificate):len((*c.CallOptions).DeleteAuthorizedCertificate)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.authorizedCertificatesClient.DeleteAuthorizedCertificate(ctx, req, settings.GRPC...) diff --git a/appengine/apiv1/authorized_certificates_client_example_test.go b/appengine/apiv1/authorized_certificates_client_example_test.go index 901b771c71fc..24e672c5956b 100644 --- a/appengine/apiv1/authorized_certificates_client_example_test.go +++ b/appengine/apiv1/authorized_certificates_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewAuthorizedCertificatesClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleAuthorizedCertificatesClient_ListAuthorizedCertificates() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := appengine.NewAuthorizedCertificatesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.ListAuthorizedCertificatesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleAuthorizedCertificatesClient_ListAuthorizedCertificates() { } func ExampleAuthorizedCertificatesClient_GetAuthorizedCertificate() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewAuthorizedCertificatesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.GetAuthorizedCertificateRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleAuthorizedCertificatesClient_GetAuthorizedCertificate() { } func ExampleAuthorizedCertificatesClient_CreateAuthorizedCertificate() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewAuthorizedCertificatesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.CreateAuthorizedCertificateRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleAuthorizedCertificatesClient_CreateAuthorizedCertificate() { } func ExampleAuthorizedCertificatesClient_UpdateAuthorizedCertificate() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewAuthorizedCertificatesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.UpdateAuthorizedCertificateRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleAuthorizedCertificatesClient_DeleteAuthorizedCertificate() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.DeleteAuthorizedCertificateRequest{ // TODO: Fill request struct fields. diff --git a/appengine/apiv1/authorized_domains_client.go b/appengine/apiv1/authorized_domains_client.go index 087e037a010a..2308e7c0578a 100644 --- a/appengine/apiv1/authorized_domains_client.go +++ b/appengine/apiv1/authorized_domains_client.go @@ -40,7 +40,7 @@ type AuthorizedDomainsCallOptions struct { ListAuthorizedDomains []gax.CallOption } -func defaultAuthorizedDomainsClientOptions() []option.ClientOption { +func defaultAuthorizedDomainsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("appengine.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("appengine.mtls.googleapis.com:443"), @@ -58,34 +58,83 @@ func defaultAuthorizedDomainsCallOptions() *AuthorizedDomainsCallOptions { } } +// internalAuthorizedDomainsClient is an interface that defines the methods availaible from App Engine Admin API. +type internalAuthorizedDomainsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListAuthorizedDomains(context.Context, *appenginepb.ListAuthorizedDomainsRequest, ...gax.CallOption) *AuthorizedDomainIterator +} + // AuthorizedDomainsClient is a client for interacting with App Engine Admin API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Manages domains a user is authorized to administer. To authorize use of a +// domain, verify ownership via +// Webmaster Central (at https://www.google.com/webmasters/verification/home). type AuthorizedDomainsClient struct { + // The internal transport-dependent client. + internalClient internalAuthorizedDomainsClient + + // The call options for this service. + CallOptions *AuthorizedDomainsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *AuthorizedDomainsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *AuthorizedDomainsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *AuthorizedDomainsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListAuthorizedDomains lists all domains the user is authorized to administer. +func (c *AuthorizedDomainsClient) ListAuthorizedDomains(ctx context.Context, req *appenginepb.ListAuthorizedDomainsRequest, opts ...gax.CallOption) *AuthorizedDomainIterator { + return c.internalClient.ListAuthorizedDomains(ctx, req, opts...) +} + +// authorizedDomainsGRPCClient is a client for interacting with App Engine Admin API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type authorizedDomainsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing AuthorizedDomainsClient + CallOptions **AuthorizedDomainsCallOptions + // The gRPC API client. authorizedDomainsClient appenginepb.AuthorizedDomainsClient - // The call options for this service. - CallOptions *AuthorizedDomainsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewAuthorizedDomainsClient creates a new authorized domains client. +// NewAuthorizedDomainsClient creates a new authorized domains client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Manages domains a user is authorized to administer. To authorize use of a // domain, verify ownership via // Webmaster Central (at https://www.google.com/webmasters/verification/home). func NewAuthorizedDomainsClient(ctx context.Context, opts ...option.ClientOption) (*AuthorizedDomainsClient, error) { - clientOpts := defaultAuthorizedDomainsClientOptions() - + clientOpts := defaultAuthorizedDomainsGRPCClientOptions() if newAuthorizedDomainsClientHook != nil { hookOpts, err := newAuthorizedDomainsClientHook(ctx, clientHookParams{}) if err != nil { @@ -103,45 +152,47 @@ func NewAuthorizedDomainsClient(ctx context.Context, opts ...option.ClientOption if err != nil { return nil, err } - c := &AuthorizedDomainsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultAuthorizedDomainsCallOptions(), + client := AuthorizedDomainsClient{CallOptions: defaultAuthorizedDomainsCallOptions()} + c := &authorizedDomainsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, authorizedDomainsClient: appenginepb.NewAuthorizedDomainsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *AuthorizedDomainsClient) Connection() *grpc.ClientConn { +func (c *authorizedDomainsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *AuthorizedDomainsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *AuthorizedDomainsClient) setGoogleClientInfo(keyval ...string) { +func (c *authorizedDomainsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListAuthorizedDomains lists all domains the user is authorized to administer. -func (c *AuthorizedDomainsClient) ListAuthorizedDomains(ctx context.Context, req *appenginepb.ListAuthorizedDomainsRequest, opts ...gax.CallOption) *AuthorizedDomainIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *authorizedDomainsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *authorizedDomainsGRPCClient) ListAuthorizedDomains(ctx context.Context, req *appenginepb.ListAuthorizedDomainsRequest, opts ...gax.CallOption) *AuthorizedDomainIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAuthorizedDomains[0:len(c.CallOptions.ListAuthorizedDomains):len(c.CallOptions.ListAuthorizedDomains)], opts...) + opts = append((*c.CallOptions).ListAuthorizedDomains[0:len((*c.CallOptions).ListAuthorizedDomains):len((*c.CallOptions).ListAuthorizedDomains)], opts...) it := &AuthorizedDomainIterator{} req = proto.Clone(req).(*appenginepb.ListAuthorizedDomainsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*appenginepb.AuthorizedDomain, string, error) { diff --git a/appengine/apiv1/authorized_domains_client_example_test.go b/appengine/apiv1/authorized_domains_client_example_test.go index 88d1b6028e2d..2161278a41b6 100644 --- a/appengine/apiv1/authorized_domains_client_example_test.go +++ b/appengine/apiv1/authorized_domains_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewAuthorizedDomainsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleAuthorizedDomainsClient_ListAuthorizedDomains() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := appengine.NewAuthorizedDomainsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.ListAuthorizedDomainsRequest{ // TODO: Fill request struct fields. diff --git a/appengine/apiv1/doc.go b/appengine/apiv1/doc.go index a5431787daf3..454756aeeab7 100644 --- a/appengine/apiv1/doc.go +++ b/appengine/apiv1/doc.go @@ -17,7 +17,7 @@ // Package appengine is an auto-generated package for the // App Engine Admin API. // -// Provisions and manages developers' App Engine applications. +// Provisions and manages developers’ App Engine applications. // // Use of Context // @@ -28,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package appengine // import "cloud.google.com/go/appengine/apiv1" import ( @@ -48,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/appengine/apiv1/domain_mappings_client.go b/appengine/apiv1/domain_mappings_client.go index b8814b9f0e6a..f950fff6ac1e 100644 --- a/appengine/apiv1/domain_mappings_client.go +++ b/appengine/apiv1/domain_mappings_client.go @@ -48,7 +48,7 @@ type DomainMappingsCallOptions struct { DeleteDomainMapping []gax.CallOption } -func defaultDomainMappingsClientOptions() []option.ClientOption { +func defaultDomainMappingsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("appengine.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("appengine.mtls.googleapis.com:443"), @@ -70,37 +70,141 @@ func defaultDomainMappingsCallOptions() *DomainMappingsCallOptions { } } +// internalDomainMappingsClient is an interface that defines the methods availaible from App Engine Admin API. +type internalDomainMappingsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListDomainMappings(context.Context, *appenginepb.ListDomainMappingsRequest, ...gax.CallOption) *DomainMappingIterator + GetDomainMapping(context.Context, *appenginepb.GetDomainMappingRequest, ...gax.CallOption) (*appenginepb.DomainMapping, error) + CreateDomainMapping(context.Context, *appenginepb.CreateDomainMappingRequest, ...gax.CallOption) (*CreateDomainMappingOperation, error) + CreateDomainMappingOperation(name string) *CreateDomainMappingOperation + UpdateDomainMapping(context.Context, *appenginepb.UpdateDomainMappingRequest, ...gax.CallOption) (*UpdateDomainMappingOperation, error) + UpdateDomainMappingOperation(name string) *UpdateDomainMappingOperation + DeleteDomainMapping(context.Context, *appenginepb.DeleteDomainMappingRequest, ...gax.CallOption) (*DeleteDomainMappingOperation, error) + DeleteDomainMappingOperation(name string) *DeleteDomainMappingOperation +} + // DomainMappingsClient is a client for interacting with App Engine Admin API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Manages domains serving an application. type DomainMappingsClient struct { + // The internal transport-dependent client. + internalClient internalDomainMappingsClient + + // The call options for this service. + CallOptions *DomainMappingsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *DomainMappingsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *DomainMappingsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *DomainMappingsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListDomainMappings lists the domain mappings on an application. +func (c *DomainMappingsClient) ListDomainMappings(ctx context.Context, req *appenginepb.ListDomainMappingsRequest, opts ...gax.CallOption) *DomainMappingIterator { + return c.internalClient.ListDomainMappings(ctx, req, opts...) +} + +// GetDomainMapping gets the specified domain mapping. +func (c *DomainMappingsClient) GetDomainMapping(ctx context.Context, req *appenginepb.GetDomainMappingRequest, opts ...gax.CallOption) (*appenginepb.DomainMapping, error) { + return c.internalClient.GetDomainMapping(ctx, req, opts...) +} + +// CreateDomainMapping maps a domain to an application. A user must be authorized to administer a +// domain in order to map it to an application. For a list of available +// authorized domains, see AuthorizedDomains.ListAuthorizedDomains (at ). +func (c *DomainMappingsClient) CreateDomainMapping(ctx context.Context, req *appenginepb.CreateDomainMappingRequest, opts ...gax.CallOption) (*CreateDomainMappingOperation, error) { + return c.internalClient.CreateDomainMapping(ctx, req, opts...) +} + +// CreateDomainMappingOperation returns a new CreateDomainMappingOperation from a given name. +// The name must be that of a previously created CreateDomainMappingOperation, possibly from a different process. +func (c *DomainMappingsClient) CreateDomainMappingOperation(name string) *CreateDomainMappingOperation { + return c.internalClient.CreateDomainMappingOperation(name) +} + +// UpdateDomainMapping updates the specified domain mapping. To map an SSL certificate to a +// domain mapping, update certificate_id to point to an AuthorizedCertificate +// resource. A user must be authorized to administer the associated domain +// in order to update a DomainMapping resource. +func (c *DomainMappingsClient) UpdateDomainMapping(ctx context.Context, req *appenginepb.UpdateDomainMappingRequest, opts ...gax.CallOption) (*UpdateDomainMappingOperation, error) { + return c.internalClient.UpdateDomainMapping(ctx, req, opts...) +} + +// UpdateDomainMappingOperation returns a new UpdateDomainMappingOperation from a given name. +// The name must be that of a previously created UpdateDomainMappingOperation, possibly from a different process. +func (c *DomainMappingsClient) UpdateDomainMappingOperation(name string) *UpdateDomainMappingOperation { + return c.internalClient.UpdateDomainMappingOperation(name) +} + +// DeleteDomainMapping deletes the specified domain mapping. A user must be authorized to +// administer the associated domain in order to delete a DomainMapping +// resource. +func (c *DomainMappingsClient) DeleteDomainMapping(ctx context.Context, req *appenginepb.DeleteDomainMappingRequest, opts ...gax.CallOption) (*DeleteDomainMappingOperation, error) { + return c.internalClient.DeleteDomainMapping(ctx, req, opts...) +} + +// DeleteDomainMappingOperation returns a new DeleteDomainMappingOperation from a given name. +// The name must be that of a previously created DeleteDomainMappingOperation, possibly from a different process. +func (c *DomainMappingsClient) DeleteDomainMappingOperation(name string) *DeleteDomainMappingOperation { + return c.internalClient.DeleteDomainMappingOperation(name) +} + +// domainMappingsGRPCClient is a client for interacting with App Engine Admin API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type domainMappingsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing DomainMappingsClient + CallOptions **DomainMappingsCallOptions + // The gRPC API client. domainMappingsClient appenginepb.DomainMappingsClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *DomainMappingsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewDomainMappingsClient creates a new domain mappings client. +// NewDomainMappingsClient creates a new domain mappings client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Manages domains serving an application. func NewDomainMappingsClient(ctx context.Context, opts ...option.ClientOption) (*DomainMappingsClient, error) { - clientOpts := defaultDomainMappingsClientOptions() - + clientOpts := defaultDomainMappingsGRPCClientOptions() if newDomainMappingsClientHook != nil { hookOpts, err := newDomainMappingsClientHook(ctx, clientHookParams{}) if err != nil { @@ -118,16 +222,19 @@ func NewDomainMappingsClient(ctx context.Context, opts ...option.ClientOption) ( if err != nil { return nil, err } - c := &DomainMappingsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultDomainMappingsCallOptions(), + client := DomainMappingsClient{CallOptions: defaultDomainMappingsCallOptions()} + c := &domainMappingsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, domainMappingsClient: appenginepb.NewDomainMappingsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -137,36 +244,36 @@ func NewDomainMappingsClient(ctx context.Context, opts ...option.ClientOption) ( // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *DomainMappingsClient) Connection() *grpc.ClientConn { +func (c *domainMappingsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *DomainMappingsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *DomainMappingsClient) setGoogleClientInfo(keyval ...string) { +func (c *domainMappingsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListDomainMappings lists the domain mappings on an application. -func (c *DomainMappingsClient) ListDomainMappings(ctx context.Context, req *appenginepb.ListDomainMappingsRequest, opts ...gax.CallOption) *DomainMappingIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *domainMappingsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *domainMappingsGRPCClient) ListDomainMappings(ctx context.Context, req *appenginepb.ListDomainMappingsRequest, opts ...gax.CallOption) *DomainMappingIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDomainMappings[0:len(c.CallOptions.ListDomainMappings):len(c.CallOptions.ListDomainMappings)], opts...) + opts = append((*c.CallOptions).ListDomainMappings[0:len((*c.CallOptions).ListDomainMappings):len((*c.CallOptions).ListDomainMappings)], opts...) it := &DomainMappingIterator{} req = proto.Clone(req).(*appenginepb.ListDomainMappingsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*appenginepb.DomainMapping, string, error) { @@ -203,11 +310,10 @@ func (c *DomainMappingsClient) ListDomainMappings(ctx context.Context, req *appe return it } -// GetDomainMapping gets the specified domain mapping. -func (c *DomainMappingsClient) GetDomainMapping(ctx context.Context, req *appenginepb.GetDomainMappingRequest, opts ...gax.CallOption) (*appenginepb.DomainMapping, error) { +func (c *domainMappingsGRPCClient) GetDomainMapping(ctx context.Context, req *appenginepb.GetDomainMappingRequest, opts ...gax.CallOption) (*appenginepb.DomainMapping, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetDomainMapping[0:len(c.CallOptions.GetDomainMapping):len(c.CallOptions.GetDomainMapping)], opts...) + opts = append((*c.CallOptions).GetDomainMapping[0:len((*c.CallOptions).GetDomainMapping):len((*c.CallOptions).GetDomainMapping)], opts...) var resp *appenginepb.DomainMapping err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -220,13 +326,10 @@ func (c *DomainMappingsClient) GetDomainMapping(ctx context.Context, req *appeng return resp, nil } -// CreateDomainMapping maps a domain to an application. A user must be authorized to administer a -// domain in order to map it to an application. For a list of available -// authorized domains, see AuthorizedDomains.ListAuthorizedDomains (at ). -func (c *DomainMappingsClient) CreateDomainMapping(ctx context.Context, req *appenginepb.CreateDomainMappingRequest, opts ...gax.CallOption) (*CreateDomainMappingOperation, error) { +func (c *domainMappingsGRPCClient) CreateDomainMapping(ctx context.Context, req *appenginepb.CreateDomainMappingRequest, opts ...gax.CallOption) (*CreateDomainMappingOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateDomainMapping[0:len(c.CallOptions.CreateDomainMapping):len(c.CallOptions.CreateDomainMapping)], opts...) + opts = append((*c.CallOptions).CreateDomainMapping[0:len((*c.CallOptions).CreateDomainMapping):len((*c.CallOptions).CreateDomainMapping)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -237,18 +340,14 @@ func (c *DomainMappingsClient) CreateDomainMapping(ctx context.Context, req *app return nil, err } return &CreateDomainMappingOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateDomainMapping updates the specified domain mapping. To map an SSL certificate to a -// domain mapping, update certificate_id to point to an AuthorizedCertificate -// resource. A user must be authorized to administer the associated domain -// in order to update a DomainMapping resource. -func (c *DomainMappingsClient) UpdateDomainMapping(ctx context.Context, req *appenginepb.UpdateDomainMappingRequest, opts ...gax.CallOption) (*UpdateDomainMappingOperation, error) { +func (c *domainMappingsGRPCClient) UpdateDomainMapping(ctx context.Context, req *appenginepb.UpdateDomainMappingRequest, opts ...gax.CallOption) (*UpdateDomainMappingOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateDomainMapping[0:len(c.CallOptions.UpdateDomainMapping):len(c.CallOptions.UpdateDomainMapping)], opts...) + opts = append((*c.CallOptions).UpdateDomainMapping[0:len((*c.CallOptions).UpdateDomainMapping):len((*c.CallOptions).UpdateDomainMapping)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -259,17 +358,14 @@ func (c *DomainMappingsClient) UpdateDomainMapping(ctx context.Context, req *app return nil, err } return &UpdateDomainMappingOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteDomainMapping deletes the specified domain mapping. A user must be authorized to -// administer the associated domain in order to delete a DomainMapping -// resource. -func (c *DomainMappingsClient) DeleteDomainMapping(ctx context.Context, req *appenginepb.DeleteDomainMappingRequest, opts ...gax.CallOption) (*DeleteDomainMappingOperation, error) { +func (c *domainMappingsGRPCClient) DeleteDomainMapping(ctx context.Context, req *appenginepb.DeleteDomainMappingRequest, opts ...gax.CallOption) (*DeleteDomainMappingOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteDomainMapping[0:len(c.CallOptions.DeleteDomainMapping):len(c.CallOptions.DeleteDomainMapping)], opts...) + opts = append((*c.CallOptions).DeleteDomainMapping[0:len((*c.CallOptions).DeleteDomainMapping):len((*c.CallOptions).DeleteDomainMapping)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -280,7 +376,7 @@ func (c *DomainMappingsClient) DeleteDomainMapping(ctx context.Context, req *app return nil, err } return &DeleteDomainMappingOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -291,9 +387,9 @@ type CreateDomainMappingOperation struct { // CreateDomainMappingOperation returns a new CreateDomainMappingOperation from a given name. // The name must be that of a previously created CreateDomainMappingOperation, possibly from a different process. -func (c *DomainMappingsClient) CreateDomainMappingOperation(name string) *CreateDomainMappingOperation { +func (c *domainMappingsGRPCClient) CreateDomainMappingOperation(name string) *CreateDomainMappingOperation { return &CreateDomainMappingOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -360,9 +456,9 @@ type DeleteDomainMappingOperation struct { // DeleteDomainMappingOperation returns a new DeleteDomainMappingOperation from a given name. // The name must be that of a previously created DeleteDomainMappingOperation, possibly from a different process. -func (c *DomainMappingsClient) DeleteDomainMappingOperation(name string) *DeleteDomainMappingOperation { +func (c *domainMappingsGRPCClient) DeleteDomainMappingOperation(name string) *DeleteDomainMappingOperation { return &DeleteDomainMappingOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -418,9 +514,9 @@ type UpdateDomainMappingOperation struct { // UpdateDomainMappingOperation returns a new UpdateDomainMappingOperation from a given name. // The name must be that of a previously created UpdateDomainMappingOperation, possibly from a different process. -func (c *DomainMappingsClient) UpdateDomainMappingOperation(name string) *UpdateDomainMappingOperation { +func (c *domainMappingsGRPCClient) UpdateDomainMappingOperation(name string) *UpdateDomainMappingOperation { return &UpdateDomainMappingOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/appengine/apiv1/domain_mappings_client_example_test.go b/appengine/apiv1/domain_mappings_client_example_test.go index f3aed5113145..c0893f44a4c5 100644 --- a/appengine/apiv1/domain_mappings_client_example_test.go +++ b/appengine/apiv1/domain_mappings_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewDomainMappingsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleDomainMappingsClient_ListDomainMappings() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := appengine.NewDomainMappingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.ListDomainMappingsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleDomainMappingsClient_ListDomainMappings() { } func ExampleDomainMappingsClient_GetDomainMapping() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewDomainMappingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.GetDomainMappingRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleDomainMappingsClient_GetDomainMapping() { } func ExampleDomainMappingsClient_CreateDomainMapping() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewDomainMappingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.CreateDomainMappingRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleDomainMappingsClient_CreateDomainMapping() { } func ExampleDomainMappingsClient_UpdateDomainMapping() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewDomainMappingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.UpdateDomainMappingRequest{ // TODO: Fill request struct fields. @@ -132,13 +129,12 @@ func ExampleDomainMappingsClient_UpdateDomainMapping() { } func ExampleDomainMappingsClient_DeleteDomainMapping() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewDomainMappingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.DeleteDomainMappingRequest{ // TODO: Fill request struct fields. diff --git a/appengine/apiv1/firewall_client.go b/appengine/apiv1/firewall_client.go index c241c2be8303..c7f70b6aa75b 100644 --- a/appengine/apiv1/firewall_client.go +++ b/appengine/apiv1/firewall_client.go @@ -45,7 +45,7 @@ type FirewallCallOptions struct { DeleteIngressRule []gax.CallOption } -func defaultFirewallClientOptions() []option.ClientOption { +func defaultFirewallGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("appengine.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("appengine.mtls.googleapis.com:443"), @@ -68,27 +68,118 @@ func defaultFirewallCallOptions() *FirewallCallOptions { } } +// internalFirewallClient is an interface that defines the methods availaible from App Engine Admin API. +type internalFirewallClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListIngressRules(context.Context, *appenginepb.ListIngressRulesRequest, ...gax.CallOption) *FirewallRuleIterator + BatchUpdateIngressRules(context.Context, *appenginepb.BatchUpdateIngressRulesRequest, ...gax.CallOption) (*appenginepb.BatchUpdateIngressRulesResponse, error) + CreateIngressRule(context.Context, *appenginepb.CreateIngressRuleRequest, ...gax.CallOption) (*appenginepb.FirewallRule, error) + GetIngressRule(context.Context, *appenginepb.GetIngressRuleRequest, ...gax.CallOption) (*appenginepb.FirewallRule, error) + UpdateIngressRule(context.Context, *appenginepb.UpdateIngressRuleRequest, ...gax.CallOption) (*appenginepb.FirewallRule, error) + DeleteIngressRule(context.Context, *appenginepb.DeleteIngressRuleRequest, ...gax.CallOption) error +} + // FirewallClient is a client for interacting with App Engine Admin API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Firewall resources are used to define a collection of access control rules +// for an Application. Each rule is defined with a position which specifies +// the rule’s order in the sequence of rules, an IP range to be matched against +// requests, and an action to take upon matching requests. +// +// Every request is evaluated against the Firewall rules in priority order. +// Processesing stops at the first rule which matches the request’s IP address. +// A final rule always specifies an action that applies to all remaining +// IP addresses. The default final rule for a newly-created application will be +// set to “allow” if not otherwise specified by the user. type FirewallClient struct { + // The internal transport-dependent client. + internalClient internalFirewallClient + + // The call options for this service. + CallOptions *FirewallCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *FirewallClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *FirewallClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *FirewallClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListIngressRules lists the firewall rules of an application. +func (c *FirewallClient) ListIngressRules(ctx context.Context, req *appenginepb.ListIngressRulesRequest, opts ...gax.CallOption) *FirewallRuleIterator { + return c.internalClient.ListIngressRules(ctx, req, opts...) +} + +// BatchUpdateIngressRules replaces the entire firewall ruleset in one bulk operation. This overrides +// and replaces the rules of an existing firewall with the new rules. +// +// If the final rule does not match traffic with the ‘*’ wildcard IP range, +// then an “allow all” rule is explicitly added to the end of the list. +func (c *FirewallClient) BatchUpdateIngressRules(ctx context.Context, req *appenginepb.BatchUpdateIngressRulesRequest, opts ...gax.CallOption) (*appenginepb.BatchUpdateIngressRulesResponse, error) { + return c.internalClient.BatchUpdateIngressRules(ctx, req, opts...) +} + +// CreateIngressRule creates a firewall rule for the application. +func (c *FirewallClient) CreateIngressRule(ctx context.Context, req *appenginepb.CreateIngressRuleRequest, opts ...gax.CallOption) (*appenginepb.FirewallRule, error) { + return c.internalClient.CreateIngressRule(ctx, req, opts...) +} + +// GetIngressRule gets the specified firewall rule. +func (c *FirewallClient) GetIngressRule(ctx context.Context, req *appenginepb.GetIngressRuleRequest, opts ...gax.CallOption) (*appenginepb.FirewallRule, error) { + return c.internalClient.GetIngressRule(ctx, req, opts...) +} + +// UpdateIngressRule updates the specified firewall rule. +func (c *FirewallClient) UpdateIngressRule(ctx context.Context, req *appenginepb.UpdateIngressRuleRequest, opts ...gax.CallOption) (*appenginepb.FirewallRule, error) { + return c.internalClient.UpdateIngressRule(ctx, req, opts...) +} + +// DeleteIngressRule deletes the specified firewall rule. +func (c *FirewallClient) DeleteIngressRule(ctx context.Context, req *appenginepb.DeleteIngressRuleRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteIngressRule(ctx, req, opts...) +} + +// firewallGRPCClient is a client for interacting with App Engine Admin API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type firewallGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing FirewallClient + CallOptions **FirewallCallOptions + // The gRPC API client. firewallClient appenginepb.FirewallClient - // The call options for this service. - CallOptions *FirewallCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewFirewallClient creates a new firewall client. +// NewFirewallClient creates a new firewall client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Firewall resources are used to define a collection of access control rules // for an Application. Each rule is defined with a position which specifies @@ -101,8 +192,7 @@ type FirewallClient struct { // IP addresses. The default final rule for a newly-created application will be // set to “allow” if not otherwise specified by the user. func NewFirewallClient(ctx context.Context, opts ...option.ClientOption) (*FirewallClient, error) { - clientOpts := defaultFirewallClientOptions() - + clientOpts := defaultFirewallGRPCClientOptions() if newFirewallClientHook != nil { hookOpts, err := newFirewallClientHook(ctx, clientHookParams{}) if err != nil { @@ -120,45 +210,47 @@ func NewFirewallClient(ctx context.Context, opts ...option.ClientOption) (*Firew if err != nil { return nil, err } - c := &FirewallClient{ + client := FirewallClient{CallOptions: defaultFirewallCallOptions()} + + c := &firewallGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultFirewallCallOptions(), - - firewallClient: appenginepb.NewFirewallClient(connPool), + firewallClient: appenginepb.NewFirewallClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *FirewallClient) Connection() *grpc.ClientConn { +func (c *firewallGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *FirewallClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *FirewallClient) setGoogleClientInfo(keyval ...string) { +func (c *firewallGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListIngressRules lists the firewall rules of an application. -func (c *FirewallClient) ListIngressRules(ctx context.Context, req *appenginepb.ListIngressRulesRequest, opts ...gax.CallOption) *FirewallRuleIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *firewallGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *firewallGRPCClient) ListIngressRules(ctx context.Context, req *appenginepb.ListIngressRulesRequest, opts ...gax.CallOption) *FirewallRuleIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListIngressRules[0:len(c.CallOptions.ListIngressRules):len(c.CallOptions.ListIngressRules)], opts...) + opts = append((*c.CallOptions).ListIngressRules[0:len((*c.CallOptions).ListIngressRules):len((*c.CallOptions).ListIngressRules)], opts...) it := &FirewallRuleIterator{} req = proto.Clone(req).(*appenginepb.ListIngressRulesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*appenginepb.FirewallRule, string, error) { @@ -195,15 +287,10 @@ func (c *FirewallClient) ListIngressRules(ctx context.Context, req *appenginepb. return it } -// BatchUpdateIngressRules replaces the entire firewall ruleset in one bulk operation. This overrides -// and replaces the rules of an existing firewall with the new rules. -// -// If the final rule does not match traffic with the ‘*’ wildcard IP range, -// then an “allow all” rule is explicitly added to the end of the list. -func (c *FirewallClient) BatchUpdateIngressRules(ctx context.Context, req *appenginepb.BatchUpdateIngressRulesRequest, opts ...gax.CallOption) (*appenginepb.BatchUpdateIngressRulesResponse, error) { +func (c *firewallGRPCClient) BatchUpdateIngressRules(ctx context.Context, req *appenginepb.BatchUpdateIngressRulesRequest, opts ...gax.CallOption) (*appenginepb.BatchUpdateIngressRulesResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchUpdateIngressRules[0:len(c.CallOptions.BatchUpdateIngressRules):len(c.CallOptions.BatchUpdateIngressRules)], opts...) + opts = append((*c.CallOptions).BatchUpdateIngressRules[0:len((*c.CallOptions).BatchUpdateIngressRules):len((*c.CallOptions).BatchUpdateIngressRules)], opts...) var resp *appenginepb.BatchUpdateIngressRulesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -216,11 +303,10 @@ func (c *FirewallClient) BatchUpdateIngressRules(ctx context.Context, req *appen return resp, nil } -// CreateIngressRule creates a firewall rule for the application. -func (c *FirewallClient) CreateIngressRule(ctx context.Context, req *appenginepb.CreateIngressRuleRequest, opts ...gax.CallOption) (*appenginepb.FirewallRule, error) { +func (c *firewallGRPCClient) CreateIngressRule(ctx context.Context, req *appenginepb.CreateIngressRuleRequest, opts ...gax.CallOption) (*appenginepb.FirewallRule, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateIngressRule[0:len(c.CallOptions.CreateIngressRule):len(c.CallOptions.CreateIngressRule)], opts...) + opts = append((*c.CallOptions).CreateIngressRule[0:len((*c.CallOptions).CreateIngressRule):len((*c.CallOptions).CreateIngressRule)], opts...) var resp *appenginepb.FirewallRule err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -233,11 +319,10 @@ func (c *FirewallClient) CreateIngressRule(ctx context.Context, req *appenginepb return resp, nil } -// GetIngressRule gets the specified firewall rule. -func (c *FirewallClient) GetIngressRule(ctx context.Context, req *appenginepb.GetIngressRuleRequest, opts ...gax.CallOption) (*appenginepb.FirewallRule, error) { +func (c *firewallGRPCClient) GetIngressRule(ctx context.Context, req *appenginepb.GetIngressRuleRequest, opts ...gax.CallOption) (*appenginepb.FirewallRule, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIngressRule[0:len(c.CallOptions.GetIngressRule):len(c.CallOptions.GetIngressRule)], opts...) + opts = append((*c.CallOptions).GetIngressRule[0:len((*c.CallOptions).GetIngressRule):len((*c.CallOptions).GetIngressRule)], opts...) var resp *appenginepb.FirewallRule err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -250,11 +335,10 @@ func (c *FirewallClient) GetIngressRule(ctx context.Context, req *appenginepb.Ge return resp, nil } -// UpdateIngressRule updates the specified firewall rule. -func (c *FirewallClient) UpdateIngressRule(ctx context.Context, req *appenginepb.UpdateIngressRuleRequest, opts ...gax.CallOption) (*appenginepb.FirewallRule, error) { +func (c *firewallGRPCClient) UpdateIngressRule(ctx context.Context, req *appenginepb.UpdateIngressRuleRequest, opts ...gax.CallOption) (*appenginepb.FirewallRule, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateIngressRule[0:len(c.CallOptions.UpdateIngressRule):len(c.CallOptions.UpdateIngressRule)], opts...) + opts = append((*c.CallOptions).UpdateIngressRule[0:len((*c.CallOptions).UpdateIngressRule):len((*c.CallOptions).UpdateIngressRule)], opts...) var resp *appenginepb.FirewallRule err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -267,11 +351,10 @@ func (c *FirewallClient) UpdateIngressRule(ctx context.Context, req *appenginepb return resp, nil } -// DeleteIngressRule deletes the specified firewall rule. -func (c *FirewallClient) DeleteIngressRule(ctx context.Context, req *appenginepb.DeleteIngressRuleRequest, opts ...gax.CallOption) error { +func (c *firewallGRPCClient) DeleteIngressRule(ctx context.Context, req *appenginepb.DeleteIngressRuleRequest, opts ...gax.CallOption) error { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteIngressRule[0:len(c.CallOptions.DeleteIngressRule):len(c.CallOptions.DeleteIngressRule)], opts...) + opts = append((*c.CallOptions).DeleteIngressRule[0:len((*c.CallOptions).DeleteIngressRule):len((*c.CallOptions).DeleteIngressRule)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.firewallClient.DeleteIngressRule(ctx, req, settings.GRPC...) diff --git a/appengine/apiv1/firewall_client_example_test.go b/appengine/apiv1/firewall_client_example_test.go index 1076b407e20c..23b69b69ba7e 100644 --- a/appengine/apiv1/firewall_client_example_test.go +++ b/appengine/apiv1/firewall_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewFirewallClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleFirewallClient_ListIngressRules() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := appengine.NewFirewallClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.ListIngressRulesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleFirewallClient_ListIngressRules() { } func ExampleFirewallClient_BatchUpdateIngressRules() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewFirewallClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.BatchUpdateIngressRulesRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleFirewallClient_BatchUpdateIngressRules() { } func ExampleFirewallClient_CreateIngressRule() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewFirewallClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.CreateIngressRuleRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleFirewallClient_CreateIngressRule() { } func ExampleFirewallClient_GetIngressRule() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewFirewallClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.GetIngressRuleRequest{ // TODO: Fill request struct fields. @@ -122,13 +119,12 @@ func ExampleFirewallClient_GetIngressRule() { } func ExampleFirewallClient_UpdateIngressRule() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewFirewallClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.UpdateIngressRuleRequest{ // TODO: Fill request struct fields. @@ -147,6 +143,7 @@ func ExampleFirewallClient_DeleteIngressRule() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.DeleteIngressRuleRequest{ // TODO: Fill request struct fields. diff --git a/appengine/apiv1/instances_client.go b/appengine/apiv1/instances_client.go index 09c2956d2f9e..4fa8651d0b06 100644 --- a/appengine/apiv1/instances_client.go +++ b/appengine/apiv1/instances_client.go @@ -47,7 +47,7 @@ type InstancesCallOptions struct { DebugInstance []gax.CallOption } -func defaultInstancesClientOptions() []option.ClientOption { +func defaultInstancesGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("appengine.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("appengine.mtls.googleapis.com:443"), @@ -68,37 +68,142 @@ func defaultInstancesCallOptions() *InstancesCallOptions { } } +// internalInstancesClient is an interface that defines the methods availaible from App Engine Admin API. +type internalInstancesClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListInstances(context.Context, *appenginepb.ListInstancesRequest, ...gax.CallOption) *InstanceIterator + GetInstance(context.Context, *appenginepb.GetInstanceRequest, ...gax.CallOption) (*appenginepb.Instance, error) + DeleteInstance(context.Context, *appenginepb.DeleteInstanceRequest, ...gax.CallOption) (*DeleteInstanceOperation, error) + DeleteInstanceOperation(name string) *DeleteInstanceOperation + DebugInstance(context.Context, *appenginepb.DebugInstanceRequest, ...gax.CallOption) (*DebugInstanceOperation, error) + DebugInstanceOperation(name string) *DebugInstanceOperation +} + // InstancesClient is a client for interacting with App Engine Admin API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Manages instances of a version. type InstancesClient struct { + // The internal transport-dependent client. + internalClient internalInstancesClient + + // The call options for this service. + CallOptions *InstancesCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *InstancesClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *InstancesClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *InstancesClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListInstances lists the instances of a version. +// +// Tip: To aggregate details about instances over time, see the +// Stackdriver Monitoring API (at https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list). +func (c *InstancesClient) ListInstances(ctx context.Context, req *appenginepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { + return c.internalClient.ListInstances(ctx, req, opts...) +} + +// GetInstance gets instance information. +func (c *InstancesClient) GetInstance(ctx context.Context, req *appenginepb.GetInstanceRequest, opts ...gax.CallOption) (*appenginepb.Instance, error) { + return c.internalClient.GetInstance(ctx, req, opts...) +} + +// DeleteInstance stops a running instance. +// +// The instance might be automatically recreated based on the scaling settings +// of the version. For more information, see “How Instances are Managed” +// (standard environment (at https://cloud.google.com/appengine/docs/standard/python/how-instances-are-managed) | +// flexible environment (at https://cloud.google.com/appengine/docs/flexible/python/how-instances-are-managed)). +// +// To ensure that instances are not re-created and avoid getting billed, you +// can stop all instances within the target version by changing the serving +// status of the version to STOPPED with the +// apps.services.versions.patch (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions/patch) +// method. +func (c *InstancesClient) DeleteInstance(ctx context.Context, req *appenginepb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { + return c.internalClient.DeleteInstance(ctx, req, opts...) +} + +// DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. +// The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. +func (c *InstancesClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { + return c.internalClient.DeleteInstanceOperation(name) +} + +// DebugInstance enables debugging on a VM instance. This allows you to use the SSH +// command to connect to the virtual machine where the instance lives. +// While in “debug mode”, the instance continues to serve live traffic. +// You should delete the instance when you are done debugging and then +// allow the system to take over and determine if another instance +// should be started. +// +// Only applicable for instances in App Engine flexible environment. +func (c *InstancesClient) DebugInstance(ctx context.Context, req *appenginepb.DebugInstanceRequest, opts ...gax.CallOption) (*DebugInstanceOperation, error) { + return c.internalClient.DebugInstance(ctx, req, opts...) +} + +// DebugInstanceOperation returns a new DebugInstanceOperation from a given name. +// The name must be that of a previously created DebugInstanceOperation, possibly from a different process. +func (c *InstancesClient) DebugInstanceOperation(name string) *DebugInstanceOperation { + return c.internalClient.DebugInstanceOperation(name) +} + +// instancesGRPCClient is a client for interacting with App Engine Admin API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type instancesGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing InstancesClient + CallOptions **InstancesCallOptions + // The gRPC API client. instancesClient appenginepb.InstancesClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *InstancesCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewInstancesClient creates a new instances client. +// NewInstancesClient creates a new instances client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Manages instances of a version. func NewInstancesClient(ctx context.Context, opts ...option.ClientOption) (*InstancesClient, error) { - clientOpts := defaultInstancesClientOptions() - + clientOpts := defaultInstancesGRPCClientOptions() if newInstancesClientHook != nil { hookOpts, err := newInstancesClientHook(ctx, clientHookParams{}) if err != nil { @@ -116,16 +221,19 @@ func NewInstancesClient(ctx context.Context, opts ...option.ClientOption) (*Inst if err != nil { return nil, err } - c := &InstancesClient{ + client := InstancesClient{CallOptions: defaultInstancesCallOptions()} + + c := &instancesGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultInstancesCallOptions(), - - instancesClient: appenginepb.NewInstancesClient(connPool), + instancesClient: appenginepb.NewInstancesClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -135,39 +243,36 @@ func NewInstancesClient(ctx context.Context, opts ...option.ClientOption) (*Inst // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *InstancesClient) Connection() *grpc.ClientConn { +func (c *instancesGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *InstancesClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *InstancesClient) setGoogleClientInfo(keyval ...string) { +func (c *instancesGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListInstances lists the instances of a version. -// -// Tip: To aggregate details about instances over time, see the -// Stackdriver Monitoring API (at https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list). -func (c *InstancesClient) ListInstances(ctx context.Context, req *appenginepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *instancesGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *instancesGRPCClient) ListInstances(ctx context.Context, req *appenginepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListInstances[0:len(c.CallOptions.ListInstances):len(c.CallOptions.ListInstances)], opts...) + opts = append((*c.CallOptions).ListInstances[0:len((*c.CallOptions).ListInstances):len((*c.CallOptions).ListInstances)], opts...) it := &InstanceIterator{} req = proto.Clone(req).(*appenginepb.ListInstancesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*appenginepb.Instance, string, error) { @@ -204,11 +309,10 @@ func (c *InstancesClient) ListInstances(ctx context.Context, req *appenginepb.Li return it } -// GetInstance gets instance information. -func (c *InstancesClient) GetInstance(ctx context.Context, req *appenginepb.GetInstanceRequest, opts ...gax.CallOption) (*appenginepb.Instance, error) { +func (c *instancesGRPCClient) GetInstance(ctx context.Context, req *appenginepb.GetInstanceRequest, opts ...gax.CallOption) (*appenginepb.Instance, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetInstance[0:len(c.CallOptions.GetInstance):len(c.CallOptions.GetInstance)], opts...) + opts = append((*c.CallOptions).GetInstance[0:len((*c.CallOptions).GetInstance):len((*c.CallOptions).GetInstance)], opts...) var resp *appenginepb.Instance err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -221,22 +325,10 @@ func (c *InstancesClient) GetInstance(ctx context.Context, req *appenginepb.GetI return resp, nil } -// DeleteInstance stops a running instance. -// -// The instance might be automatically recreated based on the scaling settings -// of the version. For more information, see “How Instances are Managed” -// (standard environment (at https://cloud.google.com/appengine/docs/standard/python/how-instances-are-managed) | -// flexible environment (at https://cloud.google.com/appengine/docs/flexible/python/how-instances-are-managed)). -// -// To ensure that instances are not re-created and avoid getting billed, you -// can stop all instances within the target version by changing the serving -// status of the version to STOPPED with the -// apps.services.versions.patch (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions/patch) -// method. -func (c *InstancesClient) DeleteInstance(ctx context.Context, req *appenginepb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { +func (c *instancesGRPCClient) DeleteInstance(ctx context.Context, req *appenginepb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteInstance[0:len(c.CallOptions.DeleteInstance):len(c.CallOptions.DeleteInstance)], opts...) + opts = append((*c.CallOptions).DeleteInstance[0:len((*c.CallOptions).DeleteInstance):len((*c.CallOptions).DeleteInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -247,22 +339,14 @@ func (c *InstancesClient) DeleteInstance(ctx context.Context, req *appenginepb.D return nil, err } return &DeleteInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DebugInstance enables debugging on a VM instance. This allows you to use the SSH -// command to connect to the virtual machine where the instance lives. -// While in “debug mode”, the instance continues to serve live traffic. -// You should delete the instance when you are done debugging and then -// allow the system to take over and determine if another instance -// should be started. -// -// Only applicable for instances in App Engine flexible environment. -func (c *InstancesClient) DebugInstance(ctx context.Context, req *appenginepb.DebugInstanceRequest, opts ...gax.CallOption) (*DebugInstanceOperation, error) { +func (c *instancesGRPCClient) DebugInstance(ctx context.Context, req *appenginepb.DebugInstanceRequest, opts ...gax.CallOption) (*DebugInstanceOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DebugInstance[0:len(c.CallOptions.DebugInstance):len(c.CallOptions.DebugInstance)], opts...) + opts = append((*c.CallOptions).DebugInstance[0:len((*c.CallOptions).DebugInstance):len((*c.CallOptions).DebugInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -273,7 +357,7 @@ func (c *InstancesClient) DebugInstance(ctx context.Context, req *appenginepb.De return nil, err } return &DebugInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -284,9 +368,9 @@ type DebugInstanceOperation struct { // DebugInstanceOperation returns a new DebugInstanceOperation from a given name. // The name must be that of a previously created DebugInstanceOperation, possibly from a different process. -func (c *InstancesClient) DebugInstanceOperation(name string) *DebugInstanceOperation { +func (c *instancesGRPCClient) DebugInstanceOperation(name string) *DebugInstanceOperation { return &DebugInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -353,9 +437,9 @@ type DeleteInstanceOperation struct { // DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. // The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. -func (c *InstancesClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { +func (c *instancesGRPCClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { return &DeleteInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/appengine/apiv1/instances_client_example_test.go b/appengine/apiv1/instances_client_example_test.go index 39f6279fbd96..593d41aeed18 100644 --- a/appengine/apiv1/instances_client_example_test.go +++ b/appengine/apiv1/instances_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewInstancesClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleInstancesClient_ListInstances() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := appengine.NewInstancesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.ListInstancesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleInstancesClient_ListInstances() { } func ExampleInstancesClient_GetInstance() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewInstancesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.GetInstanceRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleInstancesClient_GetInstance() { } func ExampleInstancesClient_DeleteInstance() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewInstancesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.DeleteInstanceRequest{ // TODO: Fill request struct fields. @@ -105,13 +103,12 @@ func ExampleInstancesClient_DeleteInstance() { } func ExampleInstancesClient_DebugInstance() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewInstancesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.DebugInstanceRequest{ // TODO: Fill request struct fields. diff --git a/appengine/apiv1/services_client.go b/appengine/apiv1/services_client.go index d37751814c48..41e88a848d1b 100644 --- a/appengine/apiv1/services_client.go +++ b/appengine/apiv1/services_client.go @@ -47,7 +47,7 @@ type ServicesCallOptions struct { DeleteService []gax.CallOption } -func defaultServicesClientOptions() []option.ClientOption { +func defaultServicesGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("appengine.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("appengine.mtls.googleapis.com:443"), @@ -68,37 +68,121 @@ func defaultServicesCallOptions() *ServicesCallOptions { } } +// internalServicesClient is an interface that defines the methods availaible from App Engine Admin API. +type internalServicesClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListServices(context.Context, *appenginepb.ListServicesRequest, ...gax.CallOption) *ServiceIterator + GetService(context.Context, *appenginepb.GetServiceRequest, ...gax.CallOption) (*appenginepb.Service, error) + UpdateService(context.Context, *appenginepb.UpdateServiceRequest, ...gax.CallOption) (*UpdateServiceOperation, error) + UpdateServiceOperation(name string) *UpdateServiceOperation + DeleteService(context.Context, *appenginepb.DeleteServiceRequest, ...gax.CallOption) (*DeleteServiceOperation, error) + DeleteServiceOperation(name string) *DeleteServiceOperation +} + // ServicesClient is a client for interacting with App Engine Admin API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Manages services of an application. type ServicesClient struct { + // The internal transport-dependent client. + internalClient internalServicesClient + + // The call options for this service. + CallOptions *ServicesCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ServicesClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ServicesClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ServicesClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListServices lists all the services in the application. +func (c *ServicesClient) ListServices(ctx context.Context, req *appenginepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { + return c.internalClient.ListServices(ctx, req, opts...) +} + +// GetService gets the current configuration of the specified service. +func (c *ServicesClient) GetService(ctx context.Context, req *appenginepb.GetServiceRequest, opts ...gax.CallOption) (*appenginepb.Service, error) { + return c.internalClient.GetService(ctx, req, opts...) +} + +// UpdateService updates the configuration of the specified service. +func (c *ServicesClient) UpdateService(ctx context.Context, req *appenginepb.UpdateServiceRequest, opts ...gax.CallOption) (*UpdateServiceOperation, error) { + return c.internalClient.UpdateService(ctx, req, opts...) +} + +// UpdateServiceOperation returns a new UpdateServiceOperation from a given name. +// The name must be that of a previously created UpdateServiceOperation, possibly from a different process. +func (c *ServicesClient) UpdateServiceOperation(name string) *UpdateServiceOperation { + return c.internalClient.UpdateServiceOperation(name) +} + +// DeleteService deletes the specified service and all enclosed versions. +func (c *ServicesClient) DeleteService(ctx context.Context, req *appenginepb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { + return c.internalClient.DeleteService(ctx, req, opts...) +} + +// DeleteServiceOperation returns a new DeleteServiceOperation from a given name. +// The name must be that of a previously created DeleteServiceOperation, possibly from a different process. +func (c *ServicesClient) DeleteServiceOperation(name string) *DeleteServiceOperation { + return c.internalClient.DeleteServiceOperation(name) +} + +// servicesGRPCClient is a client for interacting with App Engine Admin API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type servicesGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ServicesClient + CallOptions **ServicesCallOptions + // The gRPC API client. servicesClient appenginepb.ServicesClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *ServicesCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewServicesClient creates a new services client. +// NewServicesClient creates a new services client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Manages services of an application. func NewServicesClient(ctx context.Context, opts ...option.ClientOption) (*ServicesClient, error) { - clientOpts := defaultServicesClientOptions() - + clientOpts := defaultServicesGRPCClientOptions() if newServicesClientHook != nil { hookOpts, err := newServicesClientHook(ctx, clientHookParams{}) if err != nil { @@ -116,16 +200,19 @@ func NewServicesClient(ctx context.Context, opts ...option.ClientOption) (*Servi if err != nil { return nil, err } - c := &ServicesClient{ + client := ServicesClient{CallOptions: defaultServicesCallOptions()} + + c := &servicesGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultServicesCallOptions(), - - servicesClient: appenginepb.NewServicesClient(connPool), + servicesClient: appenginepb.NewServicesClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -135,36 +222,36 @@ func NewServicesClient(ctx context.Context, opts ...option.ClientOption) (*Servi // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ServicesClient) Connection() *grpc.ClientConn { +func (c *servicesGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ServicesClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ServicesClient) setGoogleClientInfo(keyval ...string) { +func (c *servicesGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListServices lists all the services in the application. -func (c *ServicesClient) ListServices(ctx context.Context, req *appenginepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *servicesGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *servicesGRPCClient) ListServices(ctx context.Context, req *appenginepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListServices[0:len(c.CallOptions.ListServices):len(c.CallOptions.ListServices)], opts...) + opts = append((*c.CallOptions).ListServices[0:len((*c.CallOptions).ListServices):len((*c.CallOptions).ListServices)], opts...) it := &ServiceIterator{} req = proto.Clone(req).(*appenginepb.ListServicesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*appenginepb.Service, string, error) { @@ -201,11 +288,10 @@ func (c *ServicesClient) ListServices(ctx context.Context, req *appenginepb.List return it } -// GetService gets the current configuration of the specified service. -func (c *ServicesClient) GetService(ctx context.Context, req *appenginepb.GetServiceRequest, opts ...gax.CallOption) (*appenginepb.Service, error) { +func (c *servicesGRPCClient) GetService(ctx context.Context, req *appenginepb.GetServiceRequest, opts ...gax.CallOption) (*appenginepb.Service, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetService[0:len(c.CallOptions.GetService):len(c.CallOptions.GetService)], opts...) + opts = append((*c.CallOptions).GetService[0:len((*c.CallOptions).GetService):len((*c.CallOptions).GetService)], opts...) var resp *appenginepb.Service err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -218,11 +304,10 @@ func (c *ServicesClient) GetService(ctx context.Context, req *appenginepb.GetSer return resp, nil } -// UpdateService updates the configuration of the specified service. -func (c *ServicesClient) UpdateService(ctx context.Context, req *appenginepb.UpdateServiceRequest, opts ...gax.CallOption) (*UpdateServiceOperation, error) { +func (c *servicesGRPCClient) UpdateService(ctx context.Context, req *appenginepb.UpdateServiceRequest, opts ...gax.CallOption) (*UpdateServiceOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateService[0:len(c.CallOptions.UpdateService):len(c.CallOptions.UpdateService)], opts...) + opts = append((*c.CallOptions).UpdateService[0:len((*c.CallOptions).UpdateService):len((*c.CallOptions).UpdateService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -233,15 +318,14 @@ func (c *ServicesClient) UpdateService(ctx context.Context, req *appenginepb.Upd return nil, err } return &UpdateServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteService deletes the specified service and all enclosed versions. -func (c *ServicesClient) DeleteService(ctx context.Context, req *appenginepb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { +func (c *servicesGRPCClient) DeleteService(ctx context.Context, req *appenginepb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteService[0:len(c.CallOptions.DeleteService):len(c.CallOptions.DeleteService)], opts...) + opts = append((*c.CallOptions).DeleteService[0:len((*c.CallOptions).DeleteService):len((*c.CallOptions).DeleteService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -252,7 +336,7 @@ func (c *ServicesClient) DeleteService(ctx context.Context, req *appenginepb.Del return nil, err } return &DeleteServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -263,9 +347,9 @@ type DeleteServiceOperation struct { // DeleteServiceOperation returns a new DeleteServiceOperation from a given name. // The name must be that of a previously created DeleteServiceOperation, possibly from a different process. -func (c *ServicesClient) DeleteServiceOperation(name string) *DeleteServiceOperation { +func (c *servicesGRPCClient) DeleteServiceOperation(name string) *DeleteServiceOperation { return &DeleteServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -321,9 +405,9 @@ type UpdateServiceOperation struct { // UpdateServiceOperation returns a new UpdateServiceOperation from a given name. // The name must be that of a previously created UpdateServiceOperation, possibly from a different process. -func (c *ServicesClient) UpdateServiceOperation(name string) *UpdateServiceOperation { +func (c *servicesGRPCClient) UpdateServiceOperation(name string) *UpdateServiceOperation { return &UpdateServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/appengine/apiv1/services_client_example_test.go b/appengine/apiv1/services_client_example_test.go index 0b8019b35fce..c4205944d533 100644 --- a/appengine/apiv1/services_client_example_test.go +++ b/appengine/apiv1/services_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewServicesClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleServicesClient_ListServices() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := appengine.NewServicesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.ListServicesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleServicesClient_ListServices() { } func ExampleServicesClient_GetService() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewServicesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.GetServiceRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleServicesClient_GetService() { } func ExampleServicesClient_UpdateService() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewServicesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.UpdateServiceRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleServicesClient_UpdateService() { } func ExampleServicesClient_DeleteService() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewServicesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.DeleteServiceRequest{ // TODO: Fill request struct fields. diff --git a/appengine/apiv1/versions_client.go b/appengine/apiv1/versions_client.go index f9052f4c5a59..8ac09dda7d4b 100644 --- a/appengine/apiv1/versions_client.go +++ b/appengine/apiv1/versions_client.go @@ -48,7 +48,7 @@ type VersionsCallOptions struct { DeleteVersion []gax.CallOption } -func defaultVersionsClientOptions() []option.ClientOption { +func defaultVersionsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("appengine.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("appengine.mtls.googleapis.com:443"), @@ -70,37 +70,180 @@ func defaultVersionsCallOptions() *VersionsCallOptions { } } +// internalVersionsClient is an interface that defines the methods availaible from App Engine Admin API. +type internalVersionsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListVersions(context.Context, *appenginepb.ListVersionsRequest, ...gax.CallOption) *VersionIterator + GetVersion(context.Context, *appenginepb.GetVersionRequest, ...gax.CallOption) (*appenginepb.Version, error) + CreateVersion(context.Context, *appenginepb.CreateVersionRequest, ...gax.CallOption) (*CreateVersionOperation, error) + CreateVersionOperation(name string) *CreateVersionOperation + UpdateVersion(context.Context, *appenginepb.UpdateVersionRequest, ...gax.CallOption) (*UpdateVersionOperation, error) + UpdateVersionOperation(name string) *UpdateVersionOperation + DeleteVersion(context.Context, *appenginepb.DeleteVersionRequest, ...gax.CallOption) (*DeleteVersionOperation, error) + DeleteVersionOperation(name string) *DeleteVersionOperation +} + // VersionsClient is a client for interacting with App Engine Admin API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Manages versions of a service. type VersionsClient struct { + // The internal transport-dependent client. + internalClient internalVersionsClient + + // The call options for this service. + CallOptions *VersionsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *VersionsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *VersionsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *VersionsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListVersions lists the versions of a service. +func (c *VersionsClient) ListVersions(ctx context.Context, req *appenginepb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { + return c.internalClient.ListVersions(ctx, req, opts...) +} + +// GetVersion gets the specified Version resource. +// By default, only a BASIC_VIEW will be returned. +// Specify the FULL_VIEW parameter to get the full resource. +func (c *VersionsClient) GetVersion(ctx context.Context, req *appenginepb.GetVersionRequest, opts ...gax.CallOption) (*appenginepb.Version, error) { + return c.internalClient.GetVersion(ctx, req, opts...) +} + +// CreateVersion deploys code and resource files to a new version. +func (c *VersionsClient) CreateVersion(ctx context.Context, req *appenginepb.CreateVersionRequest, opts ...gax.CallOption) (*CreateVersionOperation, error) { + return c.internalClient.CreateVersion(ctx, req, opts...) +} + +// CreateVersionOperation returns a new CreateVersionOperation from a given name. +// The name must be that of a previously created CreateVersionOperation, possibly from a different process. +func (c *VersionsClient) CreateVersionOperation(name string) *CreateVersionOperation { + return c.internalClient.CreateVersionOperation(name) +} + +// UpdateVersion updates the specified Version resource. +// You can specify the following fields depending on the App Engine +// environment and type of scaling that the version resource uses: +// +// Standard environment +// +// instance_class (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.instance_class) +// +// automatic scaling in the standard environment: +// +// automatic_scaling.min_idle_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) +// +// automatic_scaling.max_idle_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) +// +// automaticScaling.standard_scheduler_settings.max_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#StandardSchedulerSettings) +// +// automaticScaling.standard_scheduler_settings.min_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#StandardSchedulerSettings) +// +// automaticScaling.standard_scheduler_settings.target_cpu_utilization (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#StandardSchedulerSettings) +// +// automaticScaling.standard_scheduler_settings.target_throughput_utilization (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#StandardSchedulerSettings) +// +// basic scaling or manual scaling in the standard environment: +// +// serving_status (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.serving_status) +// +// manual_scaling.instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#manualscaling) +// +// Flexible environment +// +// serving_status (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.serving_status) +// +// automatic scaling in the flexible environment: +// +// automatic_scaling.min_total_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) +// +// automatic_scaling.max_total_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) +// +// automatic_scaling.cool_down_period_sec (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) +// +// automatic_scaling.cpu_utilization.target_utilization (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) +// +// manual scaling in the flexible environment: +// +// manual_scaling.instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#manualscaling) +func (c *VersionsClient) UpdateVersion(ctx context.Context, req *appenginepb.UpdateVersionRequest, opts ...gax.CallOption) (*UpdateVersionOperation, error) { + return c.internalClient.UpdateVersion(ctx, req, opts...) +} + +// UpdateVersionOperation returns a new UpdateVersionOperation from a given name. +// The name must be that of a previously created UpdateVersionOperation, possibly from a different process. +func (c *VersionsClient) UpdateVersionOperation(name string) *UpdateVersionOperation { + return c.internalClient.UpdateVersionOperation(name) +} + +// DeleteVersion deletes an existing Version resource. +func (c *VersionsClient) DeleteVersion(ctx context.Context, req *appenginepb.DeleteVersionRequest, opts ...gax.CallOption) (*DeleteVersionOperation, error) { + return c.internalClient.DeleteVersion(ctx, req, opts...) +} + +// DeleteVersionOperation returns a new DeleteVersionOperation from a given name. +// The name must be that of a previously created DeleteVersionOperation, possibly from a different process. +func (c *VersionsClient) DeleteVersionOperation(name string) *DeleteVersionOperation { + return c.internalClient.DeleteVersionOperation(name) +} + +// versionsGRPCClient is a client for interacting with App Engine Admin API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type versionsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing VersionsClient + CallOptions **VersionsCallOptions + // The gRPC API client. versionsClient appenginepb.VersionsClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *VersionsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewVersionsClient creates a new versions client. +// NewVersionsClient creates a new versions client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Manages versions of a service. func NewVersionsClient(ctx context.Context, opts ...option.ClientOption) (*VersionsClient, error) { - clientOpts := defaultVersionsClientOptions() - + clientOpts := defaultVersionsGRPCClientOptions() if newVersionsClientHook != nil { hookOpts, err := newVersionsClientHook(ctx, clientHookParams{}) if err != nil { @@ -118,16 +261,19 @@ func NewVersionsClient(ctx context.Context, opts ...option.ClientOption) (*Versi if err != nil { return nil, err } - c := &VersionsClient{ + client := VersionsClient{CallOptions: defaultVersionsCallOptions()} + + c := &versionsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultVersionsCallOptions(), - - versionsClient: appenginepb.NewVersionsClient(connPool), + versionsClient: appenginepb.NewVersionsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -137,36 +283,36 @@ func NewVersionsClient(ctx context.Context, opts ...option.ClientOption) (*Versi // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *VersionsClient) Connection() *grpc.ClientConn { +func (c *versionsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *VersionsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *VersionsClient) setGoogleClientInfo(keyval ...string) { +func (c *versionsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListVersions lists the versions of a service. -func (c *VersionsClient) ListVersions(ctx context.Context, req *appenginepb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *versionsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *versionsGRPCClient) ListVersions(ctx context.Context, req *appenginepb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListVersions[0:len(c.CallOptions.ListVersions):len(c.CallOptions.ListVersions)], opts...) + opts = append((*c.CallOptions).ListVersions[0:len((*c.CallOptions).ListVersions):len((*c.CallOptions).ListVersions)], opts...) it := &VersionIterator{} req = proto.Clone(req).(*appenginepb.ListVersionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*appenginepb.Version, string, error) { @@ -203,13 +349,10 @@ func (c *VersionsClient) ListVersions(ctx context.Context, req *appenginepb.List return it } -// GetVersion gets the specified Version resource. -// By default, only a BASIC_VIEW will be returned. -// Specify the FULL_VIEW parameter to get the full resource. -func (c *VersionsClient) GetVersion(ctx context.Context, req *appenginepb.GetVersionRequest, opts ...gax.CallOption) (*appenginepb.Version, error) { +func (c *versionsGRPCClient) GetVersion(ctx context.Context, req *appenginepb.GetVersionRequest, opts ...gax.CallOption) (*appenginepb.Version, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetVersion[0:len(c.CallOptions.GetVersion):len(c.CallOptions.GetVersion)], opts...) + opts = append((*c.CallOptions).GetVersion[0:len((*c.CallOptions).GetVersion):len((*c.CallOptions).GetVersion)], opts...) var resp *appenginepb.Version err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -222,11 +365,10 @@ func (c *VersionsClient) GetVersion(ctx context.Context, req *appenginepb.GetVer return resp, nil } -// CreateVersion deploys code and resource files to a new version. -func (c *VersionsClient) CreateVersion(ctx context.Context, req *appenginepb.CreateVersionRequest, opts ...gax.CallOption) (*CreateVersionOperation, error) { +func (c *versionsGRPCClient) CreateVersion(ctx context.Context, req *appenginepb.CreateVersionRequest, opts ...gax.CallOption) (*CreateVersionOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateVersion[0:len(c.CallOptions.CreateVersion):len(c.CallOptions.CreateVersion)], opts...) + opts = append((*c.CallOptions).CreateVersion[0:len((*c.CallOptions).CreateVersion):len((*c.CallOptions).CreateVersion)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -237,59 +379,14 @@ func (c *VersionsClient) CreateVersion(ctx context.Context, req *appenginepb.Cre return nil, err } return &CreateVersionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateVersion updates the specified Version resource. -// You can specify the following fields depending on the App Engine -// environment and type of scaling that the version resource uses: -// -// Standard environment -// -// instance_class (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.instance_class) -// -// automatic scaling in the standard environment: -// -// automatic_scaling.min_idle_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) -// -// automatic_scaling.max_idle_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) -// -// automaticScaling.standard_scheduler_settings.max_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#StandardSchedulerSettings) -// -// automaticScaling.standard_scheduler_settings.min_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#StandardSchedulerSettings) -// -// automaticScaling.standard_scheduler_settings.target_cpu_utilization (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#StandardSchedulerSettings) -// -// automaticScaling.standard_scheduler_settings.target_throughput_utilization (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#StandardSchedulerSettings) -// -// basic scaling or manual scaling in the standard environment: -// -// serving_status (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.serving_status) -// -// manual_scaling.instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#manualscaling) -// -// Flexible environment -// -// serving_status (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.serving_status) -// -// automatic scaling in the flexible environment: -// -// automatic_scaling.min_total_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) -// -// automatic_scaling.max_total_instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) -// -// automatic_scaling.cool_down_period_sec (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) -// -// automatic_scaling.cpu_utilization.target_utilization (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#Version.FIELDS.automatic_scaling) -// -// manual scaling in the flexible environment: -// -// manual_scaling.instances (at https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions#manualscaling) -func (c *VersionsClient) UpdateVersion(ctx context.Context, req *appenginepb.UpdateVersionRequest, opts ...gax.CallOption) (*UpdateVersionOperation, error) { +func (c *versionsGRPCClient) UpdateVersion(ctx context.Context, req *appenginepb.UpdateVersionRequest, opts ...gax.CallOption) (*UpdateVersionOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateVersion[0:len(c.CallOptions.UpdateVersion):len(c.CallOptions.UpdateVersion)], opts...) + opts = append((*c.CallOptions).UpdateVersion[0:len((*c.CallOptions).UpdateVersion):len((*c.CallOptions).UpdateVersion)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -300,15 +397,14 @@ func (c *VersionsClient) UpdateVersion(ctx context.Context, req *appenginepb.Upd return nil, err } return &UpdateVersionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteVersion deletes an existing Version resource. -func (c *VersionsClient) DeleteVersion(ctx context.Context, req *appenginepb.DeleteVersionRequest, opts ...gax.CallOption) (*DeleteVersionOperation, error) { +func (c *versionsGRPCClient) DeleteVersion(ctx context.Context, req *appenginepb.DeleteVersionRequest, opts ...gax.CallOption) (*DeleteVersionOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteVersion[0:len(c.CallOptions.DeleteVersion):len(c.CallOptions.DeleteVersion)], opts...) + opts = append((*c.CallOptions).DeleteVersion[0:len((*c.CallOptions).DeleteVersion):len((*c.CallOptions).DeleteVersion)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -319,7 +415,7 @@ func (c *VersionsClient) DeleteVersion(ctx context.Context, req *appenginepb.Del return nil, err } return &DeleteVersionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -330,9 +426,9 @@ type CreateVersionOperation struct { // CreateVersionOperation returns a new CreateVersionOperation from a given name. // The name must be that of a previously created CreateVersionOperation, possibly from a different process. -func (c *VersionsClient) CreateVersionOperation(name string) *CreateVersionOperation { +func (c *versionsGRPCClient) CreateVersionOperation(name string) *CreateVersionOperation { return &CreateVersionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -399,9 +495,9 @@ type DeleteVersionOperation struct { // DeleteVersionOperation returns a new DeleteVersionOperation from a given name. // The name must be that of a previously created DeleteVersionOperation, possibly from a different process. -func (c *VersionsClient) DeleteVersionOperation(name string) *DeleteVersionOperation { +func (c *versionsGRPCClient) DeleteVersionOperation(name string) *DeleteVersionOperation { return &DeleteVersionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -457,9 +553,9 @@ type UpdateVersionOperation struct { // UpdateVersionOperation returns a new UpdateVersionOperation from a given name. // The name must be that of a previously created UpdateVersionOperation, possibly from a different process. -func (c *VersionsClient) UpdateVersionOperation(name string) *UpdateVersionOperation { +func (c *versionsGRPCClient) UpdateVersionOperation(name string) *UpdateVersionOperation { return &UpdateVersionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/appengine/apiv1/versions_client_example_test.go b/appengine/apiv1/versions_client_example_test.go index ede257f13818..5ad603907c1b 100644 --- a/appengine/apiv1/versions_client_example_test.go +++ b/appengine/apiv1/versions_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewVersionsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleVersionsClient_ListVersions() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := appengine.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.ListVersionsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleVersionsClient_ListVersions() { } func ExampleVersionsClient_GetVersion() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.GetVersionRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleVersionsClient_GetVersion() { } func ExampleVersionsClient_CreateVersion() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.CreateVersionRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleVersionsClient_CreateVersion() { } func ExampleVersionsClient_UpdateVersion() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.UpdateVersionRequest{ // TODO: Fill request struct fields. @@ -132,13 +129,12 @@ func ExampleVersionsClient_UpdateVersion() { } func ExampleVersionsClient_DeleteVersion() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.DeleteVersionRequest{ // TODO: Fill request struct fields. diff --git a/area120/tables/apiv1alpha1/doc.go b/area120/tables/apiv1alpha1/doc.go index 62657fa7d386..60fb61e8b2a5 100644 --- a/area120/tables/apiv1alpha1/doc.go +++ b/area120/tables/apiv1alpha1/doc.go @@ -17,6 +17,8 @@ // Package tables is an auto-generated package for the // Area120 Tables API. // +// NOTE: This package is in alpha. It is not stable, and is likely to change. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -26,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package tables // import "cloud.google.com/go/area120/tables/apiv1alpha1" import ( @@ -46,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/area120/tables/apiv1alpha1/tables_client.go b/area120/tables/apiv1alpha1/tables_client.go index 2523cd2821de..80bfea06fbe7 100644 --- a/area120/tables/apiv1alpha1/tables_client.go +++ b/area120/tables/apiv1alpha1/tables_client.go @@ -52,7 +52,7 @@ type CallOptions struct { BatchDeleteRows []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("area120tables.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("area120tables.mtls.googleapis.com:443"), @@ -81,27 +81,152 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Area120 Tables API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + GetTable(context.Context, *tablespb.GetTableRequest, ...gax.CallOption) (*tablespb.Table, error) + ListTables(context.Context, *tablespb.ListTablesRequest, ...gax.CallOption) *TableIterator + GetWorkspace(context.Context, *tablespb.GetWorkspaceRequest, ...gax.CallOption) (*tablespb.Workspace, error) + ListWorkspaces(context.Context, *tablespb.ListWorkspacesRequest, ...gax.CallOption) *WorkspaceIterator + GetRow(context.Context, *tablespb.GetRowRequest, ...gax.CallOption) (*tablespb.Row, error) + ListRows(context.Context, *tablespb.ListRowsRequest, ...gax.CallOption) *RowIterator + CreateRow(context.Context, *tablespb.CreateRowRequest, ...gax.CallOption) (*tablespb.Row, error) + BatchCreateRows(context.Context, *tablespb.BatchCreateRowsRequest, ...gax.CallOption) (*tablespb.BatchCreateRowsResponse, error) + UpdateRow(context.Context, *tablespb.UpdateRowRequest, ...gax.CallOption) (*tablespb.Row, error) + BatchUpdateRows(context.Context, *tablespb.BatchUpdateRowsRequest, ...gax.CallOption) (*tablespb.BatchUpdateRowsResponse, error) + DeleteRow(context.Context, *tablespb.DeleteRowRequest, ...gax.CallOption) error + BatchDeleteRows(context.Context, *tablespb.BatchDeleteRowsRequest, ...gax.CallOption) error +} + // Client is a client for interacting with Area120 Tables API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The Tables Service provides an API for reading and updating tables. +// It defines the following resource model: +// +// The API has a collection of [Table][google.area120.tables.v1alpha1.Table] +// resources, named tables/* +// +// Each Table has a collection of [Row][google.area120.tables.v1alpha1.Row] +// resources, named tables/*/rows/* +// +// The API has a collection of +// [Workspace][google.area120.tables.v1alpha1.Workspace] +// resources, named workspaces/*. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// GetTable gets a table. Returns NOT_FOUND if the table does not exist. +func (c *Client) GetTable(ctx context.Context, req *tablespb.GetTableRequest, opts ...gax.CallOption) (*tablespb.Table, error) { + return c.internalClient.GetTable(ctx, req, opts...) +} + +// ListTables lists tables for the user. +func (c *Client) ListTables(ctx context.Context, req *tablespb.ListTablesRequest, opts ...gax.CallOption) *TableIterator { + return c.internalClient.ListTables(ctx, req, opts...) +} + +// GetWorkspace gets a workspace. Returns NOT_FOUND if the workspace does not exist. +func (c *Client) GetWorkspace(ctx context.Context, req *tablespb.GetWorkspaceRequest, opts ...gax.CallOption) (*tablespb.Workspace, error) { + return c.internalClient.GetWorkspace(ctx, req, opts...) +} + +// ListWorkspaces lists workspaces for the user. +func (c *Client) ListWorkspaces(ctx context.Context, req *tablespb.ListWorkspacesRequest, opts ...gax.CallOption) *WorkspaceIterator { + return c.internalClient.ListWorkspaces(ctx, req, opts...) +} + +// GetRow gets a row. Returns NOT_FOUND if the row does not exist in the table. +func (c *Client) GetRow(ctx context.Context, req *tablespb.GetRowRequest, opts ...gax.CallOption) (*tablespb.Row, error) { + return c.internalClient.GetRow(ctx, req, opts...) +} + +// ListRows lists rows in a table. Returns NOT_FOUND if the table does not exist. +func (c *Client) ListRows(ctx context.Context, req *tablespb.ListRowsRequest, opts ...gax.CallOption) *RowIterator { + return c.internalClient.ListRows(ctx, req, opts...) +} + +// CreateRow creates a row. +func (c *Client) CreateRow(ctx context.Context, req *tablespb.CreateRowRequest, opts ...gax.CallOption) (*tablespb.Row, error) { + return c.internalClient.CreateRow(ctx, req, opts...) +} + +// BatchCreateRows creates multiple rows. +func (c *Client) BatchCreateRows(ctx context.Context, req *tablespb.BatchCreateRowsRequest, opts ...gax.CallOption) (*tablespb.BatchCreateRowsResponse, error) { + return c.internalClient.BatchCreateRows(ctx, req, opts...) +} + +// UpdateRow updates a row. +func (c *Client) UpdateRow(ctx context.Context, req *tablespb.UpdateRowRequest, opts ...gax.CallOption) (*tablespb.Row, error) { + return c.internalClient.UpdateRow(ctx, req, opts...) +} + +// BatchUpdateRows updates multiple rows. +func (c *Client) BatchUpdateRows(ctx context.Context, req *tablespb.BatchUpdateRowsRequest, opts ...gax.CallOption) (*tablespb.BatchUpdateRowsResponse, error) { + return c.internalClient.BatchUpdateRows(ctx, req, opts...) +} + +// DeleteRow deletes a row. +func (c *Client) DeleteRow(ctx context.Context, req *tablespb.DeleteRowRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteRow(ctx, req, opts...) +} + +// BatchDeleteRows deletes multiple rows. +func (c *Client) BatchDeleteRows(ctx context.Context, req *tablespb.BatchDeleteRowsRequest, opts ...gax.CallOption) error { + return c.internalClient.BatchDeleteRows(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Area120 Tables API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client tablespb.TablesServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new tables service client. +// NewClient creates a new tables service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The Tables Service provides an API for reading and updating tables. // It defines the following resource model: @@ -116,8 +241,7 @@ type Client struct { // [Workspace][google.area120.tables.v1alpha1.Workspace] // resources, named workspaces/*. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -135,42 +259,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: tablespb.NewTablesServiceClient(connPool), + client: tablespb.NewTablesServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// GetTable gets a table. Returns NOT_FOUND if the table does not exist. -func (c *Client) GetTable(ctx context.Context, req *tablespb.GetTableRequest, opts ...gax.CallOption) (*tablespb.Table, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) GetTable(ctx context.Context, req *tablespb.GetTableRequest, opts ...gax.CallOption) (*tablespb.Table, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -178,7 +304,7 @@ func (c *Client) GetTable(ctx context.Context, req *tablespb.GetTableRequest, op } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTable[0:len(c.CallOptions.GetTable):len(c.CallOptions.GetTable)], opts...) + opts = append((*c.CallOptions).GetTable[0:len((*c.CallOptions).GetTable):len((*c.CallOptions).GetTable)], opts...) var resp *tablespb.Table err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -191,10 +317,9 @@ func (c *Client) GetTable(ctx context.Context, req *tablespb.GetTableRequest, op return resp, nil } -// ListTables lists tables for the user. -func (c *Client) ListTables(ctx context.Context, req *tablespb.ListTablesRequest, opts ...gax.CallOption) *TableIterator { +func (c *gRPCClient) ListTables(ctx context.Context, req *tablespb.ListTablesRequest, opts ...gax.CallOption) *TableIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListTables[0:len(c.CallOptions.ListTables):len(c.CallOptions.ListTables)], opts...) + opts = append((*c.CallOptions).ListTables[0:len((*c.CallOptions).ListTables):len((*c.CallOptions).ListTables)], opts...) it := &TableIterator{} req = proto.Clone(req).(*tablespb.ListTablesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*tablespb.Table, string, error) { @@ -231,8 +356,7 @@ func (c *Client) ListTables(ctx context.Context, req *tablespb.ListTablesRequest return it } -// GetWorkspace gets a workspace. Returns NOT_FOUND if the workspace does not exist. -func (c *Client) GetWorkspace(ctx context.Context, req *tablespb.GetWorkspaceRequest, opts ...gax.CallOption) (*tablespb.Workspace, error) { +func (c *gRPCClient) GetWorkspace(ctx context.Context, req *tablespb.GetWorkspaceRequest, opts ...gax.CallOption) (*tablespb.Workspace, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -240,7 +364,7 @@ func (c *Client) GetWorkspace(ctx context.Context, req *tablespb.GetWorkspaceReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetWorkspace[0:len(c.CallOptions.GetWorkspace):len(c.CallOptions.GetWorkspace)], opts...) + opts = append((*c.CallOptions).GetWorkspace[0:len((*c.CallOptions).GetWorkspace):len((*c.CallOptions).GetWorkspace)], opts...) var resp *tablespb.Workspace err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -253,10 +377,9 @@ func (c *Client) GetWorkspace(ctx context.Context, req *tablespb.GetWorkspaceReq return resp, nil } -// ListWorkspaces lists workspaces for the user. -func (c *Client) ListWorkspaces(ctx context.Context, req *tablespb.ListWorkspacesRequest, opts ...gax.CallOption) *WorkspaceIterator { +func (c *gRPCClient) ListWorkspaces(ctx context.Context, req *tablespb.ListWorkspacesRequest, opts ...gax.CallOption) *WorkspaceIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListWorkspaces[0:len(c.CallOptions.ListWorkspaces):len(c.CallOptions.ListWorkspaces)], opts...) + opts = append((*c.CallOptions).ListWorkspaces[0:len((*c.CallOptions).ListWorkspaces):len((*c.CallOptions).ListWorkspaces)], opts...) it := &WorkspaceIterator{} req = proto.Clone(req).(*tablespb.ListWorkspacesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*tablespb.Workspace, string, error) { @@ -293,8 +416,7 @@ func (c *Client) ListWorkspaces(ctx context.Context, req *tablespb.ListWorkspace return it } -// GetRow gets a row. Returns NOT_FOUND if the row does not exist in the table. -func (c *Client) GetRow(ctx context.Context, req *tablespb.GetRowRequest, opts ...gax.CallOption) (*tablespb.Row, error) { +func (c *gRPCClient) GetRow(ctx context.Context, req *tablespb.GetRowRequest, opts ...gax.CallOption) (*tablespb.Row, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -302,7 +424,7 @@ func (c *Client) GetRow(ctx context.Context, req *tablespb.GetRowRequest, opts . } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetRow[0:len(c.CallOptions.GetRow):len(c.CallOptions.GetRow)], opts...) + opts = append((*c.CallOptions).GetRow[0:len((*c.CallOptions).GetRow):len((*c.CallOptions).GetRow)], opts...) var resp *tablespb.Row err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -315,11 +437,10 @@ func (c *Client) GetRow(ctx context.Context, req *tablespb.GetRowRequest, opts . return resp, nil } -// ListRows lists rows in a table. Returns NOT_FOUND if the table does not exist. -func (c *Client) ListRows(ctx context.Context, req *tablespb.ListRowsRequest, opts ...gax.CallOption) *RowIterator { +func (c *gRPCClient) ListRows(ctx context.Context, req *tablespb.ListRowsRequest, opts ...gax.CallOption) *RowIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListRows[0:len(c.CallOptions.ListRows):len(c.CallOptions.ListRows)], opts...) + opts = append((*c.CallOptions).ListRows[0:len((*c.CallOptions).ListRows):len((*c.CallOptions).ListRows)], opts...) it := &RowIterator{} req = proto.Clone(req).(*tablespb.ListRowsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*tablespb.Row, string, error) { @@ -356,8 +477,7 @@ func (c *Client) ListRows(ctx context.Context, req *tablespb.ListRowsRequest, op return it } -// CreateRow creates a row. -func (c *Client) CreateRow(ctx context.Context, req *tablespb.CreateRowRequest, opts ...gax.CallOption) (*tablespb.Row, error) { +func (c *gRPCClient) CreateRow(ctx context.Context, req *tablespb.CreateRowRequest, opts ...gax.CallOption) (*tablespb.Row, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -365,7 +485,7 @@ func (c *Client) CreateRow(ctx context.Context, req *tablespb.CreateRowRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateRow[0:len(c.CallOptions.CreateRow):len(c.CallOptions.CreateRow)], opts...) + opts = append((*c.CallOptions).CreateRow[0:len((*c.CallOptions).CreateRow):len((*c.CallOptions).CreateRow)], opts...) var resp *tablespb.Row err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -378,8 +498,7 @@ func (c *Client) CreateRow(ctx context.Context, req *tablespb.CreateRowRequest, return resp, nil } -// BatchCreateRows creates multiple rows. -func (c *Client) BatchCreateRows(ctx context.Context, req *tablespb.BatchCreateRowsRequest, opts ...gax.CallOption) (*tablespb.BatchCreateRowsResponse, error) { +func (c *gRPCClient) BatchCreateRows(ctx context.Context, req *tablespb.BatchCreateRowsRequest, opts ...gax.CallOption) (*tablespb.BatchCreateRowsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -387,7 +506,7 @@ func (c *Client) BatchCreateRows(ctx context.Context, req *tablespb.BatchCreateR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchCreateRows[0:len(c.CallOptions.BatchCreateRows):len(c.CallOptions.BatchCreateRows)], opts...) + opts = append((*c.CallOptions).BatchCreateRows[0:len((*c.CallOptions).BatchCreateRows):len((*c.CallOptions).BatchCreateRows)], opts...) var resp *tablespb.BatchCreateRowsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -400,8 +519,7 @@ func (c *Client) BatchCreateRows(ctx context.Context, req *tablespb.BatchCreateR return resp, nil } -// UpdateRow updates a row. -func (c *Client) UpdateRow(ctx context.Context, req *tablespb.UpdateRowRequest, opts ...gax.CallOption) (*tablespb.Row, error) { +func (c *gRPCClient) UpdateRow(ctx context.Context, req *tablespb.UpdateRowRequest, opts ...gax.CallOption) (*tablespb.Row, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -409,7 +527,7 @@ func (c *Client) UpdateRow(ctx context.Context, req *tablespb.UpdateRowRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "row.name", url.QueryEscape(req.GetRow().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateRow[0:len(c.CallOptions.UpdateRow):len(c.CallOptions.UpdateRow)], opts...) + opts = append((*c.CallOptions).UpdateRow[0:len((*c.CallOptions).UpdateRow):len((*c.CallOptions).UpdateRow)], opts...) var resp *tablespb.Row err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -422,8 +540,7 @@ func (c *Client) UpdateRow(ctx context.Context, req *tablespb.UpdateRowRequest, return resp, nil } -// BatchUpdateRows updates multiple rows. -func (c *Client) BatchUpdateRows(ctx context.Context, req *tablespb.BatchUpdateRowsRequest, opts ...gax.CallOption) (*tablespb.BatchUpdateRowsResponse, error) { +func (c *gRPCClient) BatchUpdateRows(ctx context.Context, req *tablespb.BatchUpdateRowsRequest, opts ...gax.CallOption) (*tablespb.BatchUpdateRowsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -431,7 +548,7 @@ func (c *Client) BatchUpdateRows(ctx context.Context, req *tablespb.BatchUpdateR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchUpdateRows[0:len(c.CallOptions.BatchUpdateRows):len(c.CallOptions.BatchUpdateRows)], opts...) + opts = append((*c.CallOptions).BatchUpdateRows[0:len((*c.CallOptions).BatchUpdateRows):len((*c.CallOptions).BatchUpdateRows)], opts...) var resp *tablespb.BatchUpdateRowsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -444,8 +561,7 @@ func (c *Client) BatchUpdateRows(ctx context.Context, req *tablespb.BatchUpdateR return resp, nil } -// DeleteRow deletes a row. -func (c *Client) DeleteRow(ctx context.Context, req *tablespb.DeleteRowRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteRow(ctx context.Context, req *tablespb.DeleteRowRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -453,7 +569,7 @@ func (c *Client) DeleteRow(ctx context.Context, req *tablespb.DeleteRowRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteRow[0:len(c.CallOptions.DeleteRow):len(c.CallOptions.DeleteRow)], opts...) + opts = append((*c.CallOptions).DeleteRow[0:len((*c.CallOptions).DeleteRow):len((*c.CallOptions).DeleteRow)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteRow(ctx, req, settings.GRPC...) @@ -462,8 +578,7 @@ func (c *Client) DeleteRow(ctx context.Context, req *tablespb.DeleteRowRequest, return err } -// BatchDeleteRows deletes multiple rows. -func (c *Client) BatchDeleteRows(ctx context.Context, req *tablespb.BatchDeleteRowsRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) BatchDeleteRows(ctx context.Context, req *tablespb.BatchDeleteRowsRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -471,7 +586,7 @@ func (c *Client) BatchDeleteRows(ctx context.Context, req *tablespb.BatchDeleteR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchDeleteRows[0:len(c.CallOptions.BatchDeleteRows):len(c.CallOptions.BatchDeleteRows)], opts...) + opts = append((*c.CallOptions).BatchDeleteRows[0:len((*c.CallOptions).BatchDeleteRows):len((*c.CallOptions).BatchDeleteRows)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.BatchDeleteRows(ctx, req, settings.GRPC...) diff --git a/area120/tables/apiv1alpha1/tables_client_example_test.go b/area120/tables/apiv1alpha1/tables_client_example_test.go index 3f6762c85819..c424eb612bb6 100644 --- a/area120/tables/apiv1alpha1/tables_client_example_test.go +++ b/area120/tables/apiv1alpha1/tables_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_GetTable() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.GetTableRequest{ // TODO: Fill request struct fields. @@ -55,14 +56,12 @@ func ExampleClient_GetTable() { } func ExampleClient_ListTables() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.ListTablesRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleClient_ListTables() { } func ExampleClient_GetWorkspace() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.GetWorkspaceRequest{ // TODO: Fill request struct fields. @@ -102,14 +100,12 @@ func ExampleClient_GetWorkspace() { } func ExampleClient_ListWorkspaces() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.ListWorkspacesRequest{ // TODO: Fill request struct fields. @@ -129,13 +125,12 @@ func ExampleClient_ListWorkspaces() { } func ExampleClient_GetRow() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.GetRowRequest{ // TODO: Fill request struct fields. @@ -149,14 +144,12 @@ func ExampleClient_GetRow() { } func ExampleClient_ListRows() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.ListRowsRequest{ // TODO: Fill request struct fields. @@ -176,13 +169,12 @@ func ExampleClient_ListRows() { } func ExampleClient_CreateRow() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.CreateRowRequest{ // TODO: Fill request struct fields. @@ -196,13 +188,12 @@ func ExampleClient_CreateRow() { } func ExampleClient_BatchCreateRows() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.BatchCreateRowsRequest{ // TODO: Fill request struct fields. @@ -216,13 +207,12 @@ func ExampleClient_BatchCreateRows() { } func ExampleClient_UpdateRow() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.UpdateRowRequest{ // TODO: Fill request struct fields. @@ -236,13 +226,12 @@ func ExampleClient_UpdateRow() { } func ExampleClient_BatchUpdateRows() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.BatchUpdateRowsRequest{ // TODO: Fill request struct fields. @@ -261,6 +250,7 @@ func ExampleClient_DeleteRow() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.DeleteRowRequest{ // TODO: Fill request struct fields. @@ -277,6 +267,7 @@ func ExampleClient_BatchDeleteRows() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.BatchDeleteRowsRequest{ // TODO: Fill request struct fields. diff --git a/artifactregistry/apiv1beta2/artifact_registry_client.go b/artifactregistry/apiv1beta2/artifact_registry_client.go index 00d6c8241e60..964c4c5c8cec 100644 --- a/artifactregistry/apiv1beta2/artifact_registry_client.go +++ b/artifactregistry/apiv1beta2/artifact_registry_client.go @@ -66,7 +66,7 @@ type CallOptions struct { TestIamPermissions []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("artifactregistry.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("artifactregistry.mtls.googleapis.com:443"), @@ -254,32 +254,254 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Artifact Registry API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListRepositories(context.Context, *artifactregistrypb.ListRepositoriesRequest, ...gax.CallOption) *RepositoryIterator + GetRepository(context.Context, *artifactregistrypb.GetRepositoryRequest, ...gax.CallOption) (*artifactregistrypb.Repository, error) + CreateRepository(context.Context, *artifactregistrypb.CreateRepositoryRequest, ...gax.CallOption) (*CreateRepositoryOperation, error) + CreateRepositoryOperation(name string) *CreateRepositoryOperation + UpdateRepository(context.Context, *artifactregistrypb.UpdateRepositoryRequest, ...gax.CallOption) (*artifactregistrypb.Repository, error) + DeleteRepository(context.Context, *artifactregistrypb.DeleteRepositoryRequest, ...gax.CallOption) (*DeleteRepositoryOperation, error) + DeleteRepositoryOperation(name string) *DeleteRepositoryOperation + ListPackages(context.Context, *artifactregistrypb.ListPackagesRequest, ...gax.CallOption) *PackageIterator + GetPackage(context.Context, *artifactregistrypb.GetPackageRequest, ...gax.CallOption) (*artifactregistrypb.Package, error) + DeletePackage(context.Context, *artifactregistrypb.DeletePackageRequest, ...gax.CallOption) (*DeletePackageOperation, error) + DeletePackageOperation(name string) *DeletePackageOperation + ListVersions(context.Context, *artifactregistrypb.ListVersionsRequest, ...gax.CallOption) *VersionIterator + GetVersion(context.Context, *artifactregistrypb.GetVersionRequest, ...gax.CallOption) (*artifactregistrypb.Version, error) + DeleteVersion(context.Context, *artifactregistrypb.DeleteVersionRequest, ...gax.CallOption) (*DeleteVersionOperation, error) + DeleteVersionOperation(name string) *DeleteVersionOperation + ListFiles(context.Context, *artifactregistrypb.ListFilesRequest, ...gax.CallOption) *FileIterator + GetFile(context.Context, *artifactregistrypb.GetFileRequest, ...gax.CallOption) (*artifactregistrypb.File, error) + ListTags(context.Context, *artifactregistrypb.ListTagsRequest, ...gax.CallOption) *TagIterator + GetTag(context.Context, *artifactregistrypb.GetTagRequest, ...gax.CallOption) (*artifactregistrypb.Tag, error) + CreateTag(context.Context, *artifactregistrypb.CreateTagRequest, ...gax.CallOption) (*artifactregistrypb.Tag, error) + UpdateTag(context.Context, *artifactregistrypb.UpdateTagRequest, ...gax.CallOption) (*artifactregistrypb.Tag, error) + DeleteTag(context.Context, *artifactregistrypb.DeleteTagRequest, ...gax.CallOption) error + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) +} + // Client is a client for interacting with Artifact Registry API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The Artifact Registry API service. +// +// Artifact Registry is an artifact management system for storing artifacts +// from different package management systems. +// +// The resources managed by this API are: +// +// Repositories, which group packages and their data. +// +// Packages, which group versions and their tags. +// +// Versions, which are specific forms of a package. +// +// Tags, which represent alternative names for versions. +// +// Files, which contain content and are optionally associated with a Package +// or Version. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListRepositories lists repositories. +func (c *Client) ListRepositories(ctx context.Context, req *artifactregistrypb.ListRepositoriesRequest, opts ...gax.CallOption) *RepositoryIterator { + return c.internalClient.ListRepositories(ctx, req, opts...) +} + +// GetRepository gets a repository. +func (c *Client) GetRepository(ctx context.Context, req *artifactregistrypb.GetRepositoryRequest, opts ...gax.CallOption) (*artifactregistrypb.Repository, error) { + return c.internalClient.GetRepository(ctx, req, opts...) +} + +// CreateRepository creates a repository. The returned Operation will finish once the +// repository has been created. Its response will be the created Repository. +func (c *Client) CreateRepository(ctx context.Context, req *artifactregistrypb.CreateRepositoryRequest, opts ...gax.CallOption) (*CreateRepositoryOperation, error) { + return c.internalClient.CreateRepository(ctx, req, opts...) +} + +// CreateRepositoryOperation returns a new CreateRepositoryOperation from a given name. +// The name must be that of a previously created CreateRepositoryOperation, possibly from a different process. +func (c *Client) CreateRepositoryOperation(name string) *CreateRepositoryOperation { + return c.internalClient.CreateRepositoryOperation(name) +} + +// UpdateRepository updates a repository. +func (c *Client) UpdateRepository(ctx context.Context, req *artifactregistrypb.UpdateRepositoryRequest, opts ...gax.CallOption) (*artifactregistrypb.Repository, error) { + return c.internalClient.UpdateRepository(ctx, req, opts...) +} + +// DeleteRepository deletes a repository and all of its contents. The returned Operation will +// finish once the repository has been deleted. It will not have any Operation +// metadata and will return a google.protobuf.Empty response. +func (c *Client) DeleteRepository(ctx context.Context, req *artifactregistrypb.DeleteRepositoryRequest, opts ...gax.CallOption) (*DeleteRepositoryOperation, error) { + return c.internalClient.DeleteRepository(ctx, req, opts...) +} + +// DeleteRepositoryOperation returns a new DeleteRepositoryOperation from a given name. +// The name must be that of a previously created DeleteRepositoryOperation, possibly from a different process. +func (c *Client) DeleteRepositoryOperation(name string) *DeleteRepositoryOperation { + return c.internalClient.DeleteRepositoryOperation(name) +} + +// ListPackages lists packages. +func (c *Client) ListPackages(ctx context.Context, req *artifactregistrypb.ListPackagesRequest, opts ...gax.CallOption) *PackageIterator { + return c.internalClient.ListPackages(ctx, req, opts...) +} + +// GetPackage gets a package. +func (c *Client) GetPackage(ctx context.Context, req *artifactregistrypb.GetPackageRequest, opts ...gax.CallOption) (*artifactregistrypb.Package, error) { + return c.internalClient.GetPackage(ctx, req, opts...) +} + +// DeletePackage deletes a package and all of its versions and tags. The returned operation +// will complete once the package has been deleted. +func (c *Client) DeletePackage(ctx context.Context, req *artifactregistrypb.DeletePackageRequest, opts ...gax.CallOption) (*DeletePackageOperation, error) { + return c.internalClient.DeletePackage(ctx, req, opts...) +} + +// DeletePackageOperation returns a new DeletePackageOperation from a given name. +// The name must be that of a previously created DeletePackageOperation, possibly from a different process. +func (c *Client) DeletePackageOperation(name string) *DeletePackageOperation { + return c.internalClient.DeletePackageOperation(name) +} + +// ListVersions lists versions. +func (c *Client) ListVersions(ctx context.Context, req *artifactregistrypb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { + return c.internalClient.ListVersions(ctx, req, opts...) +} + +// GetVersion gets a version +func (c *Client) GetVersion(ctx context.Context, req *artifactregistrypb.GetVersionRequest, opts ...gax.CallOption) (*artifactregistrypb.Version, error) { + return c.internalClient.GetVersion(ctx, req, opts...) +} + +// DeleteVersion deletes a version and all of its content. The returned operation will +// complete once the version has been deleted. +func (c *Client) DeleteVersion(ctx context.Context, req *artifactregistrypb.DeleteVersionRequest, opts ...gax.CallOption) (*DeleteVersionOperation, error) { + return c.internalClient.DeleteVersion(ctx, req, opts...) +} + +// DeleteVersionOperation returns a new DeleteVersionOperation from a given name. +// The name must be that of a previously created DeleteVersionOperation, possibly from a different process. +func (c *Client) DeleteVersionOperation(name string) *DeleteVersionOperation { + return c.internalClient.DeleteVersionOperation(name) +} + +// ListFiles lists files. +func (c *Client) ListFiles(ctx context.Context, req *artifactregistrypb.ListFilesRequest, opts ...gax.CallOption) *FileIterator { + return c.internalClient.ListFiles(ctx, req, opts...) +} + +// GetFile gets a file. +func (c *Client) GetFile(ctx context.Context, req *artifactregistrypb.GetFileRequest, opts ...gax.CallOption) (*artifactregistrypb.File, error) { + return c.internalClient.GetFile(ctx, req, opts...) +} + +// ListTags lists tags. +func (c *Client) ListTags(ctx context.Context, req *artifactregistrypb.ListTagsRequest, opts ...gax.CallOption) *TagIterator { + return c.internalClient.ListTags(ctx, req, opts...) +} + +// GetTag gets a tag. +func (c *Client) GetTag(ctx context.Context, req *artifactregistrypb.GetTagRequest, opts ...gax.CallOption) (*artifactregistrypb.Tag, error) { + return c.internalClient.GetTag(ctx, req, opts...) +} + +// CreateTag creates a tag. +func (c *Client) CreateTag(ctx context.Context, req *artifactregistrypb.CreateTagRequest, opts ...gax.CallOption) (*artifactregistrypb.Tag, error) { + return c.internalClient.CreateTag(ctx, req, opts...) +} + +// UpdateTag updates a tag. +func (c *Client) UpdateTag(ctx context.Context, req *artifactregistrypb.UpdateTagRequest, opts ...gax.CallOption) (*artifactregistrypb.Tag, error) { + return c.internalClient.UpdateTag(ctx, req, opts...) +} + +// DeleteTag deletes a tag. +func (c *Client) DeleteTag(ctx context.Context, req *artifactregistrypb.DeleteTagRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTag(ctx, req, opts...) +} + +// SetIamPolicy updates the IAM policy for a given resource. +func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// GetIamPolicy gets the IAM policy for a given resource. +func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions tests if the caller has a list of permissions on a resource. +func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Artifact Registry API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client artifactregistrypb.ArtifactRegistryClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new artifact registry client. +// NewClient creates a new artifact registry client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The Artifact Registry API service. // @@ -299,8 +521,7 @@ type Client struct { // Files, which contain content and are optionally associated with a Package // or Version. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -318,16 +539,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: artifactregistrypb.NewArtifactRegistryClient(connPool), + client: artifactregistrypb.NewArtifactRegistryClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -337,36 +561,36 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListRepositories lists repositories. -func (c *Client) ListRepositories(ctx context.Context, req *artifactregistrypb.ListRepositoriesRequest, opts ...gax.CallOption) *RepositoryIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ListRepositories(ctx context.Context, req *artifactregistrypb.ListRepositoriesRequest, opts ...gax.CallOption) *RepositoryIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListRepositories[0:len(c.CallOptions.ListRepositories):len(c.CallOptions.ListRepositories)], opts...) + opts = append((*c.CallOptions).ListRepositories[0:len((*c.CallOptions).ListRepositories):len((*c.CallOptions).ListRepositories)], opts...) it := &RepositoryIterator{} req = proto.Clone(req).(*artifactregistrypb.ListRepositoriesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*artifactregistrypb.Repository, string, error) { @@ -403,8 +627,7 @@ func (c *Client) ListRepositories(ctx context.Context, req *artifactregistrypb.L return it } -// GetRepository gets a repository. -func (c *Client) GetRepository(ctx context.Context, req *artifactregistrypb.GetRepositoryRequest, opts ...gax.CallOption) (*artifactregistrypb.Repository, error) { +func (c *gRPCClient) GetRepository(ctx context.Context, req *artifactregistrypb.GetRepositoryRequest, opts ...gax.CallOption) (*artifactregistrypb.Repository, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -412,7 +635,7 @@ func (c *Client) GetRepository(ctx context.Context, req *artifactregistrypb.GetR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetRepository[0:len(c.CallOptions.GetRepository):len(c.CallOptions.GetRepository)], opts...) + opts = append((*c.CallOptions).GetRepository[0:len((*c.CallOptions).GetRepository):len((*c.CallOptions).GetRepository)], opts...) var resp *artifactregistrypb.Repository err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -425,9 +648,7 @@ func (c *Client) GetRepository(ctx context.Context, req *artifactregistrypb.GetR return resp, nil } -// CreateRepository creates a repository. The returned Operation will finish once the -// repository has been created. Its response will be the created Repository. -func (c *Client) CreateRepository(ctx context.Context, req *artifactregistrypb.CreateRepositoryRequest, opts ...gax.CallOption) (*CreateRepositoryOperation, error) { +func (c *gRPCClient) CreateRepository(ctx context.Context, req *artifactregistrypb.CreateRepositoryRequest, opts ...gax.CallOption) (*CreateRepositoryOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -435,7 +656,7 @@ func (c *Client) CreateRepository(ctx context.Context, req *artifactregistrypb.C } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateRepository[0:len(c.CallOptions.CreateRepository):len(c.CallOptions.CreateRepository)], opts...) + opts = append((*c.CallOptions).CreateRepository[0:len((*c.CallOptions).CreateRepository):len((*c.CallOptions).CreateRepository)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -446,12 +667,11 @@ func (c *Client) CreateRepository(ctx context.Context, req *artifactregistrypb.C return nil, err } return &CreateRepositoryOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateRepository updates a repository. -func (c *Client) UpdateRepository(ctx context.Context, req *artifactregistrypb.UpdateRepositoryRequest, opts ...gax.CallOption) (*artifactregistrypb.Repository, error) { +func (c *gRPCClient) UpdateRepository(ctx context.Context, req *artifactregistrypb.UpdateRepositoryRequest, opts ...gax.CallOption) (*artifactregistrypb.Repository, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -459,7 +679,7 @@ func (c *Client) UpdateRepository(ctx context.Context, req *artifactregistrypb.U } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "repository.name", url.QueryEscape(req.GetRepository().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateRepository[0:len(c.CallOptions.UpdateRepository):len(c.CallOptions.UpdateRepository)], opts...) + opts = append((*c.CallOptions).UpdateRepository[0:len((*c.CallOptions).UpdateRepository):len((*c.CallOptions).UpdateRepository)], opts...) var resp *artifactregistrypb.Repository err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -472,10 +692,7 @@ func (c *Client) UpdateRepository(ctx context.Context, req *artifactregistrypb.U return resp, nil } -// DeleteRepository deletes a repository and all of its contents. The returned Operation will -// finish once the repository has been deleted. It will not have any Operation -// metadata and will return a google.protobuf.Empty response. -func (c *Client) DeleteRepository(ctx context.Context, req *artifactregistrypb.DeleteRepositoryRequest, opts ...gax.CallOption) (*DeleteRepositoryOperation, error) { +func (c *gRPCClient) DeleteRepository(ctx context.Context, req *artifactregistrypb.DeleteRepositoryRequest, opts ...gax.CallOption) (*DeleteRepositoryOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -483,7 +700,7 @@ func (c *Client) DeleteRepository(ctx context.Context, req *artifactregistrypb.D } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteRepository[0:len(c.CallOptions.DeleteRepository):len(c.CallOptions.DeleteRepository)], opts...) + opts = append((*c.CallOptions).DeleteRepository[0:len((*c.CallOptions).DeleteRepository):len((*c.CallOptions).DeleteRepository)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -494,15 +711,14 @@ func (c *Client) DeleteRepository(ctx context.Context, req *artifactregistrypb.D return nil, err } return &DeleteRepositoryOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListPackages lists packages. -func (c *Client) ListPackages(ctx context.Context, req *artifactregistrypb.ListPackagesRequest, opts ...gax.CallOption) *PackageIterator { +func (c *gRPCClient) ListPackages(ctx context.Context, req *artifactregistrypb.ListPackagesRequest, opts ...gax.CallOption) *PackageIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListPackages[0:len(c.CallOptions.ListPackages):len(c.CallOptions.ListPackages)], opts...) + opts = append((*c.CallOptions).ListPackages[0:len((*c.CallOptions).ListPackages):len((*c.CallOptions).ListPackages)], opts...) it := &PackageIterator{} req = proto.Clone(req).(*artifactregistrypb.ListPackagesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*artifactregistrypb.Package, string, error) { @@ -539,8 +755,7 @@ func (c *Client) ListPackages(ctx context.Context, req *artifactregistrypb.ListP return it } -// GetPackage gets a package. -func (c *Client) GetPackage(ctx context.Context, req *artifactregistrypb.GetPackageRequest, opts ...gax.CallOption) (*artifactregistrypb.Package, error) { +func (c *gRPCClient) GetPackage(ctx context.Context, req *artifactregistrypb.GetPackageRequest, opts ...gax.CallOption) (*artifactregistrypb.Package, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -548,7 +763,7 @@ func (c *Client) GetPackage(ctx context.Context, req *artifactregistrypb.GetPack } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetPackage[0:len(c.CallOptions.GetPackage):len(c.CallOptions.GetPackage)], opts...) + opts = append((*c.CallOptions).GetPackage[0:len((*c.CallOptions).GetPackage):len((*c.CallOptions).GetPackage)], opts...) var resp *artifactregistrypb.Package err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -561,9 +776,7 @@ func (c *Client) GetPackage(ctx context.Context, req *artifactregistrypb.GetPack return resp, nil } -// DeletePackage deletes a package and all of its versions and tags. The returned operation -// will complete once the package has been deleted. -func (c *Client) DeletePackage(ctx context.Context, req *artifactregistrypb.DeletePackageRequest, opts ...gax.CallOption) (*DeletePackageOperation, error) { +func (c *gRPCClient) DeletePackage(ctx context.Context, req *artifactregistrypb.DeletePackageRequest, opts ...gax.CallOption) (*DeletePackageOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -571,7 +784,7 @@ func (c *Client) DeletePackage(ctx context.Context, req *artifactregistrypb.Dele } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeletePackage[0:len(c.CallOptions.DeletePackage):len(c.CallOptions.DeletePackage)], opts...) + opts = append((*c.CallOptions).DeletePackage[0:len((*c.CallOptions).DeletePackage):len((*c.CallOptions).DeletePackage)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -582,15 +795,14 @@ func (c *Client) DeletePackage(ctx context.Context, req *artifactregistrypb.Dele return nil, err } return &DeletePackageOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListVersions lists versions. -func (c *Client) ListVersions(ctx context.Context, req *artifactregistrypb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { +func (c *gRPCClient) ListVersions(ctx context.Context, req *artifactregistrypb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListVersions[0:len(c.CallOptions.ListVersions):len(c.CallOptions.ListVersions)], opts...) + opts = append((*c.CallOptions).ListVersions[0:len((*c.CallOptions).ListVersions):len((*c.CallOptions).ListVersions)], opts...) it := &VersionIterator{} req = proto.Clone(req).(*artifactregistrypb.ListVersionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*artifactregistrypb.Version, string, error) { @@ -627,8 +839,7 @@ func (c *Client) ListVersions(ctx context.Context, req *artifactregistrypb.ListV return it } -// GetVersion gets a version -func (c *Client) GetVersion(ctx context.Context, req *artifactregistrypb.GetVersionRequest, opts ...gax.CallOption) (*artifactregistrypb.Version, error) { +func (c *gRPCClient) GetVersion(ctx context.Context, req *artifactregistrypb.GetVersionRequest, opts ...gax.CallOption) (*artifactregistrypb.Version, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -636,7 +847,7 @@ func (c *Client) GetVersion(ctx context.Context, req *artifactregistrypb.GetVers } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetVersion[0:len(c.CallOptions.GetVersion):len(c.CallOptions.GetVersion)], opts...) + opts = append((*c.CallOptions).GetVersion[0:len((*c.CallOptions).GetVersion):len((*c.CallOptions).GetVersion)], opts...) var resp *artifactregistrypb.Version err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -649,9 +860,7 @@ func (c *Client) GetVersion(ctx context.Context, req *artifactregistrypb.GetVers return resp, nil } -// DeleteVersion deletes a version and all of its content. The returned operation will -// complete once the version has been deleted. -func (c *Client) DeleteVersion(ctx context.Context, req *artifactregistrypb.DeleteVersionRequest, opts ...gax.CallOption) (*DeleteVersionOperation, error) { +func (c *gRPCClient) DeleteVersion(ctx context.Context, req *artifactregistrypb.DeleteVersionRequest, opts ...gax.CallOption) (*DeleteVersionOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -659,7 +868,7 @@ func (c *Client) DeleteVersion(ctx context.Context, req *artifactregistrypb.Dele } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteVersion[0:len(c.CallOptions.DeleteVersion):len(c.CallOptions.DeleteVersion)], opts...) + opts = append((*c.CallOptions).DeleteVersion[0:len((*c.CallOptions).DeleteVersion):len((*c.CallOptions).DeleteVersion)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -670,15 +879,14 @@ func (c *Client) DeleteVersion(ctx context.Context, req *artifactregistrypb.Dele return nil, err } return &DeleteVersionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListFiles lists files. -func (c *Client) ListFiles(ctx context.Context, req *artifactregistrypb.ListFilesRequest, opts ...gax.CallOption) *FileIterator { +func (c *gRPCClient) ListFiles(ctx context.Context, req *artifactregistrypb.ListFilesRequest, opts ...gax.CallOption) *FileIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListFiles[0:len(c.CallOptions.ListFiles):len(c.CallOptions.ListFiles)], opts...) + opts = append((*c.CallOptions).ListFiles[0:len((*c.CallOptions).ListFiles):len((*c.CallOptions).ListFiles)], opts...) it := &FileIterator{} req = proto.Clone(req).(*artifactregistrypb.ListFilesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*artifactregistrypb.File, string, error) { @@ -715,8 +923,7 @@ func (c *Client) ListFiles(ctx context.Context, req *artifactregistrypb.ListFile return it } -// GetFile gets a file. -func (c *Client) GetFile(ctx context.Context, req *artifactregistrypb.GetFileRequest, opts ...gax.CallOption) (*artifactregistrypb.File, error) { +func (c *gRPCClient) GetFile(ctx context.Context, req *artifactregistrypb.GetFileRequest, opts ...gax.CallOption) (*artifactregistrypb.File, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -724,7 +931,7 @@ func (c *Client) GetFile(ctx context.Context, req *artifactregistrypb.GetFileReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetFile[0:len(c.CallOptions.GetFile):len(c.CallOptions.GetFile)], opts...) + opts = append((*c.CallOptions).GetFile[0:len((*c.CallOptions).GetFile):len((*c.CallOptions).GetFile)], opts...) var resp *artifactregistrypb.File err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -737,11 +944,10 @@ func (c *Client) GetFile(ctx context.Context, req *artifactregistrypb.GetFileReq return resp, nil } -// ListTags lists tags. -func (c *Client) ListTags(ctx context.Context, req *artifactregistrypb.ListTagsRequest, opts ...gax.CallOption) *TagIterator { +func (c *gRPCClient) ListTags(ctx context.Context, req *artifactregistrypb.ListTagsRequest, opts ...gax.CallOption) *TagIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTags[0:len(c.CallOptions.ListTags):len(c.CallOptions.ListTags)], opts...) + opts = append((*c.CallOptions).ListTags[0:len((*c.CallOptions).ListTags):len((*c.CallOptions).ListTags)], opts...) it := &TagIterator{} req = proto.Clone(req).(*artifactregistrypb.ListTagsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*artifactregistrypb.Tag, string, error) { @@ -778,8 +984,7 @@ func (c *Client) ListTags(ctx context.Context, req *artifactregistrypb.ListTagsR return it } -// GetTag gets a tag. -func (c *Client) GetTag(ctx context.Context, req *artifactregistrypb.GetTagRequest, opts ...gax.CallOption) (*artifactregistrypb.Tag, error) { +func (c *gRPCClient) GetTag(ctx context.Context, req *artifactregistrypb.GetTagRequest, opts ...gax.CallOption) (*artifactregistrypb.Tag, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -787,7 +992,7 @@ func (c *Client) GetTag(ctx context.Context, req *artifactregistrypb.GetTagReque } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTag[0:len(c.CallOptions.GetTag):len(c.CallOptions.GetTag)], opts...) + opts = append((*c.CallOptions).GetTag[0:len((*c.CallOptions).GetTag):len((*c.CallOptions).GetTag)], opts...) var resp *artifactregistrypb.Tag err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -800,8 +1005,7 @@ func (c *Client) GetTag(ctx context.Context, req *artifactregistrypb.GetTagReque return resp, nil } -// CreateTag creates a tag. -func (c *Client) CreateTag(ctx context.Context, req *artifactregistrypb.CreateTagRequest, opts ...gax.CallOption) (*artifactregistrypb.Tag, error) { +func (c *gRPCClient) CreateTag(ctx context.Context, req *artifactregistrypb.CreateTagRequest, opts ...gax.CallOption) (*artifactregistrypb.Tag, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -809,7 +1013,7 @@ func (c *Client) CreateTag(ctx context.Context, req *artifactregistrypb.CreateTa } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTag[0:len(c.CallOptions.CreateTag):len(c.CallOptions.CreateTag)], opts...) + opts = append((*c.CallOptions).CreateTag[0:len((*c.CallOptions).CreateTag):len((*c.CallOptions).CreateTag)], opts...) var resp *artifactregistrypb.Tag err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -822,8 +1026,7 @@ func (c *Client) CreateTag(ctx context.Context, req *artifactregistrypb.CreateTa return resp, nil } -// UpdateTag updates a tag. -func (c *Client) UpdateTag(ctx context.Context, req *artifactregistrypb.UpdateTagRequest, opts ...gax.CallOption) (*artifactregistrypb.Tag, error) { +func (c *gRPCClient) UpdateTag(ctx context.Context, req *artifactregistrypb.UpdateTagRequest, opts ...gax.CallOption) (*artifactregistrypb.Tag, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -831,7 +1034,7 @@ func (c *Client) UpdateTag(ctx context.Context, req *artifactregistrypb.UpdateTa } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "tag.name", url.QueryEscape(req.GetTag().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTag[0:len(c.CallOptions.UpdateTag):len(c.CallOptions.UpdateTag)], opts...) + opts = append((*c.CallOptions).UpdateTag[0:len((*c.CallOptions).UpdateTag):len((*c.CallOptions).UpdateTag)], opts...) var resp *artifactregistrypb.Tag err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -844,8 +1047,7 @@ func (c *Client) UpdateTag(ctx context.Context, req *artifactregistrypb.UpdateTa return resp, nil } -// DeleteTag deletes a tag. -func (c *Client) DeleteTag(ctx context.Context, req *artifactregistrypb.DeleteTagRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteTag(ctx context.Context, req *artifactregistrypb.DeleteTagRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -853,7 +1055,7 @@ func (c *Client) DeleteTag(ctx context.Context, req *artifactregistrypb.DeleteTa } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTag[0:len(c.CallOptions.DeleteTag):len(c.CallOptions.DeleteTag)], opts...) + opts = append((*c.CallOptions).DeleteTag[0:len((*c.CallOptions).DeleteTag):len((*c.CallOptions).DeleteTag)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteTag(ctx, req, settings.GRPC...) @@ -862,11 +1064,10 @@ func (c *Client) DeleteTag(ctx context.Context, req *artifactregistrypb.DeleteTa return err } -// SetIamPolicy updates the IAM policy for a given resource. -func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -879,8 +1080,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques return resp, nil } -// GetIamPolicy gets the IAM policy for a given resource. -func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -888,7 +1088,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -901,8 +1101,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques return resp, nil } -// TestIamPermissions tests if the caller has a list of permissions on a resource. -func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *gRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -910,7 +1109,7 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -930,9 +1129,9 @@ type CreateRepositoryOperation struct { // CreateRepositoryOperation returns a new CreateRepositoryOperation from a given name. // The name must be that of a previously created CreateRepositoryOperation, possibly from a different process. -func (c *Client) CreateRepositoryOperation(name string) *CreateRepositoryOperation { +func (c *gRPCClient) CreateRepositoryOperation(name string) *CreateRepositoryOperation { return &CreateRepositoryOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -999,9 +1198,9 @@ type DeletePackageOperation struct { // DeletePackageOperation returns a new DeletePackageOperation from a given name. // The name must be that of a previously created DeletePackageOperation, possibly from a different process. -func (c *Client) DeletePackageOperation(name string) *DeletePackageOperation { +func (c *gRPCClient) DeletePackageOperation(name string) *DeletePackageOperation { return &DeletePackageOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1057,9 +1256,9 @@ type DeleteRepositoryOperation struct { // DeleteRepositoryOperation returns a new DeleteRepositoryOperation from a given name. // The name must be that of a previously created DeleteRepositoryOperation, possibly from a different process. -func (c *Client) DeleteRepositoryOperation(name string) *DeleteRepositoryOperation { +func (c *gRPCClient) DeleteRepositoryOperation(name string) *DeleteRepositoryOperation { return &DeleteRepositoryOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1115,9 +1314,9 @@ type DeleteVersionOperation struct { // DeleteVersionOperation returns a new DeleteVersionOperation from a given name. // The name must be that of a previously created DeleteVersionOperation, possibly from a different process. -func (c *Client) DeleteVersionOperation(name string) *DeleteVersionOperation { +func (c *gRPCClient) DeleteVersionOperation(name string) *DeleteVersionOperation { return &DeleteVersionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/artifactregistry/apiv1beta2/artifact_registry_client_example_test.go b/artifactregistry/apiv1beta2/artifact_registry_client_example_test.go index 6d0a91e9ca52..c0f5af5766e9 100644 --- a/artifactregistry/apiv1beta2/artifact_registry_client_example_test.go +++ b/artifactregistry/apiv1beta2/artifact_registry_client_example_test.go @@ -31,19 +31,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ListRepositories() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.ListRepositoriesRequest{ // TODO: Fill request struct fields. @@ -63,13 +63,12 @@ func ExampleClient_ListRepositories() { } func ExampleClient_GetRepository() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.GetRepositoryRequest{ // TODO: Fill request struct fields. @@ -83,13 +82,12 @@ func ExampleClient_GetRepository() { } func ExampleClient_CreateRepository() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.CreateRepositoryRequest{ // TODO: Fill request struct fields. @@ -108,13 +106,12 @@ func ExampleClient_CreateRepository() { } func ExampleClient_UpdateRepository() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.UpdateRepositoryRequest{ // TODO: Fill request struct fields. @@ -128,13 +125,12 @@ func ExampleClient_UpdateRepository() { } func ExampleClient_DeleteRepository() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.DeleteRepositoryRequest{ // TODO: Fill request struct fields. @@ -151,14 +147,12 @@ func ExampleClient_DeleteRepository() { } func ExampleClient_ListPackages() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.ListPackagesRequest{ // TODO: Fill request struct fields. @@ -178,13 +172,12 @@ func ExampleClient_ListPackages() { } func ExampleClient_GetPackage() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.GetPackageRequest{ // TODO: Fill request struct fields. @@ -198,13 +191,12 @@ func ExampleClient_GetPackage() { } func ExampleClient_DeletePackage() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.DeletePackageRequest{ // TODO: Fill request struct fields. @@ -221,14 +213,12 @@ func ExampleClient_DeletePackage() { } func ExampleClient_ListVersions() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.ListVersionsRequest{ // TODO: Fill request struct fields. @@ -248,13 +238,12 @@ func ExampleClient_ListVersions() { } func ExampleClient_GetVersion() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.GetVersionRequest{ // TODO: Fill request struct fields. @@ -268,13 +257,12 @@ func ExampleClient_GetVersion() { } func ExampleClient_DeleteVersion() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.DeleteVersionRequest{ // TODO: Fill request struct fields. @@ -291,14 +279,12 @@ func ExampleClient_DeleteVersion() { } func ExampleClient_ListFiles() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.ListFilesRequest{ // TODO: Fill request struct fields. @@ -318,13 +304,12 @@ func ExampleClient_ListFiles() { } func ExampleClient_GetFile() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.GetFileRequest{ // TODO: Fill request struct fields. @@ -338,14 +323,12 @@ func ExampleClient_GetFile() { } func ExampleClient_ListTags() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.ListTagsRequest{ // TODO: Fill request struct fields. @@ -365,13 +348,12 @@ func ExampleClient_ListTags() { } func ExampleClient_GetTag() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.GetTagRequest{ // TODO: Fill request struct fields. @@ -385,13 +367,12 @@ func ExampleClient_GetTag() { } func ExampleClient_CreateTag() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.CreateTagRequest{ // TODO: Fill request struct fields. @@ -405,13 +386,12 @@ func ExampleClient_CreateTag() { } func ExampleClient_UpdateTag() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.UpdateTagRequest{ // TODO: Fill request struct fields. @@ -430,6 +410,7 @@ func ExampleClient_DeleteTag() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.DeleteTagRequest{ // TODO: Fill request struct fields. @@ -441,13 +422,12 @@ func ExampleClient_DeleteTag() { } func ExampleClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -461,13 +441,12 @@ func ExampleClient_SetIamPolicy() { } func ExampleClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -481,13 +460,12 @@ func ExampleClient_GetIamPolicy() { } func ExampleClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/artifactregistry/apiv1beta2/doc.go b/artifactregistry/apiv1beta2/doc.go index 2dbd41ef069d..32332f073c35 100644 --- a/artifactregistry/apiv1beta2/doc.go +++ b/artifactregistry/apiv1beta2/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package artifactregistry // import "cloud.google.com/go/artifactregistry/apiv1beta2" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/asset/apiv1/asset_client.go b/asset/apiv1/asset_client.go index fe42167bc5e1..98baea4c879c 100644 --- a/asset/apiv1/asset_client.go +++ b/asset/apiv1/asset_client.go @@ -55,7 +55,7 @@ type CallOptions struct { AnalyzeIamPolicyLongrunning []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudasset.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudasset.mtls.googleapis.com:443"), @@ -159,37 +159,194 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Asset API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ExportAssets(context.Context, *assetpb.ExportAssetsRequest, ...gax.CallOption) (*ExportAssetsOperation, error) + ExportAssetsOperation(name string) *ExportAssetsOperation + BatchGetAssetsHistory(context.Context, *assetpb.BatchGetAssetsHistoryRequest, ...gax.CallOption) (*assetpb.BatchGetAssetsHistoryResponse, error) + CreateFeed(context.Context, *assetpb.CreateFeedRequest, ...gax.CallOption) (*assetpb.Feed, error) + GetFeed(context.Context, *assetpb.GetFeedRequest, ...gax.CallOption) (*assetpb.Feed, error) + ListFeeds(context.Context, *assetpb.ListFeedsRequest, ...gax.CallOption) (*assetpb.ListFeedsResponse, error) + UpdateFeed(context.Context, *assetpb.UpdateFeedRequest, ...gax.CallOption) (*assetpb.Feed, error) + DeleteFeed(context.Context, *assetpb.DeleteFeedRequest, ...gax.CallOption) error + SearchAllResources(context.Context, *assetpb.SearchAllResourcesRequest, ...gax.CallOption) *ResourceSearchResultIterator + SearchAllIamPolicies(context.Context, *assetpb.SearchAllIamPoliciesRequest, ...gax.CallOption) *IamPolicySearchResultIterator + AnalyzeIamPolicy(context.Context, *assetpb.AnalyzeIamPolicyRequest, ...gax.CallOption) (*assetpb.AnalyzeIamPolicyResponse, error) + AnalyzeIamPolicyLongrunning(context.Context, *assetpb.AnalyzeIamPolicyLongrunningRequest, ...gax.CallOption) (*AnalyzeIamPolicyLongrunningOperation, error) + AnalyzeIamPolicyLongrunningOperation(name string) *AnalyzeIamPolicyLongrunningOperation +} + // Client is a client for interacting with Cloud Asset API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Asset service definition. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ExportAssets exports assets with time and resource types to a given Cloud Storage +// location/BigQuery table. For Cloud Storage location destinations, the +// output format is newline-delimited JSON. Each line represents a +// google.cloud.asset.v1.Asset in the JSON format; for BigQuery table +// destinations, the output table stores the fields in asset proto as columns. +// This API implements the google.longrunning.Operation API +// , which allows you to keep track of the export. We recommend intervals of +// at least 2 seconds with exponential retry to poll the export operation +// result. For regular-size resource parent, the export operation usually +// finishes within 5 minutes. +func (c *Client) ExportAssets(ctx context.Context, req *assetpb.ExportAssetsRequest, opts ...gax.CallOption) (*ExportAssetsOperation, error) { + return c.internalClient.ExportAssets(ctx, req, opts...) +} + +// ExportAssetsOperation returns a new ExportAssetsOperation from a given name. +// The name must be that of a previously created ExportAssetsOperation, possibly from a different process. +func (c *Client) ExportAssetsOperation(name string) *ExportAssetsOperation { + return c.internalClient.ExportAssetsOperation(name) +} + +// BatchGetAssetsHistory batch gets the update history of assets that overlap a time window. +// For IAM_POLICY content, this API outputs history when the asset and its +// attached IAM POLICY both exist. This can create gaps in the output history. +// Otherwise, this API outputs history with asset in both non-delete or +// deleted status. +// If a specified asset does not exist, this API returns an INVALID_ARGUMENT +// error. +func (c *Client) BatchGetAssetsHistory(ctx context.Context, req *assetpb.BatchGetAssetsHistoryRequest, opts ...gax.CallOption) (*assetpb.BatchGetAssetsHistoryResponse, error) { + return c.internalClient.BatchGetAssetsHistory(ctx, req, opts...) +} + +// CreateFeed creates a feed in a parent project/folder/organization to listen to its +// asset updates. +func (c *Client) CreateFeed(ctx context.Context, req *assetpb.CreateFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { + return c.internalClient.CreateFeed(ctx, req, opts...) +} + +// GetFeed gets details about an asset feed. +func (c *Client) GetFeed(ctx context.Context, req *assetpb.GetFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { + return c.internalClient.GetFeed(ctx, req, opts...) +} + +// ListFeeds lists all asset feeds in a parent project/folder/organization. +func (c *Client) ListFeeds(ctx context.Context, req *assetpb.ListFeedsRequest, opts ...gax.CallOption) (*assetpb.ListFeedsResponse, error) { + return c.internalClient.ListFeeds(ctx, req, opts...) +} + +// UpdateFeed updates an asset feed configuration. +func (c *Client) UpdateFeed(ctx context.Context, req *assetpb.UpdateFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { + return c.internalClient.UpdateFeed(ctx, req, opts...) +} + +// DeleteFeed deletes an asset feed. +func (c *Client) DeleteFeed(ctx context.Context, req *assetpb.DeleteFeedRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteFeed(ctx, req, opts...) +} + +// SearchAllResources searches all Cloud resources within the specified scope, such as a project, +// folder, or organization. The caller must be granted the +// cloudasset.assets.searchAllResources permission on the desired scope, +// otherwise the request will be rejected. +func (c *Client) SearchAllResources(ctx context.Context, req *assetpb.SearchAllResourcesRequest, opts ...gax.CallOption) *ResourceSearchResultIterator { + return c.internalClient.SearchAllResources(ctx, req, opts...) +} + +// SearchAllIamPolicies searches all IAM policies within the specified scope, such as a project, +// folder, or organization. The caller must be granted the +// cloudasset.assets.searchAllIamPolicies permission on the desired scope, +// otherwise the request will be rejected. +func (c *Client) SearchAllIamPolicies(ctx context.Context, req *assetpb.SearchAllIamPoliciesRequest, opts ...gax.CallOption) *IamPolicySearchResultIterator { + return c.internalClient.SearchAllIamPolicies(ctx, req, opts...) +} + +// AnalyzeIamPolicy analyzes IAM policies to answer which identities have what accesses on +// which resources. +func (c *Client) AnalyzeIamPolicy(ctx context.Context, req *assetpb.AnalyzeIamPolicyRequest, opts ...gax.CallOption) (*assetpb.AnalyzeIamPolicyResponse, error) { + return c.internalClient.AnalyzeIamPolicy(ctx, req, opts...) +} + +// AnalyzeIamPolicyLongrunning analyzes IAM policies asynchronously to answer which identities have what +// accesses on which resources, and writes the analysis results to a Google +// Cloud Storage or a BigQuery destination. For Cloud Storage destination, the +// output format is the JSON format that represents a +// AnalyzeIamPolicyResponse. This method implements the +// google.longrunning.Operation, which allows you to track the operation +// status. We recommend intervals of at least 2 seconds with exponential +// backoff retry to poll the operation result. The metadata contains the +// request to help callers to map responses to requests. +func (c *Client) AnalyzeIamPolicyLongrunning(ctx context.Context, req *assetpb.AnalyzeIamPolicyLongrunningRequest, opts ...gax.CallOption) (*AnalyzeIamPolicyLongrunningOperation, error) { + return c.internalClient.AnalyzeIamPolicyLongrunning(ctx, req, opts...) +} + +// AnalyzeIamPolicyLongrunningOperation returns a new AnalyzeIamPolicyLongrunningOperation from a given name. +// The name must be that of a previously created AnalyzeIamPolicyLongrunningOperation, possibly from a different process. +func (c *Client) AnalyzeIamPolicyLongrunningOperation(name string) *AnalyzeIamPolicyLongrunningOperation { + return c.internalClient.AnalyzeIamPolicyLongrunningOperation(name) +} + +// gRPCClient is a client for interacting with Cloud Asset API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client assetpb.AssetServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new asset service client. +// NewClient creates a new asset service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Asset service definition. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -207,16 +364,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: assetpb.NewAssetServiceClient(connPool), + client: assetpb.NewAssetServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -226,42 +386,33 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ExportAssets exports assets with time and resource types to a given Cloud Storage -// location/BigQuery table. For Cloud Storage location destinations, the -// output format is newline-delimited JSON. Each line represents a -// google.cloud.asset.v1.Asset in the JSON format; for BigQuery table -// destinations, the output table stores the fields in asset proto as columns. -// This API implements the google.longrunning.Operation API -// , which allows you to keep track of the export. We recommend intervals of -// at least 2 seconds with exponential retry to poll the export operation -// result. For regular-size resource parent, the export operation usually -// finishes within 5 minutes. -func (c *Client) ExportAssets(ctx context.Context, req *assetpb.ExportAssetsRequest, opts ...gax.CallOption) (*ExportAssetsOperation, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ExportAssets(ctx context.Context, req *assetpb.ExportAssetsRequest, opts ...gax.CallOption) (*ExportAssetsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -269,7 +420,7 @@ func (c *Client) ExportAssets(ctx context.Context, req *assetpb.ExportAssetsRequ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportAssets[0:len(c.CallOptions.ExportAssets):len(c.CallOptions.ExportAssets)], opts...) + opts = append((*c.CallOptions).ExportAssets[0:len((*c.CallOptions).ExportAssets):len((*c.CallOptions).ExportAssets)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -280,18 +431,11 @@ func (c *Client) ExportAssets(ctx context.Context, req *assetpb.ExportAssetsRequ return nil, err } return &ExportAssetsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// BatchGetAssetsHistory batch gets the update history of assets that overlap a time window. -// For IAM_POLICY content, this API outputs history when the asset and its -// attached IAM POLICY both exist. This can create gaps in the output history. -// Otherwise, this API outputs history with asset in both non-delete or -// deleted status. -// If a specified asset does not exist, this API returns an INVALID_ARGUMENT -// error. -func (c *Client) BatchGetAssetsHistory(ctx context.Context, req *assetpb.BatchGetAssetsHistoryRequest, opts ...gax.CallOption) (*assetpb.BatchGetAssetsHistoryResponse, error) { +func (c *gRPCClient) BatchGetAssetsHistory(ctx context.Context, req *assetpb.BatchGetAssetsHistoryRequest, opts ...gax.CallOption) (*assetpb.BatchGetAssetsHistoryResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -299,7 +443,7 @@ func (c *Client) BatchGetAssetsHistory(ctx context.Context, req *assetpb.BatchGe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchGetAssetsHistory[0:len(c.CallOptions.BatchGetAssetsHistory):len(c.CallOptions.BatchGetAssetsHistory)], opts...) + opts = append((*c.CallOptions).BatchGetAssetsHistory[0:len((*c.CallOptions).BatchGetAssetsHistory):len((*c.CallOptions).BatchGetAssetsHistory)], opts...) var resp *assetpb.BatchGetAssetsHistoryResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -312,9 +456,7 @@ func (c *Client) BatchGetAssetsHistory(ctx context.Context, req *assetpb.BatchGe return resp, nil } -// CreateFeed creates a feed in a parent project/folder/organization to listen to its -// asset updates. -func (c *Client) CreateFeed(ctx context.Context, req *assetpb.CreateFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { +func (c *gRPCClient) CreateFeed(ctx context.Context, req *assetpb.CreateFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -322,7 +464,7 @@ func (c *Client) CreateFeed(ctx context.Context, req *assetpb.CreateFeedRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateFeed[0:len(c.CallOptions.CreateFeed):len(c.CallOptions.CreateFeed)], opts...) + opts = append((*c.CallOptions).CreateFeed[0:len((*c.CallOptions).CreateFeed):len((*c.CallOptions).CreateFeed)], opts...) var resp *assetpb.Feed err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -335,8 +477,7 @@ func (c *Client) CreateFeed(ctx context.Context, req *assetpb.CreateFeedRequest, return resp, nil } -// GetFeed gets details about an asset feed. -func (c *Client) GetFeed(ctx context.Context, req *assetpb.GetFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { +func (c *gRPCClient) GetFeed(ctx context.Context, req *assetpb.GetFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -344,7 +485,7 @@ func (c *Client) GetFeed(ctx context.Context, req *assetpb.GetFeedRequest, opts } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetFeed[0:len(c.CallOptions.GetFeed):len(c.CallOptions.GetFeed)], opts...) + opts = append((*c.CallOptions).GetFeed[0:len((*c.CallOptions).GetFeed):len((*c.CallOptions).GetFeed)], opts...) var resp *assetpb.Feed err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -357,8 +498,7 @@ func (c *Client) GetFeed(ctx context.Context, req *assetpb.GetFeedRequest, opts return resp, nil } -// ListFeeds lists all asset feeds in a parent project/folder/organization. -func (c *Client) ListFeeds(ctx context.Context, req *assetpb.ListFeedsRequest, opts ...gax.CallOption) (*assetpb.ListFeedsResponse, error) { +func (c *gRPCClient) ListFeeds(ctx context.Context, req *assetpb.ListFeedsRequest, opts ...gax.CallOption) (*assetpb.ListFeedsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -366,7 +506,7 @@ func (c *Client) ListFeeds(ctx context.Context, req *assetpb.ListFeedsRequest, o } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListFeeds[0:len(c.CallOptions.ListFeeds):len(c.CallOptions.ListFeeds)], opts...) + opts = append((*c.CallOptions).ListFeeds[0:len((*c.CallOptions).ListFeeds):len((*c.CallOptions).ListFeeds)], opts...) var resp *assetpb.ListFeedsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -379,8 +519,7 @@ func (c *Client) ListFeeds(ctx context.Context, req *assetpb.ListFeedsRequest, o return resp, nil } -// UpdateFeed updates an asset feed configuration. -func (c *Client) UpdateFeed(ctx context.Context, req *assetpb.UpdateFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { +func (c *gRPCClient) UpdateFeed(ctx context.Context, req *assetpb.UpdateFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -388,7 +527,7 @@ func (c *Client) UpdateFeed(ctx context.Context, req *assetpb.UpdateFeedRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "feed.name", url.QueryEscape(req.GetFeed().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateFeed[0:len(c.CallOptions.UpdateFeed):len(c.CallOptions.UpdateFeed)], opts...) + opts = append((*c.CallOptions).UpdateFeed[0:len((*c.CallOptions).UpdateFeed):len((*c.CallOptions).UpdateFeed)], opts...) var resp *assetpb.Feed err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -401,8 +540,7 @@ func (c *Client) UpdateFeed(ctx context.Context, req *assetpb.UpdateFeedRequest, return resp, nil } -// DeleteFeed deletes an asset feed. -func (c *Client) DeleteFeed(ctx context.Context, req *assetpb.DeleteFeedRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteFeed(ctx context.Context, req *assetpb.DeleteFeedRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -410,7 +548,7 @@ func (c *Client) DeleteFeed(ctx context.Context, req *assetpb.DeleteFeedRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteFeed[0:len(c.CallOptions.DeleteFeed):len(c.CallOptions.DeleteFeed)], opts...) + opts = append((*c.CallOptions).DeleteFeed[0:len((*c.CallOptions).DeleteFeed):len((*c.CallOptions).DeleteFeed)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteFeed(ctx, req, settings.GRPC...) @@ -419,14 +557,10 @@ func (c *Client) DeleteFeed(ctx context.Context, req *assetpb.DeleteFeedRequest, return err } -// SearchAllResources searches all Cloud resources within the specified scope, such as a project, -// folder, or organization. The caller must be granted the -// cloudasset.assets.searchAllResources permission on the desired scope, -// otherwise the request will be rejected. -func (c *Client) SearchAllResources(ctx context.Context, req *assetpb.SearchAllResourcesRequest, opts ...gax.CallOption) *ResourceSearchResultIterator { +func (c *gRPCClient) SearchAllResources(ctx context.Context, req *assetpb.SearchAllResourcesRequest, opts ...gax.CallOption) *ResourceSearchResultIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "scope", url.QueryEscape(req.GetScope()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SearchAllResources[0:len(c.CallOptions.SearchAllResources):len(c.CallOptions.SearchAllResources)], opts...) + opts = append((*c.CallOptions).SearchAllResources[0:len((*c.CallOptions).SearchAllResources):len((*c.CallOptions).SearchAllResources)], opts...) it := &ResourceSearchResultIterator{} req = proto.Clone(req).(*assetpb.SearchAllResourcesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*assetpb.ResourceSearchResult, string, error) { @@ -463,14 +597,10 @@ func (c *Client) SearchAllResources(ctx context.Context, req *assetpb.SearchAllR return it } -// SearchAllIamPolicies searches all IAM policies within the specified scope, such as a project, -// folder, or organization. The caller must be granted the -// cloudasset.assets.searchAllIamPolicies permission on the desired scope, -// otherwise the request will be rejected. -func (c *Client) SearchAllIamPolicies(ctx context.Context, req *assetpb.SearchAllIamPoliciesRequest, opts ...gax.CallOption) *IamPolicySearchResultIterator { +func (c *gRPCClient) SearchAllIamPolicies(ctx context.Context, req *assetpb.SearchAllIamPoliciesRequest, opts ...gax.CallOption) *IamPolicySearchResultIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "scope", url.QueryEscape(req.GetScope()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SearchAllIamPolicies[0:len(c.CallOptions.SearchAllIamPolicies):len(c.CallOptions.SearchAllIamPolicies)], opts...) + opts = append((*c.CallOptions).SearchAllIamPolicies[0:len((*c.CallOptions).SearchAllIamPolicies):len((*c.CallOptions).SearchAllIamPolicies)], opts...) it := &IamPolicySearchResultIterator{} req = proto.Clone(req).(*assetpb.SearchAllIamPoliciesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*assetpb.IamPolicySearchResult, string, error) { @@ -507,9 +637,7 @@ func (c *Client) SearchAllIamPolicies(ctx context.Context, req *assetpb.SearchAl return it } -// AnalyzeIamPolicy analyzes IAM policies to answer which identities have what accesses on -// which resources. -func (c *Client) AnalyzeIamPolicy(ctx context.Context, req *assetpb.AnalyzeIamPolicyRequest, opts ...gax.CallOption) (*assetpb.AnalyzeIamPolicyResponse, error) { +func (c *gRPCClient) AnalyzeIamPolicy(ctx context.Context, req *assetpb.AnalyzeIamPolicyRequest, opts ...gax.CallOption) (*assetpb.AnalyzeIamPolicyResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -517,7 +645,7 @@ func (c *Client) AnalyzeIamPolicy(ctx context.Context, req *assetpb.AnalyzeIamPo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "analysis_query.scope", url.QueryEscape(req.GetAnalysisQuery().GetScope()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AnalyzeIamPolicy[0:len(c.CallOptions.AnalyzeIamPolicy):len(c.CallOptions.AnalyzeIamPolicy)], opts...) + opts = append((*c.CallOptions).AnalyzeIamPolicy[0:len((*c.CallOptions).AnalyzeIamPolicy):len((*c.CallOptions).AnalyzeIamPolicy)], opts...) var resp *assetpb.AnalyzeIamPolicyResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -530,16 +658,7 @@ func (c *Client) AnalyzeIamPolicy(ctx context.Context, req *assetpb.AnalyzeIamPo return resp, nil } -// AnalyzeIamPolicyLongrunning analyzes IAM policies asynchronously to answer which identities have what -// accesses on which resources, and writes the analysis results to a Google -// Cloud Storage or a BigQuery destination. For Cloud Storage destination, the -// output format is the JSON format that represents a -// AnalyzeIamPolicyResponse. This method implements the -// google.longrunning.Operation, which allows you to track the operation -// status. We recommend intervals of at least 2 seconds with exponential -// backoff retry to poll the operation result. The metadata contains the -// request to help callers to map responses to requests. -func (c *Client) AnalyzeIamPolicyLongrunning(ctx context.Context, req *assetpb.AnalyzeIamPolicyLongrunningRequest, opts ...gax.CallOption) (*AnalyzeIamPolicyLongrunningOperation, error) { +func (c *gRPCClient) AnalyzeIamPolicyLongrunning(ctx context.Context, req *assetpb.AnalyzeIamPolicyLongrunningRequest, opts ...gax.CallOption) (*AnalyzeIamPolicyLongrunningOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -547,7 +666,7 @@ func (c *Client) AnalyzeIamPolicyLongrunning(ctx context.Context, req *assetpb.A } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "analysis_query.scope", url.QueryEscape(req.GetAnalysisQuery().GetScope()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AnalyzeIamPolicyLongrunning[0:len(c.CallOptions.AnalyzeIamPolicyLongrunning):len(c.CallOptions.AnalyzeIamPolicyLongrunning)], opts...) + opts = append((*c.CallOptions).AnalyzeIamPolicyLongrunning[0:len((*c.CallOptions).AnalyzeIamPolicyLongrunning):len((*c.CallOptions).AnalyzeIamPolicyLongrunning)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -558,7 +677,7 @@ func (c *Client) AnalyzeIamPolicyLongrunning(ctx context.Context, req *assetpb.A return nil, err } return &AnalyzeIamPolicyLongrunningOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -569,9 +688,9 @@ type AnalyzeIamPolicyLongrunningOperation struct { // AnalyzeIamPolicyLongrunningOperation returns a new AnalyzeIamPolicyLongrunningOperation from a given name. // The name must be that of a previously created AnalyzeIamPolicyLongrunningOperation, possibly from a different process. -func (c *Client) AnalyzeIamPolicyLongrunningOperation(name string) *AnalyzeIamPolicyLongrunningOperation { +func (c *gRPCClient) AnalyzeIamPolicyLongrunningOperation(name string) *AnalyzeIamPolicyLongrunningOperation { return &AnalyzeIamPolicyLongrunningOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -638,9 +757,9 @@ type ExportAssetsOperation struct { // ExportAssetsOperation returns a new ExportAssetsOperation from a given name. // The name must be that of a previously created ExportAssetsOperation, possibly from a different process. -func (c *Client) ExportAssetsOperation(name string) *ExportAssetsOperation { +func (c *gRPCClient) ExportAssetsOperation(name string) *ExportAssetsOperation { return &ExportAssetsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/asset/apiv1/asset_client_example_test.go b/asset/apiv1/asset_client_example_test.go index 85958d5f3f21..42680a57e557 100644 --- a/asset/apiv1/asset_client_example_test.go +++ b/asset/apiv1/asset_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ExportAssets() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.ExportAssetsRequest{ // TODO: Fill request struct fields. @@ -60,13 +61,12 @@ func ExampleClient_ExportAssets() { } func ExampleClient_BatchGetAssetsHistory() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.BatchGetAssetsHistoryRequest{ // TODO: Fill request struct fields. @@ -80,13 +80,12 @@ func ExampleClient_BatchGetAssetsHistory() { } func ExampleClient_CreateFeed() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.CreateFeedRequest{ // TODO: Fill request struct fields. @@ -100,13 +99,12 @@ func ExampleClient_CreateFeed() { } func ExampleClient_GetFeed() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.GetFeedRequest{ // TODO: Fill request struct fields. @@ -120,13 +118,12 @@ func ExampleClient_GetFeed() { } func ExampleClient_ListFeeds() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.ListFeedsRequest{ // TODO: Fill request struct fields. @@ -140,13 +137,12 @@ func ExampleClient_ListFeeds() { } func ExampleClient_UpdateFeed() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.UpdateFeedRequest{ // TODO: Fill request struct fields. @@ -165,6 +161,7 @@ func ExampleClient_DeleteFeed() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.DeleteFeedRequest{ // TODO: Fill request struct fields. @@ -176,14 +173,12 @@ func ExampleClient_DeleteFeed() { } func ExampleClient_SearchAllResources() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.SearchAllResourcesRequest{ // TODO: Fill request struct fields. @@ -203,14 +198,12 @@ func ExampleClient_SearchAllResources() { } func ExampleClient_SearchAllIamPolicies() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.SearchAllIamPoliciesRequest{ // TODO: Fill request struct fields. @@ -230,13 +223,12 @@ func ExampleClient_SearchAllIamPolicies() { } func ExampleClient_AnalyzeIamPolicy() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.AnalyzeIamPolicyRequest{ // TODO: Fill request struct fields. @@ -250,13 +242,12 @@ func ExampleClient_AnalyzeIamPolicy() { } func ExampleClient_AnalyzeIamPolicyLongrunning() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.AnalyzeIamPolicyLongrunningRequest{ // TODO: Fill request struct fields. diff --git a/asset/apiv1/doc.go b/asset/apiv1/doc.go index ed1eafff78e5..3ca9d59e562e 100644 --- a/asset/apiv1/doc.go +++ b/asset/apiv1/doc.go @@ -28,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package asset // import "cloud.google.com/go/asset/apiv1" import ( @@ -48,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/asset/apiv1p2beta1/asset_client.go b/asset/apiv1p2beta1/asset_client.go index 9661c2bb0b59..347d56114663 100644 --- a/asset/apiv1p2beta1/asset_client.go +++ b/asset/apiv1p2beta1/asset_client.go @@ -44,7 +44,7 @@ type CallOptions struct { DeleteFeed []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudasset.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudasset.mtls.googleapis.com:443"), @@ -99,32 +99,104 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Asset API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateFeed(context.Context, *assetpb.CreateFeedRequest, ...gax.CallOption) (*assetpb.Feed, error) + GetFeed(context.Context, *assetpb.GetFeedRequest, ...gax.CallOption) (*assetpb.Feed, error) + ListFeeds(context.Context, *assetpb.ListFeedsRequest, ...gax.CallOption) (*assetpb.ListFeedsResponse, error) + UpdateFeed(context.Context, *assetpb.UpdateFeedRequest, ...gax.CallOption) (*assetpb.Feed, error) + DeleteFeed(context.Context, *assetpb.DeleteFeedRequest, ...gax.CallOption) error +} + // Client is a client for interacting with Cloud Asset API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Asset service definition. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateFeed creates a feed in a parent project/folder/organization to listen to its +// asset updates. +func (c *Client) CreateFeed(ctx context.Context, req *assetpb.CreateFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { + return c.internalClient.CreateFeed(ctx, req, opts...) +} + +// GetFeed gets details about an asset feed. +func (c *Client) GetFeed(ctx context.Context, req *assetpb.GetFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { + return c.internalClient.GetFeed(ctx, req, opts...) +} + +// ListFeeds lists all asset feeds in a parent project/folder/organization. +func (c *Client) ListFeeds(ctx context.Context, req *assetpb.ListFeedsRequest, opts ...gax.CallOption) (*assetpb.ListFeedsResponse, error) { + return c.internalClient.ListFeeds(ctx, req, opts...) +} + +// UpdateFeed updates an asset feed configuration. +func (c *Client) UpdateFeed(ctx context.Context, req *assetpb.UpdateFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { + return c.internalClient.UpdateFeed(ctx, req, opts...) +} + +// DeleteFeed deletes an asset feed. +func (c *Client) DeleteFeed(ctx context.Context, req *assetpb.DeleteFeedRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteFeed(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud Asset API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client assetpb.AssetServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new asset service client. +// NewClient creates a new asset service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Asset service definition. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -142,43 +214,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: assetpb.NewAssetServiceClient(connPool), + client: assetpb.NewAssetServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateFeed creates a feed in a parent project/folder/organization to listen to its -// asset updates. -func (c *Client) CreateFeed(ctx context.Context, req *assetpb.CreateFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateFeed(ctx context.Context, req *assetpb.CreateFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -186,7 +259,7 @@ func (c *Client) CreateFeed(ctx context.Context, req *assetpb.CreateFeedRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateFeed[0:len(c.CallOptions.CreateFeed):len(c.CallOptions.CreateFeed)], opts...) + opts = append((*c.CallOptions).CreateFeed[0:len((*c.CallOptions).CreateFeed):len((*c.CallOptions).CreateFeed)], opts...) var resp *assetpb.Feed err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -199,8 +272,7 @@ func (c *Client) CreateFeed(ctx context.Context, req *assetpb.CreateFeedRequest, return resp, nil } -// GetFeed gets details about an asset feed. -func (c *Client) GetFeed(ctx context.Context, req *assetpb.GetFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { +func (c *gRPCClient) GetFeed(ctx context.Context, req *assetpb.GetFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -208,7 +280,7 @@ func (c *Client) GetFeed(ctx context.Context, req *assetpb.GetFeedRequest, opts } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetFeed[0:len(c.CallOptions.GetFeed):len(c.CallOptions.GetFeed)], opts...) + opts = append((*c.CallOptions).GetFeed[0:len((*c.CallOptions).GetFeed):len((*c.CallOptions).GetFeed)], opts...) var resp *assetpb.Feed err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -221,8 +293,7 @@ func (c *Client) GetFeed(ctx context.Context, req *assetpb.GetFeedRequest, opts return resp, nil } -// ListFeeds lists all asset feeds in a parent project/folder/organization. -func (c *Client) ListFeeds(ctx context.Context, req *assetpb.ListFeedsRequest, opts ...gax.CallOption) (*assetpb.ListFeedsResponse, error) { +func (c *gRPCClient) ListFeeds(ctx context.Context, req *assetpb.ListFeedsRequest, opts ...gax.CallOption) (*assetpb.ListFeedsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -230,7 +301,7 @@ func (c *Client) ListFeeds(ctx context.Context, req *assetpb.ListFeedsRequest, o } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListFeeds[0:len(c.CallOptions.ListFeeds):len(c.CallOptions.ListFeeds)], opts...) + opts = append((*c.CallOptions).ListFeeds[0:len((*c.CallOptions).ListFeeds):len((*c.CallOptions).ListFeeds)], opts...) var resp *assetpb.ListFeedsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -243,8 +314,7 @@ func (c *Client) ListFeeds(ctx context.Context, req *assetpb.ListFeedsRequest, o return resp, nil } -// UpdateFeed updates an asset feed configuration. -func (c *Client) UpdateFeed(ctx context.Context, req *assetpb.UpdateFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { +func (c *gRPCClient) UpdateFeed(ctx context.Context, req *assetpb.UpdateFeedRequest, opts ...gax.CallOption) (*assetpb.Feed, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -252,7 +322,7 @@ func (c *Client) UpdateFeed(ctx context.Context, req *assetpb.UpdateFeedRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "feed.name", url.QueryEscape(req.GetFeed().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateFeed[0:len(c.CallOptions.UpdateFeed):len(c.CallOptions.UpdateFeed)], opts...) + opts = append((*c.CallOptions).UpdateFeed[0:len((*c.CallOptions).UpdateFeed):len((*c.CallOptions).UpdateFeed)], opts...) var resp *assetpb.Feed err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -265,8 +335,7 @@ func (c *Client) UpdateFeed(ctx context.Context, req *assetpb.UpdateFeedRequest, return resp, nil } -// DeleteFeed deletes an asset feed. -func (c *Client) DeleteFeed(ctx context.Context, req *assetpb.DeleteFeedRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteFeed(ctx context.Context, req *assetpb.DeleteFeedRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -274,7 +343,7 @@ func (c *Client) DeleteFeed(ctx context.Context, req *assetpb.DeleteFeedRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteFeed[0:len(c.CallOptions.DeleteFeed):len(c.CallOptions.DeleteFeed)], opts...) + opts = append((*c.CallOptions).DeleteFeed[0:len((*c.CallOptions).DeleteFeed):len((*c.CallOptions).DeleteFeed)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteFeed(ctx, req, settings.GRPC...) diff --git a/asset/apiv1p2beta1/asset_client_example_test.go b/asset/apiv1p2beta1/asset_client_example_test.go index cdf600b5c9a1..9b824e0810a5 100644 --- a/asset/apiv1p2beta1/asset_client_example_test.go +++ b/asset/apiv1p2beta1/asset_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateFeed() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1p2beta1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.CreateFeedRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleClient_CreateFeed() { } func ExampleClient_GetFeed() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1p2beta1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.GetFeedRequest{ // TODO: Fill request struct fields. @@ -74,13 +74,12 @@ func ExampleClient_GetFeed() { } func ExampleClient_ListFeeds() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1p2beta1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.ListFeedsRequest{ // TODO: Fill request struct fields. @@ -94,13 +93,12 @@ func ExampleClient_ListFeeds() { } func ExampleClient_UpdateFeed() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1p2beta1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.UpdateFeedRequest{ // TODO: Fill request struct fields. @@ -119,6 +117,7 @@ func ExampleClient_DeleteFeed() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.DeleteFeedRequest{ // TODO: Fill request struct fields. diff --git a/asset/apiv1p2beta1/doc.go b/asset/apiv1p2beta1/doc.go index b88cd934fe07..5e2c253c99bd 100644 --- a/asset/apiv1p2beta1/doc.go +++ b/asset/apiv1p2beta1/doc.go @@ -19,6 +19,8 @@ // // The cloud asset API manages the history and inventory of cloud resources. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -28,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package asset // import "cloud.google.com/go/asset/apiv1p2beta1" import ( @@ -48,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/asset/apiv1p5beta1/asset_client.go b/asset/apiv1p5beta1/asset_client.go index 9b4f23e9cb53..a75735142038 100644 --- a/asset/apiv1p5beta1/asset_client.go +++ b/asset/apiv1p5beta1/asset_client.go @@ -42,7 +42,7 @@ type CallOptions struct { ListAssets []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudasset.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudasset.mtls.googleapis.com:443"), @@ -71,32 +71,80 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Asset API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListAssets(context.Context, *assetpb.ListAssetsRequest, ...gax.CallOption) *AssetIterator +} + // Client is a client for interacting with Cloud Asset API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Asset service definition. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListAssets lists assets with time and resource types and returns paged results in +// response. +func (c *Client) ListAssets(ctx context.Context, req *assetpb.ListAssetsRequest, opts ...gax.CallOption) *AssetIterator { + return c.internalClient.ListAssets(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud Asset API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client assetpb.AssetServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new asset service client. +// NewClient creates a new asset service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Asset service definition. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -114,46 +162,47 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: assetpb.NewAssetServiceClient(connPool), + client: assetpb.NewAssetServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListAssets lists assets with time and resource types and returns paged results in -// response. -func (c *Client) ListAssets(ctx context.Context, req *assetpb.ListAssetsRequest, opts ...gax.CallOption) *AssetIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ListAssets(ctx context.Context, req *assetpb.ListAssetsRequest, opts ...gax.CallOption) *AssetIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAssets[0:len(c.CallOptions.ListAssets):len(c.CallOptions.ListAssets)], opts...) + opts = append((*c.CallOptions).ListAssets[0:len((*c.CallOptions).ListAssets):len((*c.CallOptions).ListAssets)], opts...) it := &AssetIterator{} req = proto.Clone(req).(*assetpb.ListAssetsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*assetpb.Asset, string, error) { diff --git a/asset/apiv1p5beta1/asset_client_example_test.go b/asset/apiv1p5beta1/asset_client_example_test.go index 9a3fed968424..03b35f664536 100644 --- a/asset/apiv1p5beta1/asset_client_example_test.go +++ b/asset/apiv1p5beta1/asset_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ListAssets() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1p5beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.ListAssetsRequest{ // TODO: Fill request struct fields. diff --git a/asset/apiv1p5beta1/doc.go b/asset/apiv1p5beta1/doc.go index d079d759506e..9a28ef3c1225 100644 --- a/asset/apiv1p5beta1/doc.go +++ b/asset/apiv1p5beta1/doc.go @@ -19,6 +19,8 @@ // // The cloud asset API manages the history and inventory of cloud resources. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -28,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package asset // import "cloud.google.com/go/asset/apiv1p5beta1" import ( @@ -48,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/assuredworkloads/apiv1beta1/assured_workloads_client.go b/assuredworkloads/apiv1beta1/assured_workloads_client.go index c156d012b213..f31d27216008 100644 --- a/assuredworkloads/apiv1beta1/assured_workloads_client.go +++ b/assuredworkloads/apiv1beta1/assured_workloads_client.go @@ -49,7 +49,7 @@ type CallOptions struct { ListWorkloads []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("assuredworkloads.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("assuredworkloads.mtls.googleapis.com:443"), @@ -101,37 +101,125 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Assured Workloads API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateWorkload(context.Context, *assuredworkloadspb.CreateWorkloadRequest, ...gax.CallOption) (*CreateWorkloadOperation, error) + CreateWorkloadOperation(name string) *CreateWorkloadOperation + UpdateWorkload(context.Context, *assuredworkloadspb.UpdateWorkloadRequest, ...gax.CallOption) (*assuredworkloadspb.Workload, error) + DeleteWorkload(context.Context, *assuredworkloadspb.DeleteWorkloadRequest, ...gax.CallOption) error + GetWorkload(context.Context, *assuredworkloadspb.GetWorkloadRequest, ...gax.CallOption) (*assuredworkloadspb.Workload, error) + ListWorkloads(context.Context, *assuredworkloadspb.ListWorkloadsRequest, ...gax.CallOption) *WorkloadIterator +} + // Client is a client for interacting with Assured Workloads API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service to manage AssuredWorkloads. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateWorkload creates Assured Workload. +func (c *Client) CreateWorkload(ctx context.Context, req *assuredworkloadspb.CreateWorkloadRequest, opts ...gax.CallOption) (*CreateWorkloadOperation, error) { + return c.internalClient.CreateWorkload(ctx, req, opts...) +} + +// CreateWorkloadOperation returns a new CreateWorkloadOperation from a given name. +// The name must be that of a previously created CreateWorkloadOperation, possibly from a different process. +func (c *Client) CreateWorkloadOperation(name string) *CreateWorkloadOperation { + return c.internalClient.CreateWorkloadOperation(name) +} + +// UpdateWorkload updates an existing workload. +// Currently allows updating of workload display_name and labels. +// For force updates don’t set etag field in the Workload. +// Only one update operation per workload can be in progress. +func (c *Client) UpdateWorkload(ctx context.Context, req *assuredworkloadspb.UpdateWorkloadRequest, opts ...gax.CallOption) (*assuredworkloadspb.Workload, error) { + return c.internalClient.UpdateWorkload(ctx, req, opts...) +} + +// DeleteWorkload deletes the workload. Make sure that workload’s direct children are already +// in a deleted state, otherwise the request will fail with a +// FAILED_PRECONDITION error. +func (c *Client) DeleteWorkload(ctx context.Context, req *assuredworkloadspb.DeleteWorkloadRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteWorkload(ctx, req, opts...) +} + +// GetWorkload gets Assured Workload associated with a CRM Node +func (c *Client) GetWorkload(ctx context.Context, req *assuredworkloadspb.GetWorkloadRequest, opts ...gax.CallOption) (*assuredworkloadspb.Workload, error) { + return c.internalClient.GetWorkload(ctx, req, opts...) +} + +// ListWorkloads lists Assured Workloads under a CRM Node. +func (c *Client) ListWorkloads(ctx context.Context, req *assuredworkloadspb.ListWorkloadsRequest, opts ...gax.CallOption) *WorkloadIterator { + return c.internalClient.ListWorkloads(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Assured Workloads API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client assuredworkloadspb.AssuredWorkloadsServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new assured workloads service client. +// NewClient creates a new assured workloads service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service to manage AssuredWorkloads. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -149,16 +237,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: assuredworkloadspb.NewAssuredWorkloadsServiceClient(connPool), + client: assuredworkloadspb.NewAssuredWorkloadsServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -168,33 +259,33 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateWorkload creates Assured Workload. -func (c *Client) CreateWorkload(ctx context.Context, req *assuredworkloadspb.CreateWorkloadRequest, opts ...gax.CallOption) (*CreateWorkloadOperation, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateWorkload(ctx context.Context, req *assuredworkloadspb.CreateWorkloadRequest, opts ...gax.CallOption) (*CreateWorkloadOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -202,7 +293,7 @@ func (c *Client) CreateWorkload(ctx context.Context, req *assuredworkloadspb.Cre } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateWorkload[0:len(c.CallOptions.CreateWorkload):len(c.CallOptions.CreateWorkload)], opts...) + opts = append((*c.CallOptions).CreateWorkload[0:len((*c.CallOptions).CreateWorkload):len((*c.CallOptions).CreateWorkload)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -213,15 +304,11 @@ func (c *Client) CreateWorkload(ctx context.Context, req *assuredworkloadspb.Cre return nil, err } return &CreateWorkloadOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateWorkload updates an existing workload. -// Currently allows updating of workload display_name and labels. -// For force updates don’t set etag field in the Workload. -// Only one update operation per workload can be in progress. -func (c *Client) UpdateWorkload(ctx context.Context, req *assuredworkloadspb.UpdateWorkloadRequest, opts ...gax.CallOption) (*assuredworkloadspb.Workload, error) { +func (c *gRPCClient) UpdateWorkload(ctx context.Context, req *assuredworkloadspb.UpdateWorkloadRequest, opts ...gax.CallOption) (*assuredworkloadspb.Workload, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -229,7 +316,7 @@ func (c *Client) UpdateWorkload(ctx context.Context, req *assuredworkloadspb.Upd } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workload.name", url.QueryEscape(req.GetWorkload().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateWorkload[0:len(c.CallOptions.UpdateWorkload):len(c.CallOptions.UpdateWorkload)], opts...) + opts = append((*c.CallOptions).UpdateWorkload[0:len((*c.CallOptions).UpdateWorkload):len((*c.CallOptions).UpdateWorkload)], opts...) var resp *assuredworkloadspb.Workload err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -242,10 +329,7 @@ func (c *Client) UpdateWorkload(ctx context.Context, req *assuredworkloadspb.Upd return resp, nil } -// DeleteWorkload deletes the workload. Make sure that workload’s direct children are already -// in a deleted state, otherwise the request will fail with a -// FAILED_PRECONDITION error. -func (c *Client) DeleteWorkload(ctx context.Context, req *assuredworkloadspb.DeleteWorkloadRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteWorkload(ctx context.Context, req *assuredworkloadspb.DeleteWorkloadRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -253,7 +337,7 @@ func (c *Client) DeleteWorkload(ctx context.Context, req *assuredworkloadspb.Del } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteWorkload[0:len(c.CallOptions.DeleteWorkload):len(c.CallOptions.DeleteWorkload)], opts...) + opts = append((*c.CallOptions).DeleteWorkload[0:len((*c.CallOptions).DeleteWorkload):len((*c.CallOptions).DeleteWorkload)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteWorkload(ctx, req, settings.GRPC...) @@ -262,8 +346,7 @@ func (c *Client) DeleteWorkload(ctx context.Context, req *assuredworkloadspb.Del return err } -// GetWorkload gets Assured Workload associated with a CRM Node -func (c *Client) GetWorkload(ctx context.Context, req *assuredworkloadspb.GetWorkloadRequest, opts ...gax.CallOption) (*assuredworkloadspb.Workload, error) { +func (c *gRPCClient) GetWorkload(ctx context.Context, req *assuredworkloadspb.GetWorkloadRequest, opts ...gax.CallOption) (*assuredworkloadspb.Workload, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -271,7 +354,7 @@ func (c *Client) GetWorkload(ctx context.Context, req *assuredworkloadspb.GetWor } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetWorkload[0:len(c.CallOptions.GetWorkload):len(c.CallOptions.GetWorkload)], opts...) + opts = append((*c.CallOptions).GetWorkload[0:len((*c.CallOptions).GetWorkload):len((*c.CallOptions).GetWorkload)], opts...) var resp *assuredworkloadspb.Workload err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -284,11 +367,10 @@ func (c *Client) GetWorkload(ctx context.Context, req *assuredworkloadspb.GetWor return resp, nil } -// ListWorkloads lists Assured Workloads under a CRM Node. -func (c *Client) ListWorkloads(ctx context.Context, req *assuredworkloadspb.ListWorkloadsRequest, opts ...gax.CallOption) *WorkloadIterator { +func (c *gRPCClient) ListWorkloads(ctx context.Context, req *assuredworkloadspb.ListWorkloadsRequest, opts ...gax.CallOption) *WorkloadIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListWorkloads[0:len(c.CallOptions.ListWorkloads):len(c.CallOptions.ListWorkloads)], opts...) + opts = append((*c.CallOptions).ListWorkloads[0:len((*c.CallOptions).ListWorkloads):len((*c.CallOptions).ListWorkloads)], opts...) it := &WorkloadIterator{} req = proto.Clone(req).(*assuredworkloadspb.ListWorkloadsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*assuredworkloadspb.Workload, string, error) { @@ -332,9 +414,9 @@ type CreateWorkloadOperation struct { // CreateWorkloadOperation returns a new CreateWorkloadOperation from a given name. // The name must be that of a previously created CreateWorkloadOperation, possibly from a different process. -func (c *Client) CreateWorkloadOperation(name string) *CreateWorkloadOperation { +func (c *gRPCClient) CreateWorkloadOperation(name string) *CreateWorkloadOperation { return &CreateWorkloadOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/assuredworkloads/apiv1beta1/assured_workloads_client_example_test.go b/assuredworkloads/apiv1beta1/assured_workloads_client_example_test.go index de9b8081629c..b064d5c154bb 100644 --- a/assuredworkloads/apiv1beta1/assured_workloads_client_example_test.go +++ b/assuredworkloads/apiv1beta1/assured_workloads_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateWorkload() { - // import assuredworkloadspb "google.golang.org/genproto/googleapis/cloud/assuredworkloads/v1beta1" - ctx := context.Background() c, err := assuredworkloads.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assuredworkloadspb.CreateWorkloadRequest{ // TODO: Fill request struct fields. @@ -60,13 +61,12 @@ func ExampleClient_CreateWorkload() { } func ExampleClient_UpdateWorkload() { - // import assuredworkloadspb "google.golang.org/genproto/googleapis/cloud/assuredworkloads/v1beta1" - ctx := context.Background() c, err := assuredworkloads.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assuredworkloadspb.UpdateWorkloadRequest{ // TODO: Fill request struct fields. @@ -85,6 +85,7 @@ func ExampleClient_DeleteWorkload() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &assuredworkloadspb.DeleteWorkloadRequest{ // TODO: Fill request struct fields. @@ -96,13 +97,12 @@ func ExampleClient_DeleteWorkload() { } func ExampleClient_GetWorkload() { - // import assuredworkloadspb "google.golang.org/genproto/googleapis/cloud/assuredworkloads/v1beta1" - ctx := context.Background() c, err := assuredworkloads.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assuredworkloadspb.GetWorkloadRequest{ // TODO: Fill request struct fields. @@ -116,14 +116,12 @@ func ExampleClient_GetWorkload() { } func ExampleClient_ListWorkloads() { - // import assuredworkloadspb "google.golang.org/genproto/googleapis/cloud/assuredworkloads/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := assuredworkloads.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assuredworkloadspb.ListWorkloadsRequest{ // TODO: Fill request struct fields. diff --git a/assuredworkloads/apiv1beta1/doc.go b/assuredworkloads/apiv1beta1/doc.go index 7d1a1d75b9df..dca589e3eb9d 100644 --- a/assuredworkloads/apiv1beta1/doc.go +++ b/assuredworkloads/apiv1beta1/doc.go @@ -17,6 +17,8 @@ // Package assuredworkloads is an auto-generated package for the // Assured Workloads API. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -26,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package assuredworkloads // import "cloud.google.com/go/assuredworkloads/apiv1beta1" import ( @@ -46,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/automl/apiv1/auto_ml_client.go b/automl/apiv1/auto_ml_client.go index 783e7a7add64..c11c0c7faa01 100644 --- a/automl/apiv1/auto_ml_client.go +++ b/automl/apiv1/auto_ml_client.go @@ -62,7 +62,7 @@ type CallOptions struct { ListModelEvaluations []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("automl.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("automl.mtls.googleapis.com:443"), @@ -196,32 +196,309 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud AutoML API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateDataset(context.Context, *automlpb.CreateDatasetRequest, ...gax.CallOption) (*CreateDatasetOperation, error) + CreateDatasetOperation(name string) *CreateDatasetOperation + GetDataset(context.Context, *automlpb.GetDatasetRequest, ...gax.CallOption) (*automlpb.Dataset, error) + ListDatasets(context.Context, *automlpb.ListDatasetsRequest, ...gax.CallOption) *DatasetIterator + UpdateDataset(context.Context, *automlpb.UpdateDatasetRequest, ...gax.CallOption) (*automlpb.Dataset, error) + DeleteDataset(context.Context, *automlpb.DeleteDatasetRequest, ...gax.CallOption) (*DeleteDatasetOperation, error) + DeleteDatasetOperation(name string) *DeleteDatasetOperation + ImportData(context.Context, *automlpb.ImportDataRequest, ...gax.CallOption) (*ImportDataOperation, error) + ImportDataOperation(name string) *ImportDataOperation + ExportData(context.Context, *automlpb.ExportDataRequest, ...gax.CallOption) (*ExportDataOperation, error) + ExportDataOperation(name string) *ExportDataOperation + GetAnnotationSpec(context.Context, *automlpb.GetAnnotationSpecRequest, ...gax.CallOption) (*automlpb.AnnotationSpec, error) + CreateModel(context.Context, *automlpb.CreateModelRequest, ...gax.CallOption) (*CreateModelOperation, error) + CreateModelOperation(name string) *CreateModelOperation + GetModel(context.Context, *automlpb.GetModelRequest, ...gax.CallOption) (*automlpb.Model, error) + ListModels(context.Context, *automlpb.ListModelsRequest, ...gax.CallOption) *ModelIterator + DeleteModel(context.Context, *automlpb.DeleteModelRequest, ...gax.CallOption) (*DeleteModelOperation, error) + DeleteModelOperation(name string) *DeleteModelOperation + UpdateModel(context.Context, *automlpb.UpdateModelRequest, ...gax.CallOption) (*automlpb.Model, error) + DeployModel(context.Context, *automlpb.DeployModelRequest, ...gax.CallOption) (*DeployModelOperation, error) + DeployModelOperation(name string) *DeployModelOperation + UndeployModel(context.Context, *automlpb.UndeployModelRequest, ...gax.CallOption) (*UndeployModelOperation, error) + UndeployModelOperation(name string) *UndeployModelOperation + ExportModel(context.Context, *automlpb.ExportModelRequest, ...gax.CallOption) (*ExportModelOperation, error) + ExportModelOperation(name string) *ExportModelOperation + GetModelEvaluation(context.Context, *automlpb.GetModelEvaluationRequest, ...gax.CallOption) (*automlpb.ModelEvaluation, error) + ListModelEvaluations(context.Context, *automlpb.ListModelEvaluationsRequest, ...gax.CallOption) *ModelEvaluationIterator +} + // Client is a client for interacting with Cloud AutoML API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// AutoML Server API. +// +// The resource names are assigned by the server. +// The server never reuses names that it has created after the resources with +// those names are deleted. +// +// An ID of a resource is the last element of the item’s resource name. For +// projects/{project_id}/locations/{location_id}/datasets/{dataset_id}, then +// the id for the item is {dataset_id}. +// +// Currently the only supported location_id is “us-central1”. +// +// On any input that is documented to expect a string parameter in +// snake_case or kebab-case, either of those cases is accepted. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateDataset creates a dataset. +func (c *Client) CreateDataset(ctx context.Context, req *automlpb.CreateDatasetRequest, opts ...gax.CallOption) (*CreateDatasetOperation, error) { + return c.internalClient.CreateDataset(ctx, req, opts...) +} + +// CreateDatasetOperation returns a new CreateDatasetOperation from a given name. +// The name must be that of a previously created CreateDatasetOperation, possibly from a different process. +func (c *Client) CreateDatasetOperation(name string) *CreateDatasetOperation { + return c.internalClient.CreateDatasetOperation(name) +} + +// GetDataset gets a dataset. +func (c *Client) GetDataset(ctx context.Context, req *automlpb.GetDatasetRequest, opts ...gax.CallOption) (*automlpb.Dataset, error) { + return c.internalClient.GetDataset(ctx, req, opts...) +} + +// ListDatasets lists datasets in a project. +func (c *Client) ListDatasets(ctx context.Context, req *automlpb.ListDatasetsRequest, opts ...gax.CallOption) *DatasetIterator { + return c.internalClient.ListDatasets(ctx, req, opts...) +} + +// UpdateDataset updates a dataset. +func (c *Client) UpdateDataset(ctx context.Context, req *automlpb.UpdateDatasetRequest, opts ...gax.CallOption) (*automlpb.Dataset, error) { + return c.internalClient.UpdateDataset(ctx, req, opts...) +} + +// DeleteDataset deletes a dataset and all of its contents. +// Returns empty response in the +// response field when it completes, +// and delete_details in the +// metadata field. +func (c *Client) DeleteDataset(ctx context.Context, req *automlpb.DeleteDatasetRequest, opts ...gax.CallOption) (*DeleteDatasetOperation, error) { + return c.internalClient.DeleteDataset(ctx, req, opts...) +} + +// DeleteDatasetOperation returns a new DeleteDatasetOperation from a given name. +// The name must be that of a previously created DeleteDatasetOperation, possibly from a different process. +func (c *Client) DeleteDatasetOperation(name string) *DeleteDatasetOperation { + return c.internalClient.DeleteDatasetOperation(name) +} + +// ImportData imports data into a dataset. +// For Tables this method can only be called on an empty Dataset. +// +// For Tables: +// +// A +// schema_inference_version +// parameter must be explicitly set. +// Returns an empty response in the +// response field when it completes. +func (c *Client) ImportData(ctx context.Context, req *automlpb.ImportDataRequest, opts ...gax.CallOption) (*ImportDataOperation, error) { + return c.internalClient.ImportData(ctx, req, opts...) +} + +// ImportDataOperation returns a new ImportDataOperation from a given name. +// The name must be that of a previously created ImportDataOperation, possibly from a different process. +func (c *Client) ImportDataOperation(name string) *ImportDataOperation { + return c.internalClient.ImportDataOperation(name) +} + +// ExportData exports dataset’s data to the provided output location. +// Returns an empty response in the +// response field when it completes. +func (c *Client) ExportData(ctx context.Context, req *automlpb.ExportDataRequest, opts ...gax.CallOption) (*ExportDataOperation, error) { + return c.internalClient.ExportData(ctx, req, opts...) +} + +// ExportDataOperation returns a new ExportDataOperation from a given name. +// The name must be that of a previously created ExportDataOperation, possibly from a different process. +func (c *Client) ExportDataOperation(name string) *ExportDataOperation { + return c.internalClient.ExportDataOperation(name) +} + +// GetAnnotationSpec gets an annotation spec. +func (c *Client) GetAnnotationSpec(ctx context.Context, req *automlpb.GetAnnotationSpecRequest, opts ...gax.CallOption) (*automlpb.AnnotationSpec, error) { + return c.internalClient.GetAnnotationSpec(ctx, req, opts...) +} + +// CreateModel creates a model. +// Returns a Model in the response +// field when it completes. +// When you create a model, several model evaluations are created for it: +// a global evaluation, and one evaluation for each annotation spec. +func (c *Client) CreateModel(ctx context.Context, req *automlpb.CreateModelRequest, opts ...gax.CallOption) (*CreateModelOperation, error) { + return c.internalClient.CreateModel(ctx, req, opts...) +} + +// CreateModelOperation returns a new CreateModelOperation from a given name. +// The name must be that of a previously created CreateModelOperation, possibly from a different process. +func (c *Client) CreateModelOperation(name string) *CreateModelOperation { + return c.internalClient.CreateModelOperation(name) +} + +// GetModel gets a model. +func (c *Client) GetModel(ctx context.Context, req *automlpb.GetModelRequest, opts ...gax.CallOption) (*automlpb.Model, error) { + return c.internalClient.GetModel(ctx, req, opts...) +} + +// ListModels lists models. +func (c *Client) ListModels(ctx context.Context, req *automlpb.ListModelsRequest, opts ...gax.CallOption) *ModelIterator { + return c.internalClient.ListModels(ctx, req, opts...) +} + +// DeleteModel deletes a model. +// Returns google.protobuf.Empty in the +// response field when it completes, +// and delete_details in the +// metadata field. +func (c *Client) DeleteModel(ctx context.Context, req *automlpb.DeleteModelRequest, opts ...gax.CallOption) (*DeleteModelOperation, error) { + return c.internalClient.DeleteModel(ctx, req, opts...) +} + +// DeleteModelOperation returns a new DeleteModelOperation from a given name. +// The name must be that of a previously created DeleteModelOperation, possibly from a different process. +func (c *Client) DeleteModelOperation(name string) *DeleteModelOperation { + return c.internalClient.DeleteModelOperation(name) +} + +// UpdateModel updates a model. +func (c *Client) UpdateModel(ctx context.Context, req *automlpb.UpdateModelRequest, opts ...gax.CallOption) (*automlpb.Model, error) { + return c.internalClient.UpdateModel(ctx, req, opts...) +} + +// DeployModel deploys a model. If a model is already deployed, deploying it with the +// same parameters has no effect. Deploying with different parametrs +// (as e.g. changing +// +// node_number) +// will reset the deployment state without pausing the model’s availability. +// +// Only applicable for Text Classification, Image Object Detection , Tables, and Image Segmentation; all other domains manage +// deployment automatically. +// +// Returns an empty response in the +// response field when it completes. +func (c *Client) DeployModel(ctx context.Context, req *automlpb.DeployModelRequest, opts ...gax.CallOption) (*DeployModelOperation, error) { + return c.internalClient.DeployModel(ctx, req, opts...) +} + +// DeployModelOperation returns a new DeployModelOperation from a given name. +// The name must be that of a previously created DeployModelOperation, possibly from a different process. +func (c *Client) DeployModelOperation(name string) *DeployModelOperation { + return c.internalClient.DeployModelOperation(name) +} + +// UndeployModel undeploys a model. If the model is not deployed this method has no effect. +// +// Only applicable for Text Classification, Image Object Detection and Tables; +// all other domains manage deployment automatically. +// +// Returns an empty response in the +// response field when it completes. +func (c *Client) UndeployModel(ctx context.Context, req *automlpb.UndeployModelRequest, opts ...gax.CallOption) (*UndeployModelOperation, error) { + return c.internalClient.UndeployModel(ctx, req, opts...) +} + +// UndeployModelOperation returns a new UndeployModelOperation from a given name. +// The name must be that of a previously created UndeployModelOperation, possibly from a different process. +func (c *Client) UndeployModelOperation(name string) *UndeployModelOperation { + return c.internalClient.UndeployModelOperation(name) +} + +// ExportModel exports a trained, “export-able”, model to a user specified Google Cloud +// Storage location. A model is considered export-able if and only if it has +// an export format defined for it in +// ModelExportOutputConfig. +// +// Returns an empty response in the +// response field when it completes. +func (c *Client) ExportModel(ctx context.Context, req *automlpb.ExportModelRequest, opts ...gax.CallOption) (*ExportModelOperation, error) { + return c.internalClient.ExportModel(ctx, req, opts...) +} + +// ExportModelOperation returns a new ExportModelOperation from a given name. +// The name must be that of a previously created ExportModelOperation, possibly from a different process. +func (c *Client) ExportModelOperation(name string) *ExportModelOperation { + return c.internalClient.ExportModelOperation(name) +} + +// GetModelEvaluation gets a model evaluation. +func (c *Client) GetModelEvaluation(ctx context.Context, req *automlpb.GetModelEvaluationRequest, opts ...gax.CallOption) (*automlpb.ModelEvaluation, error) { + return c.internalClient.GetModelEvaluation(ctx, req, opts...) +} + +// ListModelEvaluations lists model evaluations. +func (c *Client) ListModelEvaluations(ctx context.Context, req *automlpb.ListModelEvaluationsRequest, opts ...gax.CallOption) *ModelEvaluationIterator { + return c.internalClient.ListModelEvaluations(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud AutoML API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client automlpb.AutoMlClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new auto ml client. +// NewClient creates a new auto ml client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // AutoML Server API. // @@ -238,8 +515,7 @@ type Client struct { // On any input that is documented to expect a string parameter in // snake_case or kebab-case, either of those cases is accepted. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -257,16 +533,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: automlpb.NewAutoMlClient(connPool), + client: automlpb.NewAutoMlClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -276,33 +555,33 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateDataset creates a dataset. -func (c *Client) CreateDataset(ctx context.Context, req *automlpb.CreateDatasetRequest, opts ...gax.CallOption) (*CreateDatasetOperation, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateDataset(ctx context.Context, req *automlpb.CreateDatasetRequest, opts ...gax.CallOption) (*CreateDatasetOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -310,7 +589,7 @@ func (c *Client) CreateDataset(ctx context.Context, req *automlpb.CreateDatasetR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateDataset[0:len(c.CallOptions.CreateDataset):len(c.CallOptions.CreateDataset)], opts...) + opts = append((*c.CallOptions).CreateDataset[0:len((*c.CallOptions).CreateDataset):len((*c.CallOptions).CreateDataset)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -321,12 +600,11 @@ func (c *Client) CreateDataset(ctx context.Context, req *automlpb.CreateDatasetR return nil, err } return &CreateDatasetOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetDataset gets a dataset. -func (c *Client) GetDataset(ctx context.Context, req *automlpb.GetDatasetRequest, opts ...gax.CallOption) (*automlpb.Dataset, error) { +func (c *gRPCClient) GetDataset(ctx context.Context, req *automlpb.GetDatasetRequest, opts ...gax.CallOption) (*automlpb.Dataset, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -334,7 +612,7 @@ func (c *Client) GetDataset(ctx context.Context, req *automlpb.GetDatasetRequest } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetDataset[0:len(c.CallOptions.GetDataset):len(c.CallOptions.GetDataset)], opts...) + opts = append((*c.CallOptions).GetDataset[0:len((*c.CallOptions).GetDataset):len((*c.CallOptions).GetDataset)], opts...) var resp *automlpb.Dataset err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -347,11 +625,10 @@ func (c *Client) GetDataset(ctx context.Context, req *automlpb.GetDatasetRequest return resp, nil } -// ListDatasets lists datasets in a project. -func (c *Client) ListDatasets(ctx context.Context, req *automlpb.ListDatasetsRequest, opts ...gax.CallOption) *DatasetIterator { +func (c *gRPCClient) ListDatasets(ctx context.Context, req *automlpb.ListDatasetsRequest, opts ...gax.CallOption) *DatasetIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDatasets[0:len(c.CallOptions.ListDatasets):len(c.CallOptions.ListDatasets)], opts...) + opts = append((*c.CallOptions).ListDatasets[0:len((*c.CallOptions).ListDatasets):len((*c.CallOptions).ListDatasets)], opts...) it := &DatasetIterator{} req = proto.Clone(req).(*automlpb.ListDatasetsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*automlpb.Dataset, string, error) { @@ -388,8 +665,7 @@ func (c *Client) ListDatasets(ctx context.Context, req *automlpb.ListDatasetsReq return it } -// UpdateDataset updates a dataset. -func (c *Client) UpdateDataset(ctx context.Context, req *automlpb.UpdateDatasetRequest, opts ...gax.CallOption) (*automlpb.Dataset, error) { +func (c *gRPCClient) UpdateDataset(ctx context.Context, req *automlpb.UpdateDatasetRequest, opts ...gax.CallOption) (*automlpb.Dataset, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -397,7 +673,7 @@ func (c *Client) UpdateDataset(ctx context.Context, req *automlpb.UpdateDatasetR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "dataset.name", url.QueryEscape(req.GetDataset().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateDataset[0:len(c.CallOptions.UpdateDataset):len(c.CallOptions.UpdateDataset)], opts...) + opts = append((*c.CallOptions).UpdateDataset[0:len((*c.CallOptions).UpdateDataset):len((*c.CallOptions).UpdateDataset)], opts...) var resp *automlpb.Dataset err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -410,12 +686,7 @@ func (c *Client) UpdateDataset(ctx context.Context, req *automlpb.UpdateDatasetR return resp, nil } -// DeleteDataset deletes a dataset and all of its contents. -// Returns empty response in the -// response field when it completes, -// and delete_details in the -// metadata field. -func (c *Client) DeleteDataset(ctx context.Context, req *automlpb.DeleteDatasetRequest, opts ...gax.CallOption) (*DeleteDatasetOperation, error) { +func (c *gRPCClient) DeleteDataset(ctx context.Context, req *automlpb.DeleteDatasetRequest, opts ...gax.CallOption) (*DeleteDatasetOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -423,7 +694,7 @@ func (c *Client) DeleteDataset(ctx context.Context, req *automlpb.DeleteDatasetR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteDataset[0:len(c.CallOptions.DeleteDataset):len(c.CallOptions.DeleteDataset)], opts...) + opts = append((*c.CallOptions).DeleteDataset[0:len((*c.CallOptions).DeleteDataset):len((*c.CallOptions).DeleteDataset)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -434,21 +705,11 @@ func (c *Client) DeleteDataset(ctx context.Context, req *automlpb.DeleteDatasetR return nil, err } return &DeleteDatasetOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ImportData imports data into a dataset. -// For Tables this method can only be called on an empty Dataset. -// -// For Tables: -// -// A -// schema_inference_version -// parameter must be explicitly set. -// Returns an empty response in the -// response field when it completes. -func (c *Client) ImportData(ctx context.Context, req *automlpb.ImportDataRequest, opts ...gax.CallOption) (*ImportDataOperation, error) { +func (c *gRPCClient) ImportData(ctx context.Context, req *automlpb.ImportDataRequest, opts ...gax.CallOption) (*ImportDataOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -456,7 +717,7 @@ func (c *Client) ImportData(ctx context.Context, req *automlpb.ImportDataRequest } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportData[0:len(c.CallOptions.ImportData):len(c.CallOptions.ImportData)], opts...) + opts = append((*c.CallOptions).ImportData[0:len((*c.CallOptions).ImportData):len((*c.CallOptions).ImportData)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -467,14 +728,11 @@ func (c *Client) ImportData(ctx context.Context, req *automlpb.ImportDataRequest return nil, err } return &ImportDataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ExportData exports dataset’s data to the provided output location. -// Returns an empty response in the -// response field when it completes. -func (c *Client) ExportData(ctx context.Context, req *automlpb.ExportDataRequest, opts ...gax.CallOption) (*ExportDataOperation, error) { +func (c *gRPCClient) ExportData(ctx context.Context, req *automlpb.ExportDataRequest, opts ...gax.CallOption) (*ExportDataOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -482,7 +740,7 @@ func (c *Client) ExportData(ctx context.Context, req *automlpb.ExportDataRequest } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportData[0:len(c.CallOptions.ExportData):len(c.CallOptions.ExportData)], opts...) + opts = append((*c.CallOptions).ExportData[0:len((*c.CallOptions).ExportData):len((*c.CallOptions).ExportData)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -493,12 +751,11 @@ func (c *Client) ExportData(ctx context.Context, req *automlpb.ExportDataRequest return nil, err } return &ExportDataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetAnnotationSpec gets an annotation spec. -func (c *Client) GetAnnotationSpec(ctx context.Context, req *automlpb.GetAnnotationSpecRequest, opts ...gax.CallOption) (*automlpb.AnnotationSpec, error) { +func (c *gRPCClient) GetAnnotationSpec(ctx context.Context, req *automlpb.GetAnnotationSpecRequest, opts ...gax.CallOption) (*automlpb.AnnotationSpec, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -506,7 +763,7 @@ func (c *Client) GetAnnotationSpec(ctx context.Context, req *automlpb.GetAnnotat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetAnnotationSpec[0:len(c.CallOptions.GetAnnotationSpec):len(c.CallOptions.GetAnnotationSpec)], opts...) + opts = append((*c.CallOptions).GetAnnotationSpec[0:len((*c.CallOptions).GetAnnotationSpec):len((*c.CallOptions).GetAnnotationSpec)], opts...) var resp *automlpb.AnnotationSpec err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -519,12 +776,7 @@ func (c *Client) GetAnnotationSpec(ctx context.Context, req *automlpb.GetAnnotat return resp, nil } -// CreateModel creates a model. -// Returns a Model in the response -// field when it completes. -// When you create a model, several model evaluations are created for it: -// a global evaluation, and one evaluation for each annotation spec. -func (c *Client) CreateModel(ctx context.Context, req *automlpb.CreateModelRequest, opts ...gax.CallOption) (*CreateModelOperation, error) { +func (c *gRPCClient) CreateModel(ctx context.Context, req *automlpb.CreateModelRequest, opts ...gax.CallOption) (*CreateModelOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -532,7 +784,7 @@ func (c *Client) CreateModel(ctx context.Context, req *automlpb.CreateModelReque } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateModel[0:len(c.CallOptions.CreateModel):len(c.CallOptions.CreateModel)], opts...) + opts = append((*c.CallOptions).CreateModel[0:len((*c.CallOptions).CreateModel):len((*c.CallOptions).CreateModel)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -543,12 +795,11 @@ func (c *Client) CreateModel(ctx context.Context, req *automlpb.CreateModelReque return nil, err } return &CreateModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetModel gets a model. -func (c *Client) GetModel(ctx context.Context, req *automlpb.GetModelRequest, opts ...gax.CallOption) (*automlpb.Model, error) { +func (c *gRPCClient) GetModel(ctx context.Context, req *automlpb.GetModelRequest, opts ...gax.CallOption) (*automlpb.Model, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -556,7 +807,7 @@ func (c *Client) GetModel(ctx context.Context, req *automlpb.GetModelRequest, op } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetModel[0:len(c.CallOptions.GetModel):len(c.CallOptions.GetModel)], opts...) + opts = append((*c.CallOptions).GetModel[0:len((*c.CallOptions).GetModel):len((*c.CallOptions).GetModel)], opts...) var resp *automlpb.Model err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -569,11 +820,10 @@ func (c *Client) GetModel(ctx context.Context, req *automlpb.GetModelRequest, op return resp, nil } -// ListModels lists models. -func (c *Client) ListModels(ctx context.Context, req *automlpb.ListModelsRequest, opts ...gax.CallOption) *ModelIterator { +func (c *gRPCClient) ListModels(ctx context.Context, req *automlpb.ListModelsRequest, opts ...gax.CallOption) *ModelIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListModels[0:len(c.CallOptions.ListModels):len(c.CallOptions.ListModels)], opts...) + opts = append((*c.CallOptions).ListModels[0:len((*c.CallOptions).ListModels):len((*c.CallOptions).ListModels)], opts...) it := &ModelIterator{} req = proto.Clone(req).(*automlpb.ListModelsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*automlpb.Model, string, error) { @@ -610,12 +860,7 @@ func (c *Client) ListModels(ctx context.Context, req *automlpb.ListModelsRequest return it } -// DeleteModel deletes a model. -// Returns google.protobuf.Empty in the -// response field when it completes, -// and delete_details in the -// metadata field. -func (c *Client) DeleteModel(ctx context.Context, req *automlpb.DeleteModelRequest, opts ...gax.CallOption) (*DeleteModelOperation, error) { +func (c *gRPCClient) DeleteModel(ctx context.Context, req *automlpb.DeleteModelRequest, opts ...gax.CallOption) (*DeleteModelOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -623,7 +868,7 @@ func (c *Client) DeleteModel(ctx context.Context, req *automlpb.DeleteModelReque } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteModel[0:len(c.CallOptions.DeleteModel):len(c.CallOptions.DeleteModel)], opts...) + opts = append((*c.CallOptions).DeleteModel[0:len((*c.CallOptions).DeleteModel):len((*c.CallOptions).DeleteModel)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -634,12 +879,11 @@ func (c *Client) DeleteModel(ctx context.Context, req *automlpb.DeleteModelReque return nil, err } return &DeleteModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateModel updates a model. -func (c *Client) UpdateModel(ctx context.Context, req *automlpb.UpdateModelRequest, opts ...gax.CallOption) (*automlpb.Model, error) { +func (c *gRPCClient) UpdateModel(ctx context.Context, req *automlpb.UpdateModelRequest, opts ...gax.CallOption) (*automlpb.Model, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -647,7 +891,7 @@ func (c *Client) UpdateModel(ctx context.Context, req *automlpb.UpdateModelReque } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "model.name", url.QueryEscape(req.GetModel().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateModel[0:len(c.CallOptions.UpdateModel):len(c.CallOptions.UpdateModel)], opts...) + opts = append((*c.CallOptions).UpdateModel[0:len((*c.CallOptions).UpdateModel):len((*c.CallOptions).UpdateModel)], opts...) var resp *automlpb.Model err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -660,19 +904,7 @@ func (c *Client) UpdateModel(ctx context.Context, req *automlpb.UpdateModelReque return resp, nil } -// DeployModel deploys a model. If a model is already deployed, deploying it with the -// same parameters has no effect. Deploying with different parametrs -// (as e.g. changing -// -// node_number) -// will reset the deployment state without pausing the model’s availability. -// -// Only applicable for Text Classification, Image Object Detection , Tables, and Image Segmentation; all other domains manage -// deployment automatically. -// -// Returns an empty response in the -// response field when it completes. -func (c *Client) DeployModel(ctx context.Context, req *automlpb.DeployModelRequest, opts ...gax.CallOption) (*DeployModelOperation, error) { +func (c *gRPCClient) DeployModel(ctx context.Context, req *automlpb.DeployModelRequest, opts ...gax.CallOption) (*DeployModelOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -680,7 +912,7 @@ func (c *Client) DeployModel(ctx context.Context, req *automlpb.DeployModelReque } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeployModel[0:len(c.CallOptions.DeployModel):len(c.CallOptions.DeployModel)], opts...) + opts = append((*c.CallOptions).DeployModel[0:len((*c.CallOptions).DeployModel):len((*c.CallOptions).DeployModel)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -691,18 +923,11 @@ func (c *Client) DeployModel(ctx context.Context, req *automlpb.DeployModelReque return nil, err } return &DeployModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UndeployModel undeploys a model. If the model is not deployed this method has no effect. -// -// Only applicable for Text Classification, Image Object Detection and Tables; -// all other domains manage deployment automatically. -// -// Returns an empty response in the -// response field when it completes. -func (c *Client) UndeployModel(ctx context.Context, req *automlpb.UndeployModelRequest, opts ...gax.CallOption) (*UndeployModelOperation, error) { +func (c *gRPCClient) UndeployModel(ctx context.Context, req *automlpb.UndeployModelRequest, opts ...gax.CallOption) (*UndeployModelOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -710,7 +935,7 @@ func (c *Client) UndeployModel(ctx context.Context, req *automlpb.UndeployModelR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UndeployModel[0:len(c.CallOptions.UndeployModel):len(c.CallOptions.UndeployModel)], opts...) + opts = append((*c.CallOptions).UndeployModel[0:len((*c.CallOptions).UndeployModel):len((*c.CallOptions).UndeployModel)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -721,18 +946,11 @@ func (c *Client) UndeployModel(ctx context.Context, req *automlpb.UndeployModelR return nil, err } return &UndeployModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ExportModel exports a trained, “export-able”, model to a user specified Google Cloud -// Storage location. A model is considered export-able if and only if it has -// an export format defined for it in -// ModelExportOutputConfig. -// -// Returns an empty response in the -// response field when it completes. -func (c *Client) ExportModel(ctx context.Context, req *automlpb.ExportModelRequest, opts ...gax.CallOption) (*ExportModelOperation, error) { +func (c *gRPCClient) ExportModel(ctx context.Context, req *automlpb.ExportModelRequest, opts ...gax.CallOption) (*ExportModelOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -740,7 +958,7 @@ func (c *Client) ExportModel(ctx context.Context, req *automlpb.ExportModelReque } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportModel[0:len(c.CallOptions.ExportModel):len(c.CallOptions.ExportModel)], opts...) + opts = append((*c.CallOptions).ExportModel[0:len((*c.CallOptions).ExportModel):len((*c.CallOptions).ExportModel)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -751,12 +969,11 @@ func (c *Client) ExportModel(ctx context.Context, req *automlpb.ExportModelReque return nil, err } return &ExportModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetModelEvaluation gets a model evaluation. -func (c *Client) GetModelEvaluation(ctx context.Context, req *automlpb.GetModelEvaluationRequest, opts ...gax.CallOption) (*automlpb.ModelEvaluation, error) { +func (c *gRPCClient) GetModelEvaluation(ctx context.Context, req *automlpb.GetModelEvaluationRequest, opts ...gax.CallOption) (*automlpb.ModelEvaluation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -764,7 +981,7 @@ func (c *Client) GetModelEvaluation(ctx context.Context, req *automlpb.GetModelE } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetModelEvaluation[0:len(c.CallOptions.GetModelEvaluation):len(c.CallOptions.GetModelEvaluation)], opts...) + opts = append((*c.CallOptions).GetModelEvaluation[0:len((*c.CallOptions).GetModelEvaluation):len((*c.CallOptions).GetModelEvaluation)], opts...) var resp *automlpb.ModelEvaluation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -777,11 +994,10 @@ func (c *Client) GetModelEvaluation(ctx context.Context, req *automlpb.GetModelE return resp, nil } -// ListModelEvaluations lists model evaluations. -func (c *Client) ListModelEvaluations(ctx context.Context, req *automlpb.ListModelEvaluationsRequest, opts ...gax.CallOption) *ModelEvaluationIterator { +func (c *gRPCClient) ListModelEvaluations(ctx context.Context, req *automlpb.ListModelEvaluationsRequest, opts ...gax.CallOption) *ModelEvaluationIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListModelEvaluations[0:len(c.CallOptions.ListModelEvaluations):len(c.CallOptions.ListModelEvaluations)], opts...) + opts = append((*c.CallOptions).ListModelEvaluations[0:len((*c.CallOptions).ListModelEvaluations):len((*c.CallOptions).ListModelEvaluations)], opts...) it := &ModelEvaluationIterator{} req = proto.Clone(req).(*automlpb.ListModelEvaluationsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*automlpb.ModelEvaluation, string, error) { @@ -825,9 +1041,9 @@ type CreateDatasetOperation struct { // CreateDatasetOperation returns a new CreateDatasetOperation from a given name. // The name must be that of a previously created CreateDatasetOperation, possibly from a different process. -func (c *Client) CreateDatasetOperation(name string) *CreateDatasetOperation { +func (c *gRPCClient) CreateDatasetOperation(name string) *CreateDatasetOperation { return &CreateDatasetOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -894,9 +1110,9 @@ type CreateModelOperation struct { // CreateModelOperation returns a new CreateModelOperation from a given name. // The name must be that of a previously created CreateModelOperation, possibly from a different process. -func (c *Client) CreateModelOperation(name string) *CreateModelOperation { +func (c *gRPCClient) CreateModelOperation(name string) *CreateModelOperation { return &CreateModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -963,9 +1179,9 @@ type DeleteDatasetOperation struct { // DeleteDatasetOperation returns a new DeleteDatasetOperation from a given name. // The name must be that of a previously created DeleteDatasetOperation, possibly from a different process. -func (c *Client) DeleteDatasetOperation(name string) *DeleteDatasetOperation { +func (c *gRPCClient) DeleteDatasetOperation(name string) *DeleteDatasetOperation { return &DeleteDatasetOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1021,9 +1237,9 @@ type DeleteModelOperation struct { // DeleteModelOperation returns a new DeleteModelOperation from a given name. // The name must be that of a previously created DeleteModelOperation, possibly from a different process. -func (c *Client) DeleteModelOperation(name string) *DeleteModelOperation { +func (c *gRPCClient) DeleteModelOperation(name string) *DeleteModelOperation { return &DeleteModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1079,9 +1295,9 @@ type DeployModelOperation struct { // DeployModelOperation returns a new DeployModelOperation from a given name. // The name must be that of a previously created DeployModelOperation, possibly from a different process. -func (c *Client) DeployModelOperation(name string) *DeployModelOperation { +func (c *gRPCClient) DeployModelOperation(name string) *DeployModelOperation { return &DeployModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1137,9 +1353,9 @@ type ExportDataOperation struct { // ExportDataOperation returns a new ExportDataOperation from a given name. // The name must be that of a previously created ExportDataOperation, possibly from a different process. -func (c *Client) ExportDataOperation(name string) *ExportDataOperation { +func (c *gRPCClient) ExportDataOperation(name string) *ExportDataOperation { return &ExportDataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1195,9 +1411,9 @@ type ExportModelOperation struct { // ExportModelOperation returns a new ExportModelOperation from a given name. // The name must be that of a previously created ExportModelOperation, possibly from a different process. -func (c *Client) ExportModelOperation(name string) *ExportModelOperation { +func (c *gRPCClient) ExportModelOperation(name string) *ExportModelOperation { return &ExportModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1253,9 +1469,9 @@ type ImportDataOperation struct { // ImportDataOperation returns a new ImportDataOperation from a given name. // The name must be that of a previously created ImportDataOperation, possibly from a different process. -func (c *Client) ImportDataOperation(name string) *ImportDataOperation { +func (c *gRPCClient) ImportDataOperation(name string) *ImportDataOperation { return &ImportDataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1311,9 +1527,9 @@ type UndeployModelOperation struct { // UndeployModelOperation returns a new UndeployModelOperation from a given name. // The name must be that of a previously created UndeployModelOperation, possibly from a different process. -func (c *Client) UndeployModelOperation(name string) *UndeployModelOperation { +func (c *gRPCClient) UndeployModelOperation(name string) *UndeployModelOperation { return &UndeployModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/automl/apiv1/auto_ml_client_example_test.go b/automl/apiv1/auto_ml_client_example_test.go index 90baeb2498ab..ceacc4c5fb86 100644 --- a/automl/apiv1/auto_ml_client_example_test.go +++ b/automl/apiv1/auto_ml_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateDataset() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.CreateDatasetRequest{ // TODO: Fill request struct fields. @@ -60,13 +61,12 @@ func ExampleClient_CreateDataset() { } func ExampleClient_GetDataset() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetDatasetRequest{ // TODO: Fill request struct fields. @@ -80,14 +80,12 @@ func ExampleClient_GetDataset() { } func ExampleClient_ListDatasets() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ListDatasetsRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleClient_ListDatasets() { } func ExampleClient_UpdateDataset() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.UpdateDatasetRequest{ // TODO: Fill request struct fields. @@ -127,13 +124,12 @@ func ExampleClient_UpdateDataset() { } func ExampleClient_DeleteDataset() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.DeleteDatasetRequest{ // TODO: Fill request struct fields. @@ -150,13 +146,12 @@ func ExampleClient_DeleteDataset() { } func ExampleClient_ImportData() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ImportDataRequest{ // TODO: Fill request struct fields. @@ -173,13 +168,12 @@ func ExampleClient_ImportData() { } func ExampleClient_ExportData() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ExportDataRequest{ // TODO: Fill request struct fields. @@ -196,13 +190,12 @@ func ExampleClient_ExportData() { } func ExampleClient_GetAnnotationSpec() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetAnnotationSpecRequest{ // TODO: Fill request struct fields. @@ -216,13 +209,12 @@ func ExampleClient_GetAnnotationSpec() { } func ExampleClient_CreateModel() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.CreateModelRequest{ // TODO: Fill request struct fields. @@ -241,13 +233,12 @@ func ExampleClient_CreateModel() { } func ExampleClient_GetModel() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetModelRequest{ // TODO: Fill request struct fields. @@ -261,14 +252,12 @@ func ExampleClient_GetModel() { } func ExampleClient_ListModels() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ListModelsRequest{ // TODO: Fill request struct fields. @@ -288,13 +277,12 @@ func ExampleClient_ListModels() { } func ExampleClient_DeleteModel() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.DeleteModelRequest{ // TODO: Fill request struct fields. @@ -311,13 +299,12 @@ func ExampleClient_DeleteModel() { } func ExampleClient_UpdateModel() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.UpdateModelRequest{ // TODO: Fill request struct fields. @@ -331,13 +318,12 @@ func ExampleClient_UpdateModel() { } func ExampleClient_DeployModel() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.DeployModelRequest{ // TODO: Fill request struct fields. @@ -354,13 +340,12 @@ func ExampleClient_DeployModel() { } func ExampleClient_UndeployModel() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.UndeployModelRequest{ // TODO: Fill request struct fields. @@ -377,13 +362,12 @@ func ExampleClient_UndeployModel() { } func ExampleClient_ExportModel() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ExportModelRequest{ // TODO: Fill request struct fields. @@ -400,13 +384,12 @@ func ExampleClient_ExportModel() { } func ExampleClient_GetModelEvaluation() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetModelEvaluationRequest{ // TODO: Fill request struct fields. @@ -420,14 +403,12 @@ func ExampleClient_GetModelEvaluation() { } func ExampleClient_ListModelEvaluations() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ListModelEvaluationsRequest{ // TODO: Fill request struct fields. diff --git a/automl/apiv1/doc.go b/automl/apiv1/doc.go index 67c1b48f5ee6..8856bb5672c7 100644 --- a/automl/apiv1/doc.go +++ b/automl/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package automl // import "cloud.google.com/go/automl/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/automl/apiv1/prediction_client.go b/automl/apiv1/prediction_client.go index 7fa2878ef4b8..dacb5b75e729 100644 --- a/automl/apiv1/prediction_client.go +++ b/automl/apiv1/prediction_client.go @@ -43,7 +43,7 @@ type PredictionCallOptions struct { BatchPredict []gax.CallOption } -func defaultPredictionClientOptions() []option.ClientOption { +func defaultPredictionGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("automl.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("automl.mtls.googleapis.com:443"), @@ -62,40 +62,163 @@ func defaultPredictionCallOptions() *PredictionCallOptions { } } +// internalPredictionClient is an interface that defines the methods availaible from Cloud AutoML API. +type internalPredictionClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + Predict(context.Context, *automlpb.PredictRequest, ...gax.CallOption) (*automlpb.PredictResponse, error) + BatchPredict(context.Context, *automlpb.BatchPredictRequest, ...gax.CallOption) (*BatchPredictOperation, error) + BatchPredictOperation(name string) *BatchPredictOperation +} + // PredictionClient is a client for interacting with Cloud AutoML API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// AutoML Prediction API. +// +// On any input that is documented to expect a string parameter in +// snake_case or kebab-case, either of those cases is accepted. type PredictionClient struct { + // The internal transport-dependent client. + internalClient internalPredictionClient + + // The call options for this service. + CallOptions *PredictionCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *PredictionClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *PredictionClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *PredictionClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// Predict perform an online prediction. The prediction result is directly +// returned in the response. +// Available for following ML scenarios, and their expected request payloads: +// +// AutoML Vision Classification +// +// An image in .JPEG, .GIF or .PNG format, image_bytes up to 30MB. +// +// AutoML Vision Object Detection +// +// An image in .JPEG, .GIF or .PNG format, image_bytes up to 30MB. +// +// AutoML Natural Language Classification +// +// A TextSnippet up to 60,000 characters, UTF-8 encoded or a document in +// .PDF, .TIF or .TIFF format with size upto 2MB. +// +// AutoML Natural Language Entity Extraction +// +// A TextSnippet up to 10,000 characters, UTF-8 NFC encoded or a document +// in .PDF, .TIF or .TIFF format with size upto 20MB. +// +// AutoML Natural Language Sentiment Analysis +// +// A TextSnippet up to 60,000 characters, UTF-8 encoded or a document in +// .PDF, .TIF or .TIFF format with size upto 2MB. +// +// AutoML Translation +// +// A TextSnippet up to 25,000 characters, UTF-8 encoded. +// +// AutoML Tables +// +// A row with column values matching +// the columns of the model, up to 5MB. Not available for FORECASTING +// prediction_type. +func (c *PredictionClient) Predict(ctx context.Context, req *automlpb.PredictRequest, opts ...gax.CallOption) (*automlpb.PredictResponse, error) { + return c.internalClient.Predict(ctx, req, opts...) +} + +// BatchPredict perform a batch prediction. Unlike the online Predict, batch +// prediction result won’t be immediately available in the response. Instead, +// a long running operation object is returned. User can poll the operation +// result via GetOperation +// method. Once the operation is done, BatchPredictResult is returned in +// the response field. +// Available for following ML scenarios: +// +// AutoML Vision Classification +// +// AutoML Vision Object Detection +// +// AutoML Video Intelligence Classification +// +// AutoML Video Intelligence Object Tracking * AutoML Natural Language Classification +// +// AutoML Natural Language Entity Extraction +// +// AutoML Natural Language Sentiment Analysis +// +// AutoML Tables +func (c *PredictionClient) BatchPredict(ctx context.Context, req *automlpb.BatchPredictRequest, opts ...gax.CallOption) (*BatchPredictOperation, error) { + return c.internalClient.BatchPredict(ctx, req, opts...) +} + +// BatchPredictOperation returns a new BatchPredictOperation from a given name. +// The name must be that of a previously created BatchPredictOperation, possibly from a different process. +func (c *PredictionClient) BatchPredictOperation(name string) *BatchPredictOperation { + return c.internalClient.BatchPredictOperation(name) +} + +// predictionGRPCClient is a client for interacting with Cloud AutoML API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type predictionGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing PredictionClient + CallOptions **PredictionCallOptions + // The gRPC API client. predictionClient automlpb.PredictionServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *PredictionCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewPredictionClient creates a new prediction service client. +// NewPredictionClient creates a new prediction service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // AutoML Prediction API. // // On any input that is documented to expect a string parameter in // snake_case or kebab-case, either of those cases is accepted. func NewPredictionClient(ctx context.Context, opts ...option.ClientOption) (*PredictionClient, error) { - clientOpts := defaultPredictionClientOptions() - + clientOpts := defaultPredictionGRPCClientOptions() if newPredictionClientHook != nil { hookOpts, err := newPredictionClientHook(ctx, clientHookParams{}) if err != nil { @@ -113,16 +236,19 @@ func NewPredictionClient(ctx context.Context, opts ...option.ClientOption) (*Pre if err != nil { return nil, err } - c := &PredictionClient{ + client := PredictionClient{CallOptions: defaultPredictionCallOptions()} + + c := &predictionGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultPredictionCallOptions(), - predictionClient: automlpb.NewPredictionServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -132,68 +258,33 @@ func NewPredictionClient(ctx context.Context, opts ...option.ClientOption) (*Pre // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *PredictionClient) Connection() *grpc.ClientConn { +func (c *predictionGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *PredictionClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *PredictionClient) setGoogleClientInfo(keyval ...string) { +func (c *predictionGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// Predict perform an online prediction. The prediction result is directly -// returned in the response. -// Available for following ML scenarios, and their expected request payloads: -// -// AutoML Vision Classification -// -// An image in .JPEG, .GIF or .PNG format, image_bytes up to 30MB. -// -// AutoML Vision Object Detection -// -// An image in .JPEG, .GIF or .PNG format, image_bytes up to 30MB. -// -// AutoML Natural Language Classification -// -// A TextSnippet up to 60,000 characters, UTF-8 encoded or a document in -// .PDF, .TIF or .TIFF format with size upto 2MB. -// -// AutoML Natural Language Entity Extraction -// -// A TextSnippet up to 10,000 characters, UTF-8 NFC encoded or a document -// in .PDF, .TIF or .TIFF format with size upto 20MB. -// -// AutoML Natural Language Sentiment Analysis -// -// A TextSnippet up to 60,000 characters, UTF-8 encoded or a document in -// .PDF, .TIF or .TIFF format with size upto 2MB. -// -// AutoML Translation -// -// A TextSnippet up to 25,000 characters, UTF-8 encoded. -// -// AutoML Tables -// -// A row with column values matching -// the columns of the model, up to 5MB. Not available for FORECASTING -// prediction_type. -func (c *PredictionClient) Predict(ctx context.Context, req *automlpb.PredictRequest, opts ...gax.CallOption) (*automlpb.PredictResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *predictionGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *predictionGRPCClient) Predict(ctx context.Context, req *automlpb.PredictRequest, opts ...gax.CallOption) (*automlpb.PredictResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -201,7 +292,7 @@ func (c *PredictionClient) Predict(ctx context.Context, req *automlpb.PredictReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.Predict[0:len(c.CallOptions.Predict):len(c.CallOptions.Predict)], opts...) + opts = append((*c.CallOptions).Predict[0:len((*c.CallOptions).Predict):len((*c.CallOptions).Predict)], opts...) var resp *automlpb.PredictResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -214,28 +305,7 @@ func (c *PredictionClient) Predict(ctx context.Context, req *automlpb.PredictReq return resp, nil } -// BatchPredict perform a batch prediction. Unlike the online Predict, batch -// prediction result won’t be immediately available in the response. Instead, -// a long running operation object is returned. User can poll the operation -// result via GetOperation -// method. Once the operation is done, BatchPredictResult is returned in -// the response field. -// Available for following ML scenarios: -// -// AutoML Vision Classification -// -// AutoML Vision Object Detection -// -// AutoML Video Intelligence Classification -// -// AutoML Video Intelligence Object Tracking * AutoML Natural Language Classification -// -// AutoML Natural Language Entity Extraction -// -// AutoML Natural Language Sentiment Analysis -// -// AutoML Tables -func (c *PredictionClient) BatchPredict(ctx context.Context, req *automlpb.BatchPredictRequest, opts ...gax.CallOption) (*BatchPredictOperation, error) { +func (c *predictionGRPCClient) BatchPredict(ctx context.Context, req *automlpb.BatchPredictRequest, opts ...gax.CallOption) (*BatchPredictOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -243,7 +313,7 @@ func (c *PredictionClient) BatchPredict(ctx context.Context, req *automlpb.Batch } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchPredict[0:len(c.CallOptions.BatchPredict):len(c.CallOptions.BatchPredict)], opts...) + opts = append((*c.CallOptions).BatchPredict[0:len((*c.CallOptions).BatchPredict):len((*c.CallOptions).BatchPredict)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -254,7 +324,7 @@ func (c *PredictionClient) BatchPredict(ctx context.Context, req *automlpb.Batch return nil, err } return &BatchPredictOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -265,9 +335,9 @@ type BatchPredictOperation struct { // BatchPredictOperation returns a new BatchPredictOperation from a given name. // The name must be that of a previously created BatchPredictOperation, possibly from a different process. -func (c *PredictionClient) BatchPredictOperation(name string) *BatchPredictOperation { +func (c *predictionGRPCClient) BatchPredictOperation(name string) *BatchPredictOperation { return &BatchPredictOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/automl/apiv1/prediction_client_example_test.go b/automl/apiv1/prediction_client_example_test.go index e25be4bb0f6a..76daa231b1ac 100644 --- a/automl/apiv1/prediction_client_example_test.go +++ b/automl/apiv1/prediction_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewPredictionClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExamplePredictionClient_Predict() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewPredictionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.PredictRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExamplePredictionClient_Predict() { } func ExamplePredictionClient_BatchPredict() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewPredictionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.BatchPredictRequest{ // TODO: Fill request struct fields. diff --git a/automl/apiv1beta1/auto_ml_client.go b/automl/apiv1beta1/auto_ml_client.go index ca9ba28465b0..ee18ad797ca3 100644 --- a/automl/apiv1beta1/auto_ml_client.go +++ b/automl/apiv1beta1/auto_ml_client.go @@ -68,7 +68,7 @@ type CallOptions struct { ListModelEvaluations []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("automl.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("automl.mtls.googleapis.com:443"), @@ -241,32 +241,359 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud AutoML API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateDataset(context.Context, *automlpb.CreateDatasetRequest, ...gax.CallOption) (*automlpb.Dataset, error) + GetDataset(context.Context, *automlpb.GetDatasetRequest, ...gax.CallOption) (*automlpb.Dataset, error) + ListDatasets(context.Context, *automlpb.ListDatasetsRequest, ...gax.CallOption) *DatasetIterator + UpdateDataset(context.Context, *automlpb.UpdateDatasetRequest, ...gax.CallOption) (*automlpb.Dataset, error) + DeleteDataset(context.Context, *automlpb.DeleteDatasetRequest, ...gax.CallOption) (*DeleteDatasetOperation, error) + DeleteDatasetOperation(name string) *DeleteDatasetOperation + ImportData(context.Context, *automlpb.ImportDataRequest, ...gax.CallOption) (*ImportDataOperation, error) + ImportDataOperation(name string) *ImportDataOperation + ExportData(context.Context, *automlpb.ExportDataRequest, ...gax.CallOption) (*ExportDataOperation, error) + ExportDataOperation(name string) *ExportDataOperation + GetAnnotationSpec(context.Context, *automlpb.GetAnnotationSpecRequest, ...gax.CallOption) (*automlpb.AnnotationSpec, error) + GetTableSpec(context.Context, *automlpb.GetTableSpecRequest, ...gax.CallOption) (*automlpb.TableSpec, error) + ListTableSpecs(context.Context, *automlpb.ListTableSpecsRequest, ...gax.CallOption) *TableSpecIterator + UpdateTableSpec(context.Context, *automlpb.UpdateTableSpecRequest, ...gax.CallOption) (*automlpb.TableSpec, error) + GetColumnSpec(context.Context, *automlpb.GetColumnSpecRequest, ...gax.CallOption) (*automlpb.ColumnSpec, error) + ListColumnSpecs(context.Context, *automlpb.ListColumnSpecsRequest, ...gax.CallOption) *ColumnSpecIterator + UpdateColumnSpec(context.Context, *automlpb.UpdateColumnSpecRequest, ...gax.CallOption) (*automlpb.ColumnSpec, error) + CreateModel(context.Context, *automlpb.CreateModelRequest, ...gax.CallOption) (*CreateModelOperation, error) + CreateModelOperation(name string) *CreateModelOperation + GetModel(context.Context, *automlpb.GetModelRequest, ...gax.CallOption) (*automlpb.Model, error) + ListModels(context.Context, *automlpb.ListModelsRequest, ...gax.CallOption) *ModelIterator + DeleteModel(context.Context, *automlpb.DeleteModelRequest, ...gax.CallOption) (*DeleteModelOperation, error) + DeleteModelOperation(name string) *DeleteModelOperation + DeployModel(context.Context, *automlpb.DeployModelRequest, ...gax.CallOption) (*DeployModelOperation, error) + DeployModelOperation(name string) *DeployModelOperation + UndeployModel(context.Context, *automlpb.UndeployModelRequest, ...gax.CallOption) (*UndeployModelOperation, error) + UndeployModelOperation(name string) *UndeployModelOperation + ExportModel(context.Context, *automlpb.ExportModelRequest, ...gax.CallOption) (*ExportModelOperation, error) + ExportModelOperation(name string) *ExportModelOperation + ExportEvaluatedExamples(context.Context, *automlpb.ExportEvaluatedExamplesRequest, ...gax.CallOption) (*ExportEvaluatedExamplesOperation, error) + ExportEvaluatedExamplesOperation(name string) *ExportEvaluatedExamplesOperation + GetModelEvaluation(context.Context, *automlpb.GetModelEvaluationRequest, ...gax.CallOption) (*automlpb.ModelEvaluation, error) + ListModelEvaluations(context.Context, *automlpb.ListModelEvaluationsRequest, ...gax.CallOption) *ModelEvaluationIterator +} + // Client is a client for interacting with Cloud AutoML API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// AutoML Server API. +// +// The resource names are assigned by the server. +// The server never reuses names that it has created after the resources with +// those names are deleted. +// +// An ID of a resource is the last element of the item’s resource name. For +// projects/{project_id}/locations/{location_id}/datasets/{dataset_id}, then +// the id for the item is {dataset_id}. +// +// Currently the only supported location_id is “us-central1”. +// +// On any input that is documented to expect a string parameter in +// snake_case or kebab-case, either of those cases is accepted. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateDataset creates a dataset. +func (c *Client) CreateDataset(ctx context.Context, req *automlpb.CreateDatasetRequest, opts ...gax.CallOption) (*automlpb.Dataset, error) { + return c.internalClient.CreateDataset(ctx, req, opts...) +} + +// GetDataset gets a dataset. +func (c *Client) GetDataset(ctx context.Context, req *automlpb.GetDatasetRequest, opts ...gax.CallOption) (*automlpb.Dataset, error) { + return c.internalClient.GetDataset(ctx, req, opts...) +} + +// ListDatasets lists datasets in a project. +func (c *Client) ListDatasets(ctx context.Context, req *automlpb.ListDatasetsRequest, opts ...gax.CallOption) *DatasetIterator { + return c.internalClient.ListDatasets(ctx, req, opts...) +} + +// UpdateDataset updates a dataset. +func (c *Client) UpdateDataset(ctx context.Context, req *automlpb.UpdateDatasetRequest, opts ...gax.CallOption) (*automlpb.Dataset, error) { + return c.internalClient.UpdateDataset(ctx, req, opts...) +} + +// DeleteDataset deletes a dataset and all of its contents. +// Returns empty response in the +// response field when it completes, +// and delete_details in the +// metadata field. +func (c *Client) DeleteDataset(ctx context.Context, req *automlpb.DeleteDatasetRequest, opts ...gax.CallOption) (*DeleteDatasetOperation, error) { + return c.internalClient.DeleteDataset(ctx, req, opts...) +} + +// DeleteDatasetOperation returns a new DeleteDatasetOperation from a given name. +// The name must be that of a previously created DeleteDatasetOperation, possibly from a different process. +func (c *Client) DeleteDatasetOperation(name string) *DeleteDatasetOperation { + return c.internalClient.DeleteDatasetOperation(name) +} + +// ImportData imports data into a dataset. +// For Tables this method can only be called on an empty Dataset. +// +// For Tables: +// +// A +// schema_inference_version +// parameter must be explicitly set. +// Returns an empty response in the +// response field when it completes. +func (c *Client) ImportData(ctx context.Context, req *automlpb.ImportDataRequest, opts ...gax.CallOption) (*ImportDataOperation, error) { + return c.internalClient.ImportData(ctx, req, opts...) +} + +// ImportDataOperation returns a new ImportDataOperation from a given name. +// The name must be that of a previously created ImportDataOperation, possibly from a different process. +func (c *Client) ImportDataOperation(name string) *ImportDataOperation { + return c.internalClient.ImportDataOperation(name) +} + +// ExportData exports dataset’s data to the provided output location. +// Returns an empty response in the +// response field when it completes. +func (c *Client) ExportData(ctx context.Context, req *automlpb.ExportDataRequest, opts ...gax.CallOption) (*ExportDataOperation, error) { + return c.internalClient.ExportData(ctx, req, opts...) +} + +// ExportDataOperation returns a new ExportDataOperation from a given name. +// The name must be that of a previously created ExportDataOperation, possibly from a different process. +func (c *Client) ExportDataOperation(name string) *ExportDataOperation { + return c.internalClient.ExportDataOperation(name) +} + +// GetAnnotationSpec gets an annotation spec. +func (c *Client) GetAnnotationSpec(ctx context.Context, req *automlpb.GetAnnotationSpecRequest, opts ...gax.CallOption) (*automlpb.AnnotationSpec, error) { + return c.internalClient.GetAnnotationSpec(ctx, req, opts...) +} + +// GetTableSpec gets a table spec. +func (c *Client) GetTableSpec(ctx context.Context, req *automlpb.GetTableSpecRequest, opts ...gax.CallOption) (*automlpb.TableSpec, error) { + return c.internalClient.GetTableSpec(ctx, req, opts...) +} + +// ListTableSpecs lists table specs in a dataset. +func (c *Client) ListTableSpecs(ctx context.Context, req *automlpb.ListTableSpecsRequest, opts ...gax.CallOption) *TableSpecIterator { + return c.internalClient.ListTableSpecs(ctx, req, opts...) +} + +// UpdateTableSpec updates a table spec. +func (c *Client) UpdateTableSpec(ctx context.Context, req *automlpb.UpdateTableSpecRequest, opts ...gax.CallOption) (*automlpb.TableSpec, error) { + return c.internalClient.UpdateTableSpec(ctx, req, opts...) +} + +// GetColumnSpec gets a column spec. +func (c *Client) GetColumnSpec(ctx context.Context, req *automlpb.GetColumnSpecRequest, opts ...gax.CallOption) (*automlpb.ColumnSpec, error) { + return c.internalClient.GetColumnSpec(ctx, req, opts...) +} + +// ListColumnSpecs lists column specs in a table spec. +func (c *Client) ListColumnSpecs(ctx context.Context, req *automlpb.ListColumnSpecsRequest, opts ...gax.CallOption) *ColumnSpecIterator { + return c.internalClient.ListColumnSpecs(ctx, req, opts...) +} + +// UpdateColumnSpec updates a column spec. +func (c *Client) UpdateColumnSpec(ctx context.Context, req *automlpb.UpdateColumnSpecRequest, opts ...gax.CallOption) (*automlpb.ColumnSpec, error) { + return c.internalClient.UpdateColumnSpec(ctx, req, opts...) +} + +// CreateModel creates a model. +// Returns a Model in the response +// field when it completes. +// When you create a model, several model evaluations are created for it: +// a global evaluation, and one evaluation for each annotation spec. +func (c *Client) CreateModel(ctx context.Context, req *automlpb.CreateModelRequest, opts ...gax.CallOption) (*CreateModelOperation, error) { + return c.internalClient.CreateModel(ctx, req, opts...) +} + +// CreateModelOperation returns a new CreateModelOperation from a given name. +// The name must be that of a previously created CreateModelOperation, possibly from a different process. +func (c *Client) CreateModelOperation(name string) *CreateModelOperation { + return c.internalClient.CreateModelOperation(name) +} + +// GetModel gets a model. +func (c *Client) GetModel(ctx context.Context, req *automlpb.GetModelRequest, opts ...gax.CallOption) (*automlpb.Model, error) { + return c.internalClient.GetModel(ctx, req, opts...) +} + +// ListModels lists models. +func (c *Client) ListModels(ctx context.Context, req *automlpb.ListModelsRequest, opts ...gax.CallOption) *ModelIterator { + return c.internalClient.ListModels(ctx, req, opts...) +} + +// DeleteModel deletes a model. +// Returns google.protobuf.Empty in the +// response field when it completes, +// and delete_details in the +// metadata field. +func (c *Client) DeleteModel(ctx context.Context, req *automlpb.DeleteModelRequest, opts ...gax.CallOption) (*DeleteModelOperation, error) { + return c.internalClient.DeleteModel(ctx, req, opts...) +} + +// DeleteModelOperation returns a new DeleteModelOperation from a given name. +// The name must be that of a previously created DeleteModelOperation, possibly from a different process. +func (c *Client) DeleteModelOperation(name string) *DeleteModelOperation { + return c.internalClient.DeleteModelOperation(name) +} + +// DeployModel deploys a model. If a model is already deployed, deploying it with the +// same parameters has no effect. Deploying with different parametrs +// (as e.g. changing +// +// node_number) +// will reset the deployment state without pausing the model’s availability. +// +// Only applicable for Text Classification, Image Object Detection , Tables, and Image Segmentation; all other domains manage +// deployment automatically. +// +// Returns an empty response in the +// response field when it completes. +func (c *Client) DeployModel(ctx context.Context, req *automlpb.DeployModelRequest, opts ...gax.CallOption) (*DeployModelOperation, error) { + return c.internalClient.DeployModel(ctx, req, opts...) +} + +// DeployModelOperation returns a new DeployModelOperation from a given name. +// The name must be that of a previously created DeployModelOperation, possibly from a different process. +func (c *Client) DeployModelOperation(name string) *DeployModelOperation { + return c.internalClient.DeployModelOperation(name) +} + +// UndeployModel undeploys a model. If the model is not deployed this method has no effect. +// +// Only applicable for Text Classification, Image Object Detection and Tables; +// all other domains manage deployment automatically. +// +// Returns an empty response in the +// response field when it completes. +func (c *Client) UndeployModel(ctx context.Context, req *automlpb.UndeployModelRequest, opts ...gax.CallOption) (*UndeployModelOperation, error) { + return c.internalClient.UndeployModel(ctx, req, opts...) +} + +// UndeployModelOperation returns a new UndeployModelOperation from a given name. +// The name must be that of a previously created UndeployModelOperation, possibly from a different process. +func (c *Client) UndeployModelOperation(name string) *UndeployModelOperation { + return c.internalClient.UndeployModelOperation(name) +} + +// ExportModel exports a trained, “export-able”, model to a user specified Google Cloud +// Storage location. A model is considered export-able if and only if it has +// an export format defined for it in +// +// ModelExportOutputConfig. +// +// Returns an empty response in the +// response field when it completes. +func (c *Client) ExportModel(ctx context.Context, req *automlpb.ExportModelRequest, opts ...gax.CallOption) (*ExportModelOperation, error) { + return c.internalClient.ExportModel(ctx, req, opts...) +} + +// ExportModelOperation returns a new ExportModelOperation from a given name. +// The name must be that of a previously created ExportModelOperation, possibly from a different process. +func (c *Client) ExportModelOperation(name string) *ExportModelOperation { + return c.internalClient.ExportModelOperation(name) +} + +// ExportEvaluatedExamples exports examples on which the model was evaluated (i.e. which were in the +// TEST set of the dataset the model was created from), together with their +// ground truth annotations and the annotations created (predicted) by the +// model. +// The examples, ground truth and predictions are exported in the state +// they were at the moment the model was evaluated. +// +// This export is available only for 30 days since the model evaluation is +// created. +// +// Currently only available for Tables. +// +// Returns an empty response in the +// response field when it completes. +func (c *Client) ExportEvaluatedExamples(ctx context.Context, req *automlpb.ExportEvaluatedExamplesRequest, opts ...gax.CallOption) (*ExportEvaluatedExamplesOperation, error) { + return c.internalClient.ExportEvaluatedExamples(ctx, req, opts...) +} + +// ExportEvaluatedExamplesOperation returns a new ExportEvaluatedExamplesOperation from a given name. +// The name must be that of a previously created ExportEvaluatedExamplesOperation, possibly from a different process. +func (c *Client) ExportEvaluatedExamplesOperation(name string) *ExportEvaluatedExamplesOperation { + return c.internalClient.ExportEvaluatedExamplesOperation(name) +} + +// GetModelEvaluation gets a model evaluation. +func (c *Client) GetModelEvaluation(ctx context.Context, req *automlpb.GetModelEvaluationRequest, opts ...gax.CallOption) (*automlpb.ModelEvaluation, error) { + return c.internalClient.GetModelEvaluation(ctx, req, opts...) +} + +// ListModelEvaluations lists model evaluations. +func (c *Client) ListModelEvaluations(ctx context.Context, req *automlpb.ListModelEvaluationsRequest, opts ...gax.CallOption) *ModelEvaluationIterator { + return c.internalClient.ListModelEvaluations(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud AutoML API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client automlpb.AutoMlClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new auto ml client. +// NewClient creates a new auto ml client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // AutoML Server API. // @@ -283,8 +610,7 @@ type Client struct { // On any input that is documented to expect a string parameter in // snake_case or kebab-case, either of those cases is accepted. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -302,16 +628,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: automlpb.NewAutoMlClient(connPool), + client: automlpb.NewAutoMlClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -321,33 +650,33 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateDataset creates a dataset. -func (c *Client) CreateDataset(ctx context.Context, req *automlpb.CreateDatasetRequest, opts ...gax.CallOption) (*automlpb.Dataset, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateDataset(ctx context.Context, req *automlpb.CreateDatasetRequest, opts ...gax.CallOption) (*automlpb.Dataset, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -355,7 +684,7 @@ func (c *Client) CreateDataset(ctx context.Context, req *automlpb.CreateDatasetR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateDataset[0:len(c.CallOptions.CreateDataset):len(c.CallOptions.CreateDataset)], opts...) + opts = append((*c.CallOptions).CreateDataset[0:len((*c.CallOptions).CreateDataset):len((*c.CallOptions).CreateDataset)], opts...) var resp *automlpb.Dataset err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -368,8 +697,7 @@ func (c *Client) CreateDataset(ctx context.Context, req *automlpb.CreateDatasetR return resp, nil } -// GetDataset gets a dataset. -func (c *Client) GetDataset(ctx context.Context, req *automlpb.GetDatasetRequest, opts ...gax.CallOption) (*automlpb.Dataset, error) { +func (c *gRPCClient) GetDataset(ctx context.Context, req *automlpb.GetDatasetRequest, opts ...gax.CallOption) (*automlpb.Dataset, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -377,7 +705,7 @@ func (c *Client) GetDataset(ctx context.Context, req *automlpb.GetDatasetRequest } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetDataset[0:len(c.CallOptions.GetDataset):len(c.CallOptions.GetDataset)], opts...) + opts = append((*c.CallOptions).GetDataset[0:len((*c.CallOptions).GetDataset):len((*c.CallOptions).GetDataset)], opts...) var resp *automlpb.Dataset err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -390,11 +718,10 @@ func (c *Client) GetDataset(ctx context.Context, req *automlpb.GetDatasetRequest return resp, nil } -// ListDatasets lists datasets in a project. -func (c *Client) ListDatasets(ctx context.Context, req *automlpb.ListDatasetsRequest, opts ...gax.CallOption) *DatasetIterator { +func (c *gRPCClient) ListDatasets(ctx context.Context, req *automlpb.ListDatasetsRequest, opts ...gax.CallOption) *DatasetIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDatasets[0:len(c.CallOptions.ListDatasets):len(c.CallOptions.ListDatasets)], opts...) + opts = append((*c.CallOptions).ListDatasets[0:len((*c.CallOptions).ListDatasets):len((*c.CallOptions).ListDatasets)], opts...) it := &DatasetIterator{} req = proto.Clone(req).(*automlpb.ListDatasetsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*automlpb.Dataset, string, error) { @@ -431,8 +758,7 @@ func (c *Client) ListDatasets(ctx context.Context, req *automlpb.ListDatasetsReq return it } -// UpdateDataset updates a dataset. -func (c *Client) UpdateDataset(ctx context.Context, req *automlpb.UpdateDatasetRequest, opts ...gax.CallOption) (*automlpb.Dataset, error) { +func (c *gRPCClient) UpdateDataset(ctx context.Context, req *automlpb.UpdateDatasetRequest, opts ...gax.CallOption) (*automlpb.Dataset, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -440,7 +766,7 @@ func (c *Client) UpdateDataset(ctx context.Context, req *automlpb.UpdateDatasetR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "dataset.name", url.QueryEscape(req.GetDataset().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateDataset[0:len(c.CallOptions.UpdateDataset):len(c.CallOptions.UpdateDataset)], opts...) + opts = append((*c.CallOptions).UpdateDataset[0:len((*c.CallOptions).UpdateDataset):len((*c.CallOptions).UpdateDataset)], opts...) var resp *automlpb.Dataset err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -453,12 +779,7 @@ func (c *Client) UpdateDataset(ctx context.Context, req *automlpb.UpdateDatasetR return resp, nil } -// DeleteDataset deletes a dataset and all of its contents. -// Returns empty response in the -// response field when it completes, -// and delete_details in the -// metadata field. -func (c *Client) DeleteDataset(ctx context.Context, req *automlpb.DeleteDatasetRequest, opts ...gax.CallOption) (*DeleteDatasetOperation, error) { +func (c *gRPCClient) DeleteDataset(ctx context.Context, req *automlpb.DeleteDatasetRequest, opts ...gax.CallOption) (*DeleteDatasetOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -466,7 +787,7 @@ func (c *Client) DeleteDataset(ctx context.Context, req *automlpb.DeleteDatasetR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteDataset[0:len(c.CallOptions.DeleteDataset):len(c.CallOptions.DeleteDataset)], opts...) + opts = append((*c.CallOptions).DeleteDataset[0:len((*c.CallOptions).DeleteDataset):len((*c.CallOptions).DeleteDataset)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -477,21 +798,11 @@ func (c *Client) DeleteDataset(ctx context.Context, req *automlpb.DeleteDatasetR return nil, err } return &DeleteDatasetOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ImportData imports data into a dataset. -// For Tables this method can only be called on an empty Dataset. -// -// For Tables: -// -// A -// schema_inference_version -// parameter must be explicitly set. -// Returns an empty response in the -// response field when it completes. -func (c *Client) ImportData(ctx context.Context, req *automlpb.ImportDataRequest, opts ...gax.CallOption) (*ImportDataOperation, error) { +func (c *gRPCClient) ImportData(ctx context.Context, req *automlpb.ImportDataRequest, opts ...gax.CallOption) (*ImportDataOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -499,7 +810,7 @@ func (c *Client) ImportData(ctx context.Context, req *automlpb.ImportDataRequest } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportData[0:len(c.CallOptions.ImportData):len(c.CallOptions.ImportData)], opts...) + opts = append((*c.CallOptions).ImportData[0:len((*c.CallOptions).ImportData):len((*c.CallOptions).ImportData)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -510,14 +821,11 @@ func (c *Client) ImportData(ctx context.Context, req *automlpb.ImportDataRequest return nil, err } return &ImportDataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ExportData exports dataset’s data to the provided output location. -// Returns an empty response in the -// response field when it completes. -func (c *Client) ExportData(ctx context.Context, req *automlpb.ExportDataRequest, opts ...gax.CallOption) (*ExportDataOperation, error) { +func (c *gRPCClient) ExportData(ctx context.Context, req *automlpb.ExportDataRequest, opts ...gax.CallOption) (*ExportDataOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -525,7 +833,7 @@ func (c *Client) ExportData(ctx context.Context, req *automlpb.ExportDataRequest } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportData[0:len(c.CallOptions.ExportData):len(c.CallOptions.ExportData)], opts...) + opts = append((*c.CallOptions).ExportData[0:len((*c.CallOptions).ExportData):len((*c.CallOptions).ExportData)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -536,12 +844,11 @@ func (c *Client) ExportData(ctx context.Context, req *automlpb.ExportDataRequest return nil, err } return &ExportDataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetAnnotationSpec gets an annotation spec. -func (c *Client) GetAnnotationSpec(ctx context.Context, req *automlpb.GetAnnotationSpecRequest, opts ...gax.CallOption) (*automlpb.AnnotationSpec, error) { +func (c *gRPCClient) GetAnnotationSpec(ctx context.Context, req *automlpb.GetAnnotationSpecRequest, opts ...gax.CallOption) (*automlpb.AnnotationSpec, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -549,7 +856,7 @@ func (c *Client) GetAnnotationSpec(ctx context.Context, req *automlpb.GetAnnotat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetAnnotationSpec[0:len(c.CallOptions.GetAnnotationSpec):len(c.CallOptions.GetAnnotationSpec)], opts...) + opts = append((*c.CallOptions).GetAnnotationSpec[0:len((*c.CallOptions).GetAnnotationSpec):len((*c.CallOptions).GetAnnotationSpec)], opts...) var resp *automlpb.AnnotationSpec err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -562,8 +869,7 @@ func (c *Client) GetAnnotationSpec(ctx context.Context, req *automlpb.GetAnnotat return resp, nil } -// GetTableSpec gets a table spec. -func (c *Client) GetTableSpec(ctx context.Context, req *automlpb.GetTableSpecRequest, opts ...gax.CallOption) (*automlpb.TableSpec, error) { +func (c *gRPCClient) GetTableSpec(ctx context.Context, req *automlpb.GetTableSpecRequest, opts ...gax.CallOption) (*automlpb.TableSpec, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -571,7 +877,7 @@ func (c *Client) GetTableSpec(ctx context.Context, req *automlpb.GetTableSpecReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTableSpec[0:len(c.CallOptions.GetTableSpec):len(c.CallOptions.GetTableSpec)], opts...) + opts = append((*c.CallOptions).GetTableSpec[0:len((*c.CallOptions).GetTableSpec):len((*c.CallOptions).GetTableSpec)], opts...) var resp *automlpb.TableSpec err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -584,11 +890,10 @@ func (c *Client) GetTableSpec(ctx context.Context, req *automlpb.GetTableSpecReq return resp, nil } -// ListTableSpecs lists table specs in a dataset. -func (c *Client) ListTableSpecs(ctx context.Context, req *automlpb.ListTableSpecsRequest, opts ...gax.CallOption) *TableSpecIterator { +func (c *gRPCClient) ListTableSpecs(ctx context.Context, req *automlpb.ListTableSpecsRequest, opts ...gax.CallOption) *TableSpecIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTableSpecs[0:len(c.CallOptions.ListTableSpecs):len(c.CallOptions.ListTableSpecs)], opts...) + opts = append((*c.CallOptions).ListTableSpecs[0:len((*c.CallOptions).ListTableSpecs):len((*c.CallOptions).ListTableSpecs)], opts...) it := &TableSpecIterator{} req = proto.Clone(req).(*automlpb.ListTableSpecsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*automlpb.TableSpec, string, error) { @@ -625,8 +930,7 @@ func (c *Client) ListTableSpecs(ctx context.Context, req *automlpb.ListTableSpec return it } -// UpdateTableSpec updates a table spec. -func (c *Client) UpdateTableSpec(ctx context.Context, req *automlpb.UpdateTableSpecRequest, opts ...gax.CallOption) (*automlpb.TableSpec, error) { +func (c *gRPCClient) UpdateTableSpec(ctx context.Context, req *automlpb.UpdateTableSpecRequest, opts ...gax.CallOption) (*automlpb.TableSpec, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -634,7 +938,7 @@ func (c *Client) UpdateTableSpec(ctx context.Context, req *automlpb.UpdateTableS } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "table_spec.name", url.QueryEscape(req.GetTableSpec().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTableSpec[0:len(c.CallOptions.UpdateTableSpec):len(c.CallOptions.UpdateTableSpec)], opts...) + opts = append((*c.CallOptions).UpdateTableSpec[0:len((*c.CallOptions).UpdateTableSpec):len((*c.CallOptions).UpdateTableSpec)], opts...) var resp *automlpb.TableSpec err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -647,8 +951,7 @@ func (c *Client) UpdateTableSpec(ctx context.Context, req *automlpb.UpdateTableS return resp, nil } -// GetColumnSpec gets a column spec. -func (c *Client) GetColumnSpec(ctx context.Context, req *automlpb.GetColumnSpecRequest, opts ...gax.CallOption) (*automlpb.ColumnSpec, error) { +func (c *gRPCClient) GetColumnSpec(ctx context.Context, req *automlpb.GetColumnSpecRequest, opts ...gax.CallOption) (*automlpb.ColumnSpec, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -656,7 +959,7 @@ func (c *Client) GetColumnSpec(ctx context.Context, req *automlpb.GetColumnSpecR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetColumnSpec[0:len(c.CallOptions.GetColumnSpec):len(c.CallOptions.GetColumnSpec)], opts...) + opts = append((*c.CallOptions).GetColumnSpec[0:len((*c.CallOptions).GetColumnSpec):len((*c.CallOptions).GetColumnSpec)], opts...) var resp *automlpb.ColumnSpec err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -669,11 +972,10 @@ func (c *Client) GetColumnSpec(ctx context.Context, req *automlpb.GetColumnSpecR return resp, nil } -// ListColumnSpecs lists column specs in a table spec. -func (c *Client) ListColumnSpecs(ctx context.Context, req *automlpb.ListColumnSpecsRequest, opts ...gax.CallOption) *ColumnSpecIterator { +func (c *gRPCClient) ListColumnSpecs(ctx context.Context, req *automlpb.ListColumnSpecsRequest, opts ...gax.CallOption) *ColumnSpecIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListColumnSpecs[0:len(c.CallOptions.ListColumnSpecs):len(c.CallOptions.ListColumnSpecs)], opts...) + opts = append((*c.CallOptions).ListColumnSpecs[0:len((*c.CallOptions).ListColumnSpecs):len((*c.CallOptions).ListColumnSpecs)], opts...) it := &ColumnSpecIterator{} req = proto.Clone(req).(*automlpb.ListColumnSpecsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*automlpb.ColumnSpec, string, error) { @@ -710,8 +1012,7 @@ func (c *Client) ListColumnSpecs(ctx context.Context, req *automlpb.ListColumnSp return it } -// UpdateColumnSpec updates a column spec. -func (c *Client) UpdateColumnSpec(ctx context.Context, req *automlpb.UpdateColumnSpecRequest, opts ...gax.CallOption) (*automlpb.ColumnSpec, error) { +func (c *gRPCClient) UpdateColumnSpec(ctx context.Context, req *automlpb.UpdateColumnSpecRequest, opts ...gax.CallOption) (*automlpb.ColumnSpec, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -719,7 +1020,7 @@ func (c *Client) UpdateColumnSpec(ctx context.Context, req *automlpb.UpdateColum } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "column_spec.name", url.QueryEscape(req.GetColumnSpec().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateColumnSpec[0:len(c.CallOptions.UpdateColumnSpec):len(c.CallOptions.UpdateColumnSpec)], opts...) + opts = append((*c.CallOptions).UpdateColumnSpec[0:len((*c.CallOptions).UpdateColumnSpec):len((*c.CallOptions).UpdateColumnSpec)], opts...) var resp *automlpb.ColumnSpec err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -732,12 +1033,7 @@ func (c *Client) UpdateColumnSpec(ctx context.Context, req *automlpb.UpdateColum return resp, nil } -// CreateModel creates a model. -// Returns a Model in the response -// field when it completes. -// When you create a model, several model evaluations are created for it: -// a global evaluation, and one evaluation for each annotation spec. -func (c *Client) CreateModel(ctx context.Context, req *automlpb.CreateModelRequest, opts ...gax.CallOption) (*CreateModelOperation, error) { +func (c *gRPCClient) CreateModel(ctx context.Context, req *automlpb.CreateModelRequest, opts ...gax.CallOption) (*CreateModelOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -745,7 +1041,7 @@ func (c *Client) CreateModel(ctx context.Context, req *automlpb.CreateModelReque } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateModel[0:len(c.CallOptions.CreateModel):len(c.CallOptions.CreateModel)], opts...) + opts = append((*c.CallOptions).CreateModel[0:len((*c.CallOptions).CreateModel):len((*c.CallOptions).CreateModel)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -756,12 +1052,11 @@ func (c *Client) CreateModel(ctx context.Context, req *automlpb.CreateModelReque return nil, err } return &CreateModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetModel gets a model. -func (c *Client) GetModel(ctx context.Context, req *automlpb.GetModelRequest, opts ...gax.CallOption) (*automlpb.Model, error) { +func (c *gRPCClient) GetModel(ctx context.Context, req *automlpb.GetModelRequest, opts ...gax.CallOption) (*automlpb.Model, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -769,7 +1064,7 @@ func (c *Client) GetModel(ctx context.Context, req *automlpb.GetModelRequest, op } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetModel[0:len(c.CallOptions.GetModel):len(c.CallOptions.GetModel)], opts...) + opts = append((*c.CallOptions).GetModel[0:len((*c.CallOptions).GetModel):len((*c.CallOptions).GetModel)], opts...) var resp *automlpb.Model err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -782,11 +1077,10 @@ func (c *Client) GetModel(ctx context.Context, req *automlpb.GetModelRequest, op return resp, nil } -// ListModels lists models. -func (c *Client) ListModels(ctx context.Context, req *automlpb.ListModelsRequest, opts ...gax.CallOption) *ModelIterator { +func (c *gRPCClient) ListModels(ctx context.Context, req *automlpb.ListModelsRequest, opts ...gax.CallOption) *ModelIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListModels[0:len(c.CallOptions.ListModels):len(c.CallOptions.ListModels)], opts...) + opts = append((*c.CallOptions).ListModels[0:len((*c.CallOptions).ListModels):len((*c.CallOptions).ListModels)], opts...) it := &ModelIterator{} req = proto.Clone(req).(*automlpb.ListModelsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*automlpb.Model, string, error) { @@ -823,12 +1117,7 @@ func (c *Client) ListModels(ctx context.Context, req *automlpb.ListModelsRequest return it } -// DeleteModel deletes a model. -// Returns google.protobuf.Empty in the -// response field when it completes, -// and delete_details in the -// metadata field. -func (c *Client) DeleteModel(ctx context.Context, req *automlpb.DeleteModelRequest, opts ...gax.CallOption) (*DeleteModelOperation, error) { +func (c *gRPCClient) DeleteModel(ctx context.Context, req *automlpb.DeleteModelRequest, opts ...gax.CallOption) (*DeleteModelOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -836,7 +1125,7 @@ func (c *Client) DeleteModel(ctx context.Context, req *automlpb.DeleteModelReque } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteModel[0:len(c.CallOptions.DeleteModel):len(c.CallOptions.DeleteModel)], opts...) + opts = append((*c.CallOptions).DeleteModel[0:len((*c.CallOptions).DeleteModel):len((*c.CallOptions).DeleteModel)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -847,23 +1136,11 @@ func (c *Client) DeleteModel(ctx context.Context, req *automlpb.DeleteModelReque return nil, err } return &DeleteModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeployModel deploys a model. If a model is already deployed, deploying it with the -// same parameters has no effect. Deploying with different parametrs -// (as e.g. changing -// -// node_number) -// will reset the deployment state without pausing the model’s availability. -// -// Only applicable for Text Classification, Image Object Detection , Tables, and Image Segmentation; all other domains manage -// deployment automatically. -// -// Returns an empty response in the -// response field when it completes. -func (c *Client) DeployModel(ctx context.Context, req *automlpb.DeployModelRequest, opts ...gax.CallOption) (*DeployModelOperation, error) { +func (c *gRPCClient) DeployModel(ctx context.Context, req *automlpb.DeployModelRequest, opts ...gax.CallOption) (*DeployModelOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -871,7 +1148,7 @@ func (c *Client) DeployModel(ctx context.Context, req *automlpb.DeployModelReque } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeployModel[0:len(c.CallOptions.DeployModel):len(c.CallOptions.DeployModel)], opts...) + opts = append((*c.CallOptions).DeployModel[0:len((*c.CallOptions).DeployModel):len((*c.CallOptions).DeployModel)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -882,18 +1159,11 @@ func (c *Client) DeployModel(ctx context.Context, req *automlpb.DeployModelReque return nil, err } return &DeployModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UndeployModel undeploys a model. If the model is not deployed this method has no effect. -// -// Only applicable for Text Classification, Image Object Detection and Tables; -// all other domains manage deployment automatically. -// -// Returns an empty response in the -// response field when it completes. -func (c *Client) UndeployModel(ctx context.Context, req *automlpb.UndeployModelRequest, opts ...gax.CallOption) (*UndeployModelOperation, error) { +func (c *gRPCClient) UndeployModel(ctx context.Context, req *automlpb.UndeployModelRequest, opts ...gax.CallOption) (*UndeployModelOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -901,7 +1171,7 @@ func (c *Client) UndeployModel(ctx context.Context, req *automlpb.UndeployModelR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UndeployModel[0:len(c.CallOptions.UndeployModel):len(c.CallOptions.UndeployModel)], opts...) + opts = append((*c.CallOptions).UndeployModel[0:len((*c.CallOptions).UndeployModel):len((*c.CallOptions).UndeployModel)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -912,19 +1182,11 @@ func (c *Client) UndeployModel(ctx context.Context, req *automlpb.UndeployModelR return nil, err } return &UndeployModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ExportModel exports a trained, “export-able”, model to a user specified Google Cloud -// Storage location. A model is considered export-able if and only if it has -// an export format defined for it in -// -// ModelExportOutputConfig. -// -// Returns an empty response in the -// response field when it completes. -func (c *Client) ExportModel(ctx context.Context, req *automlpb.ExportModelRequest, opts ...gax.CallOption) (*ExportModelOperation, error) { +func (c *gRPCClient) ExportModel(ctx context.Context, req *automlpb.ExportModelRequest, opts ...gax.CallOption) (*ExportModelOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -932,7 +1194,7 @@ func (c *Client) ExportModel(ctx context.Context, req *automlpb.ExportModelReque } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportModel[0:len(c.CallOptions.ExportModel):len(c.CallOptions.ExportModel)], opts...) + opts = append((*c.CallOptions).ExportModel[0:len((*c.CallOptions).ExportModel):len((*c.CallOptions).ExportModel)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -943,25 +1205,11 @@ func (c *Client) ExportModel(ctx context.Context, req *automlpb.ExportModelReque return nil, err } return &ExportModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ExportEvaluatedExamples exports examples on which the model was evaluated (i.e. which were in the -// TEST set of the dataset the model was created from), together with their -// ground truth annotations and the annotations created (predicted) by the -// model. -// The examples, ground truth and predictions are exported in the state -// they were at the moment the model was evaluated. -// -// This export is available only for 30 days since the model evaluation is -// created. -// -// Currently only available for Tables. -// -// Returns an empty response in the -// response field when it completes. -func (c *Client) ExportEvaluatedExamples(ctx context.Context, req *automlpb.ExportEvaluatedExamplesRequest, opts ...gax.CallOption) (*ExportEvaluatedExamplesOperation, error) { +func (c *gRPCClient) ExportEvaluatedExamples(ctx context.Context, req *automlpb.ExportEvaluatedExamplesRequest, opts ...gax.CallOption) (*ExportEvaluatedExamplesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -969,7 +1217,7 @@ func (c *Client) ExportEvaluatedExamples(ctx context.Context, req *automlpb.Expo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportEvaluatedExamples[0:len(c.CallOptions.ExportEvaluatedExamples):len(c.CallOptions.ExportEvaluatedExamples)], opts...) + opts = append((*c.CallOptions).ExportEvaluatedExamples[0:len((*c.CallOptions).ExportEvaluatedExamples):len((*c.CallOptions).ExportEvaluatedExamples)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -980,12 +1228,11 @@ func (c *Client) ExportEvaluatedExamples(ctx context.Context, req *automlpb.Expo return nil, err } return &ExportEvaluatedExamplesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetModelEvaluation gets a model evaluation. -func (c *Client) GetModelEvaluation(ctx context.Context, req *automlpb.GetModelEvaluationRequest, opts ...gax.CallOption) (*automlpb.ModelEvaluation, error) { +func (c *gRPCClient) GetModelEvaluation(ctx context.Context, req *automlpb.GetModelEvaluationRequest, opts ...gax.CallOption) (*automlpb.ModelEvaluation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000*time.Millisecond) defer cancel() @@ -993,7 +1240,7 @@ func (c *Client) GetModelEvaluation(ctx context.Context, req *automlpb.GetModelE } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetModelEvaluation[0:len(c.CallOptions.GetModelEvaluation):len(c.CallOptions.GetModelEvaluation)], opts...) + opts = append((*c.CallOptions).GetModelEvaluation[0:len((*c.CallOptions).GetModelEvaluation):len((*c.CallOptions).GetModelEvaluation)], opts...) var resp *automlpb.ModelEvaluation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1006,11 +1253,10 @@ func (c *Client) GetModelEvaluation(ctx context.Context, req *automlpb.GetModelE return resp, nil } -// ListModelEvaluations lists model evaluations. -func (c *Client) ListModelEvaluations(ctx context.Context, req *automlpb.ListModelEvaluationsRequest, opts ...gax.CallOption) *ModelEvaluationIterator { +func (c *gRPCClient) ListModelEvaluations(ctx context.Context, req *automlpb.ListModelEvaluationsRequest, opts ...gax.CallOption) *ModelEvaluationIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListModelEvaluations[0:len(c.CallOptions.ListModelEvaluations):len(c.CallOptions.ListModelEvaluations)], opts...) + opts = append((*c.CallOptions).ListModelEvaluations[0:len((*c.CallOptions).ListModelEvaluations):len((*c.CallOptions).ListModelEvaluations)], opts...) it := &ModelEvaluationIterator{} req = proto.Clone(req).(*automlpb.ListModelEvaluationsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*automlpb.ModelEvaluation, string, error) { @@ -1054,9 +1300,9 @@ type CreateModelOperation struct { // CreateModelOperation returns a new CreateModelOperation from a given name. // The name must be that of a previously created CreateModelOperation, possibly from a different process. -func (c *Client) CreateModelOperation(name string) *CreateModelOperation { +func (c *gRPCClient) CreateModelOperation(name string) *CreateModelOperation { return &CreateModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1123,9 +1369,9 @@ type DeleteDatasetOperation struct { // DeleteDatasetOperation returns a new DeleteDatasetOperation from a given name. // The name must be that of a previously created DeleteDatasetOperation, possibly from a different process. -func (c *Client) DeleteDatasetOperation(name string) *DeleteDatasetOperation { +func (c *gRPCClient) DeleteDatasetOperation(name string) *DeleteDatasetOperation { return &DeleteDatasetOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1181,9 +1427,9 @@ type DeleteModelOperation struct { // DeleteModelOperation returns a new DeleteModelOperation from a given name. // The name must be that of a previously created DeleteModelOperation, possibly from a different process. -func (c *Client) DeleteModelOperation(name string) *DeleteModelOperation { +func (c *gRPCClient) DeleteModelOperation(name string) *DeleteModelOperation { return &DeleteModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1239,9 +1485,9 @@ type DeployModelOperation struct { // DeployModelOperation returns a new DeployModelOperation from a given name. // The name must be that of a previously created DeployModelOperation, possibly from a different process. -func (c *Client) DeployModelOperation(name string) *DeployModelOperation { +func (c *gRPCClient) DeployModelOperation(name string) *DeployModelOperation { return &DeployModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1297,9 +1543,9 @@ type ExportDataOperation struct { // ExportDataOperation returns a new ExportDataOperation from a given name. // The name must be that of a previously created ExportDataOperation, possibly from a different process. -func (c *Client) ExportDataOperation(name string) *ExportDataOperation { +func (c *gRPCClient) ExportDataOperation(name string) *ExportDataOperation { return &ExportDataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1355,9 +1601,9 @@ type ExportEvaluatedExamplesOperation struct { // ExportEvaluatedExamplesOperation returns a new ExportEvaluatedExamplesOperation from a given name. // The name must be that of a previously created ExportEvaluatedExamplesOperation, possibly from a different process. -func (c *Client) ExportEvaluatedExamplesOperation(name string) *ExportEvaluatedExamplesOperation { +func (c *gRPCClient) ExportEvaluatedExamplesOperation(name string) *ExportEvaluatedExamplesOperation { return &ExportEvaluatedExamplesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1413,9 +1659,9 @@ type ExportModelOperation struct { // ExportModelOperation returns a new ExportModelOperation from a given name. // The name must be that of a previously created ExportModelOperation, possibly from a different process. -func (c *Client) ExportModelOperation(name string) *ExportModelOperation { +func (c *gRPCClient) ExportModelOperation(name string) *ExportModelOperation { return &ExportModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1471,9 +1717,9 @@ type ImportDataOperation struct { // ImportDataOperation returns a new ImportDataOperation from a given name. // The name must be that of a previously created ImportDataOperation, possibly from a different process. -func (c *Client) ImportDataOperation(name string) *ImportDataOperation { +func (c *gRPCClient) ImportDataOperation(name string) *ImportDataOperation { return &ImportDataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1529,9 +1775,9 @@ type UndeployModelOperation struct { // UndeployModelOperation returns a new UndeployModelOperation from a given name. // The name must be that of a previously created UndeployModelOperation, possibly from a different process. -func (c *Client) UndeployModelOperation(name string) *UndeployModelOperation { +func (c *gRPCClient) UndeployModelOperation(name string) *UndeployModelOperation { return &UndeployModelOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/automl/apiv1beta1/auto_ml_client_example_test.go b/automl/apiv1beta1/auto_ml_client_example_test.go index dfe395d7e03a..c1f71c7b11e4 100644 --- a/automl/apiv1beta1/auto_ml_client_example_test.go +++ b/automl/apiv1beta1/auto_ml_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateDataset() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.CreateDatasetRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleClient_CreateDataset() { } func ExampleClient_GetDataset() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetDatasetRequest{ // TODO: Fill request struct fields. @@ -75,14 +75,12 @@ func ExampleClient_GetDataset() { } func ExampleClient_ListDatasets() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ListDatasetsRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleClient_ListDatasets() { } func ExampleClient_UpdateDataset() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.UpdateDatasetRequest{ // TODO: Fill request struct fields. @@ -122,13 +119,12 @@ func ExampleClient_UpdateDataset() { } func ExampleClient_DeleteDataset() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.DeleteDatasetRequest{ // TODO: Fill request struct fields. @@ -145,13 +141,12 @@ func ExampleClient_DeleteDataset() { } func ExampleClient_ImportData() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ImportDataRequest{ // TODO: Fill request struct fields. @@ -168,13 +163,12 @@ func ExampleClient_ImportData() { } func ExampleClient_ExportData() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ExportDataRequest{ // TODO: Fill request struct fields. @@ -191,13 +185,12 @@ func ExampleClient_ExportData() { } func ExampleClient_GetAnnotationSpec() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetAnnotationSpecRequest{ // TODO: Fill request struct fields. @@ -211,13 +204,12 @@ func ExampleClient_GetAnnotationSpec() { } func ExampleClient_GetTableSpec() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetTableSpecRequest{ // TODO: Fill request struct fields. @@ -231,14 +223,12 @@ func ExampleClient_GetTableSpec() { } func ExampleClient_ListTableSpecs() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ListTableSpecsRequest{ // TODO: Fill request struct fields. @@ -258,13 +248,12 @@ func ExampleClient_ListTableSpecs() { } func ExampleClient_UpdateTableSpec() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.UpdateTableSpecRequest{ // TODO: Fill request struct fields. @@ -278,13 +267,12 @@ func ExampleClient_UpdateTableSpec() { } func ExampleClient_GetColumnSpec() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetColumnSpecRequest{ // TODO: Fill request struct fields. @@ -298,14 +286,12 @@ func ExampleClient_GetColumnSpec() { } func ExampleClient_ListColumnSpecs() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ListColumnSpecsRequest{ // TODO: Fill request struct fields. @@ -325,13 +311,12 @@ func ExampleClient_ListColumnSpecs() { } func ExampleClient_UpdateColumnSpec() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.UpdateColumnSpecRequest{ // TODO: Fill request struct fields. @@ -345,13 +330,12 @@ func ExampleClient_UpdateColumnSpec() { } func ExampleClient_CreateModel() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.CreateModelRequest{ // TODO: Fill request struct fields. @@ -370,13 +354,12 @@ func ExampleClient_CreateModel() { } func ExampleClient_GetModel() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetModelRequest{ // TODO: Fill request struct fields. @@ -390,14 +373,12 @@ func ExampleClient_GetModel() { } func ExampleClient_ListModels() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ListModelsRequest{ // TODO: Fill request struct fields. @@ -417,13 +398,12 @@ func ExampleClient_ListModels() { } func ExampleClient_DeleteModel() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.DeleteModelRequest{ // TODO: Fill request struct fields. @@ -440,13 +420,12 @@ func ExampleClient_DeleteModel() { } func ExampleClient_DeployModel() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.DeployModelRequest{ // TODO: Fill request struct fields. @@ -463,13 +442,12 @@ func ExampleClient_DeployModel() { } func ExampleClient_UndeployModel() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.UndeployModelRequest{ // TODO: Fill request struct fields. @@ -486,13 +464,12 @@ func ExampleClient_UndeployModel() { } func ExampleClient_ExportModel() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ExportModelRequest{ // TODO: Fill request struct fields. @@ -509,13 +486,12 @@ func ExampleClient_ExportModel() { } func ExampleClient_ExportEvaluatedExamples() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ExportEvaluatedExamplesRequest{ // TODO: Fill request struct fields. @@ -532,13 +508,12 @@ func ExampleClient_ExportEvaluatedExamples() { } func ExampleClient_GetModelEvaluation() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetModelEvaluationRequest{ // TODO: Fill request struct fields. @@ -552,14 +527,12 @@ func ExampleClient_GetModelEvaluation() { } func ExampleClient_ListModelEvaluations() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ListModelEvaluationsRequest{ // TODO: Fill request struct fields. diff --git a/automl/apiv1beta1/doc.go b/automl/apiv1beta1/doc.go index cdee673617e1..d80707ac64c1 100644 --- a/automl/apiv1beta1/doc.go +++ b/automl/apiv1beta1/doc.go @@ -20,6 +20,8 @@ // Train high-quality custom machine learning models with minimum effort and // machine learning expertise. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package automl // import "cloud.google.com/go/automl/apiv1beta1" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/automl/apiv1beta1/prediction_client.go b/automl/apiv1beta1/prediction_client.go index 6c5ef8221b88..885e7dc55880 100644 --- a/automl/apiv1beta1/prediction_client.go +++ b/automl/apiv1beta1/prediction_client.go @@ -43,7 +43,7 @@ type PredictionCallOptions struct { BatchPredict []gax.CallOption } -func defaultPredictionClientOptions() []option.ClientOption { +func defaultPredictionGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("automl.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("automl.mtls.googleapis.com:443"), @@ -62,40 +62,149 @@ func defaultPredictionCallOptions() *PredictionCallOptions { } } +// internalPredictionClient is an interface that defines the methods availaible from Cloud AutoML API. +type internalPredictionClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + Predict(context.Context, *automlpb.PredictRequest, ...gax.CallOption) (*automlpb.PredictResponse, error) + BatchPredict(context.Context, *automlpb.BatchPredictRequest, ...gax.CallOption) (*BatchPredictOperation, error) + BatchPredictOperation(name string) *BatchPredictOperation +} + // PredictionClient is a client for interacting with Cloud AutoML API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// AutoML Prediction API. +// +// On any input that is documented to expect a string parameter in +// snake_case or kebab-case, either of those cases is accepted. type PredictionClient struct { + // The internal transport-dependent client. + internalClient internalPredictionClient + + // The call options for this service. + CallOptions *PredictionCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *PredictionClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *PredictionClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *PredictionClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// Predict perform an online prediction. The prediction result will be directly +// returned in the response. +// Available for following ML problems, and their expected request payloads: +// +// Image Classification - Image in .JPEG, .GIF or .PNG format, image_bytes +// up to 30MB. +// +// Image Object Detection - Image in .JPEG, .GIF or .PNG format, image_bytes +// up to 30MB. +// +// Text Classification - TextSnippet, content up to 60,000 characters, +// UTF-8 encoded. +// +// Text Extraction - TextSnippet, content up to 30,000 characters, +// UTF-8 NFC encoded. +// +// Translation - TextSnippet, content up to 25,000 characters, UTF-8 +// encoded. +// +// Tables - Row, with column values matching the columns of the model, +// up to 5MB. Not available for FORECASTING +// +// prediction_type. +// +// Text Sentiment - TextSnippet, content up 500 characters, UTF-8 +// encoded. +func (c *PredictionClient) Predict(ctx context.Context, req *automlpb.PredictRequest, opts ...gax.CallOption) (*automlpb.PredictResponse, error) { + return c.internalClient.Predict(ctx, req, opts...) +} + +// BatchPredict perform a batch prediction. Unlike the online Predict, batch +// prediction result won’t be immediately available in the response. Instead, +// a long running operation object is returned. User can poll the operation +// result via GetOperation +// method. Once the operation is done, BatchPredictResult is returned in +// the response field. +// Available for following ML problems: +// +// Image Classification +// +// Image Object Detection +// +// Video Classification +// +// Video Object Tracking * Text Extraction +// +// Tables +func (c *PredictionClient) BatchPredict(ctx context.Context, req *automlpb.BatchPredictRequest, opts ...gax.CallOption) (*BatchPredictOperation, error) { + return c.internalClient.BatchPredict(ctx, req, opts...) +} + +// BatchPredictOperation returns a new BatchPredictOperation from a given name. +// The name must be that of a previously created BatchPredictOperation, possibly from a different process. +func (c *PredictionClient) BatchPredictOperation(name string) *BatchPredictOperation { + return c.internalClient.BatchPredictOperation(name) +} + +// predictionGRPCClient is a client for interacting with Cloud AutoML API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type predictionGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing PredictionClient + CallOptions **PredictionCallOptions + // The gRPC API client. predictionClient automlpb.PredictionServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *PredictionCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewPredictionClient creates a new prediction service client. +// NewPredictionClient creates a new prediction service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // AutoML Prediction API. // // On any input that is documented to expect a string parameter in // snake_case or kebab-case, either of those cases is accepted. func NewPredictionClient(ctx context.Context, opts ...option.ClientOption) (*PredictionClient, error) { - clientOpts := defaultPredictionClientOptions() - + clientOpts := defaultPredictionGRPCClientOptions() if newPredictionClientHook != nil { hookOpts, err := newPredictionClientHook(ctx, clientHookParams{}) if err != nil { @@ -113,16 +222,19 @@ func NewPredictionClient(ctx context.Context, opts ...option.ClientOption) (*Pre if err != nil { return nil, err } - c := &PredictionClient{ + client := PredictionClient{CallOptions: defaultPredictionCallOptions()} + + c := &predictionGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultPredictionCallOptions(), - predictionClient: automlpb.NewPredictionServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -132,58 +244,33 @@ func NewPredictionClient(ctx context.Context, opts ...option.ClientOption) (*Pre // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *PredictionClient) Connection() *grpc.ClientConn { +func (c *predictionGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *PredictionClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *PredictionClient) setGoogleClientInfo(keyval ...string) { +func (c *predictionGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// Predict perform an online prediction. The prediction result will be directly -// returned in the response. -// Available for following ML problems, and their expected request payloads: -// -// Image Classification - Image in .JPEG, .GIF or .PNG format, image_bytes -// up to 30MB. -// -// Image Object Detection - Image in .JPEG, .GIF or .PNG format, image_bytes -// up to 30MB. -// -// Text Classification - TextSnippet, content up to 60,000 characters, -// UTF-8 encoded. -// -// Text Extraction - TextSnippet, content up to 30,000 characters, -// UTF-8 NFC encoded. -// -// Translation - TextSnippet, content up to 25,000 characters, UTF-8 -// encoded. -// -// Tables - Row, with column values matching the columns of the model, -// up to 5MB. Not available for FORECASTING -// -// prediction_type. -// -// Text Sentiment - TextSnippet, content up 500 characters, UTF-8 -// encoded. -func (c *PredictionClient) Predict(ctx context.Context, req *automlpb.PredictRequest, opts ...gax.CallOption) (*automlpb.PredictResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *predictionGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *predictionGRPCClient) Predict(ctx context.Context, req *automlpb.PredictRequest, opts ...gax.CallOption) (*automlpb.PredictResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -191,7 +278,7 @@ func (c *PredictionClient) Predict(ctx context.Context, req *automlpb.PredictReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.Predict[0:len(c.CallOptions.Predict):len(c.CallOptions.Predict)], opts...) + opts = append((*c.CallOptions).Predict[0:len((*c.CallOptions).Predict):len((*c.CallOptions).Predict)], opts...) var resp *automlpb.PredictResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -204,24 +291,7 @@ func (c *PredictionClient) Predict(ctx context.Context, req *automlpb.PredictReq return resp, nil } -// BatchPredict perform a batch prediction. Unlike the online Predict, batch -// prediction result won’t be immediately available in the response. Instead, -// a long running operation object is returned. User can poll the operation -// result via GetOperation -// method. Once the operation is done, BatchPredictResult is returned in -// the response field. -// Available for following ML problems: -// -// Image Classification -// -// Image Object Detection -// -// Video Classification -// -// Video Object Tracking * Text Extraction -// -// Tables -func (c *PredictionClient) BatchPredict(ctx context.Context, req *automlpb.BatchPredictRequest, opts ...gax.CallOption) (*BatchPredictOperation, error) { +func (c *predictionGRPCClient) BatchPredict(ctx context.Context, req *automlpb.BatchPredictRequest, opts ...gax.CallOption) (*BatchPredictOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -229,7 +299,7 @@ func (c *PredictionClient) BatchPredict(ctx context.Context, req *automlpb.Batch } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchPredict[0:len(c.CallOptions.BatchPredict):len(c.CallOptions.BatchPredict)], opts...) + opts = append((*c.CallOptions).BatchPredict[0:len((*c.CallOptions).BatchPredict):len((*c.CallOptions).BatchPredict)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -240,7 +310,7 @@ func (c *PredictionClient) BatchPredict(ctx context.Context, req *automlpb.Batch return nil, err } return &BatchPredictOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -251,9 +321,9 @@ type BatchPredictOperation struct { // BatchPredictOperation returns a new BatchPredictOperation from a given name. // The name must be that of a previously created BatchPredictOperation, possibly from a different process. -func (c *PredictionClient) BatchPredictOperation(name string) *BatchPredictOperation { +func (c *predictionGRPCClient) BatchPredictOperation(name string) *BatchPredictOperation { return &BatchPredictOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/automl/apiv1beta1/prediction_client_example_test.go b/automl/apiv1beta1/prediction_client_example_test.go index f5f1317a3485..3bdd367d3e62 100644 --- a/automl/apiv1beta1/prediction_client_example_test.go +++ b/automl/apiv1beta1/prediction_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewPredictionClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExamplePredictionClient_Predict() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewPredictionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.PredictRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExamplePredictionClient_Predict() { } func ExamplePredictionClient_BatchPredict() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewPredictionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.BatchPredictRequest{ // TODO: Fill request struct fields. diff --git a/bigquery/connection/apiv1/connection_client.go b/bigquery/connection/apiv1/connection_client.go index 1999c784dd18..31371e3c6880 100644 --- a/bigquery/connection/apiv1/connection_client.go +++ b/bigquery/connection/apiv1/connection_client.go @@ -50,7 +50,7 @@ type CallOptions struct { TestIamPermissions []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("bigqueryconnection.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("bigqueryconnection.mtls.googleapis.com:443"), @@ -108,32 +108,133 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from BigQuery Connection API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateConnection(context.Context, *connectionpb.CreateConnectionRequest, ...gax.CallOption) (*connectionpb.Connection, error) + GetConnection(context.Context, *connectionpb.GetConnectionRequest, ...gax.CallOption) (*connectionpb.Connection, error) + ListConnections(context.Context, *connectionpb.ListConnectionsRequest, ...gax.CallOption) *ConnectionIterator + UpdateConnection(context.Context, *connectionpb.UpdateConnectionRequest, ...gax.CallOption) (*connectionpb.Connection, error) + DeleteConnection(context.Context, *connectionpb.DeleteConnectionRequest, ...gax.CallOption) error + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) +} + // Client is a client for interacting with BigQuery Connection API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Manages external data source connections and credentials. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateConnection creates a new connection. +func (c *Client) CreateConnection(ctx context.Context, req *connectionpb.CreateConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { + return c.internalClient.CreateConnection(ctx, req, opts...) +} + +// GetConnection returns specified connection. +func (c *Client) GetConnection(ctx context.Context, req *connectionpb.GetConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { + return c.internalClient.GetConnection(ctx, req, opts...) +} + +// ListConnections returns a list of connections in the given project. +func (c *Client) ListConnections(ctx context.Context, req *connectionpb.ListConnectionsRequest, opts ...gax.CallOption) *ConnectionIterator { + return c.internalClient.ListConnections(ctx, req, opts...) +} + +// UpdateConnection updates the specified connection. For security reasons, also resets +// credential if connection properties are in the update field mask. +func (c *Client) UpdateConnection(ctx context.Context, req *connectionpb.UpdateConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { + return c.internalClient.UpdateConnection(ctx, req, opts...) +} + +// DeleteConnection deletes connection and associated credential. +func (c *Client) DeleteConnection(ctx context.Context, req *connectionpb.DeleteConnectionRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteConnection(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy for a resource. +// Returns an empty policy if the resource exists and does not have a policy +// set. +func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces any +// existing policy. +// +// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED errors. +func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. +// If the resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building permission-aware +// UIs and command-line tools, not for authorization checking. This operation +// may “fail open” without warning. +func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with BigQuery Connection API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client connectionpb.ConnectionServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new connection service client. +// NewClient creates a new connection service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Manages external data source connections and credentials. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -151,42 +252,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: connectionpb.NewConnectionServiceClient(connPool), + client: connectionpb.NewConnectionServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateConnection creates a new connection. -func (c *Client) CreateConnection(ctx context.Context, req *connectionpb.CreateConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateConnection(ctx context.Context, req *connectionpb.CreateConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -194,7 +297,7 @@ func (c *Client) CreateConnection(ctx context.Context, req *connectionpb.CreateC } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateConnection[0:len(c.CallOptions.CreateConnection):len(c.CallOptions.CreateConnection)], opts...) + opts = append((*c.CallOptions).CreateConnection[0:len((*c.CallOptions).CreateConnection):len((*c.CallOptions).CreateConnection)], opts...) var resp *connectionpb.Connection err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -207,8 +310,7 @@ func (c *Client) CreateConnection(ctx context.Context, req *connectionpb.CreateC return resp, nil } -// GetConnection returns specified connection. -func (c *Client) GetConnection(ctx context.Context, req *connectionpb.GetConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { +func (c *gRPCClient) GetConnection(ctx context.Context, req *connectionpb.GetConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -216,7 +318,7 @@ func (c *Client) GetConnection(ctx context.Context, req *connectionpb.GetConnect } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetConnection[0:len(c.CallOptions.GetConnection):len(c.CallOptions.GetConnection)], opts...) + opts = append((*c.CallOptions).GetConnection[0:len((*c.CallOptions).GetConnection):len((*c.CallOptions).GetConnection)], opts...) var resp *connectionpb.Connection err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -229,11 +331,10 @@ func (c *Client) GetConnection(ctx context.Context, req *connectionpb.GetConnect return resp, nil } -// ListConnections returns a list of connections in the given project. -func (c *Client) ListConnections(ctx context.Context, req *connectionpb.ListConnectionsRequest, opts ...gax.CallOption) *ConnectionIterator { +func (c *gRPCClient) ListConnections(ctx context.Context, req *connectionpb.ListConnectionsRequest, opts ...gax.CallOption) *ConnectionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListConnections[0:len(c.CallOptions.ListConnections):len(c.CallOptions.ListConnections)], opts...) + opts = append((*c.CallOptions).ListConnections[0:len((*c.CallOptions).ListConnections):len((*c.CallOptions).ListConnections)], opts...) it := &ConnectionIterator{} req = proto.Clone(req).(*connectionpb.ListConnectionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*connectionpb.Connection, string, error) { @@ -270,9 +371,7 @@ func (c *Client) ListConnections(ctx context.Context, req *connectionpb.ListConn return it } -// UpdateConnection updates the specified connection. For security reasons, also resets -// credential if connection properties are in the update field mask. -func (c *Client) UpdateConnection(ctx context.Context, req *connectionpb.UpdateConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { +func (c *gRPCClient) UpdateConnection(ctx context.Context, req *connectionpb.UpdateConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -280,7 +379,7 @@ func (c *Client) UpdateConnection(ctx context.Context, req *connectionpb.UpdateC } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateConnection[0:len(c.CallOptions.UpdateConnection):len(c.CallOptions.UpdateConnection)], opts...) + opts = append((*c.CallOptions).UpdateConnection[0:len((*c.CallOptions).UpdateConnection):len((*c.CallOptions).UpdateConnection)], opts...) var resp *connectionpb.Connection err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -293,8 +392,7 @@ func (c *Client) UpdateConnection(ctx context.Context, req *connectionpb.UpdateC return resp, nil } -// DeleteConnection deletes connection and associated credential. -func (c *Client) DeleteConnection(ctx context.Context, req *connectionpb.DeleteConnectionRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteConnection(ctx context.Context, req *connectionpb.DeleteConnectionRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -302,7 +400,7 @@ func (c *Client) DeleteConnection(ctx context.Context, req *connectionpb.DeleteC } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteConnection[0:len(c.CallOptions.DeleteConnection):len(c.CallOptions.DeleteConnection)], opts...) + opts = append((*c.CallOptions).DeleteConnection[0:len((*c.CallOptions).DeleteConnection):len((*c.CallOptions).DeleteConnection)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteConnection(ctx, req, settings.GRPC...) @@ -311,10 +409,7 @@ func (c *Client) DeleteConnection(ctx context.Context, req *connectionpb.DeleteC return err } -// GetIamPolicy gets the access control policy for a resource. -// Returns an empty policy if the resource exists and does not have a policy -// set. -func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -322,7 +417,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -335,11 +430,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques return resp, nil } -// SetIamPolicy sets the access control policy on the specified resource. Replaces any -// existing policy. -// -// Can return NOT_FOUND, INVALID_ARGUMENT, and PERMISSION_DENIED errors. -func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -347,7 +438,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -360,14 +451,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques return resp, nil } -// TestIamPermissions returns permissions that a caller has on the specified resource. -// If the resource does not exist, this will return an empty set of -// permissions, not a NOT_FOUND error. -// -// Note: This operation is designed to be used for building permission-aware -// UIs and command-line tools, not for authorization checking. This operation -// may “fail open” without warning. -func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *gRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -375,7 +459,7 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/bigquery/connection/apiv1/connection_client_example_test.go b/bigquery/connection/apiv1/connection_client_example_test.go index 7abbb6d9b258..fb8e241e66d8 100644 --- a/bigquery/connection/apiv1/connection_client_example_test.go +++ b/bigquery/connection/apiv1/connection_client_example_test.go @@ -31,18 +31,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateConnection() { - // import connectionpb "google.golang.org/genproto/googleapis/cloud/bigquery/connection/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.CreateConnectionRequest{ // TODO: Fill request struct fields. @@ -56,13 +57,12 @@ func ExampleClient_CreateConnection() { } func ExampleClient_GetConnection() { - // import connectionpb "google.golang.org/genproto/googleapis/cloud/bigquery/connection/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.GetConnectionRequest{ // TODO: Fill request struct fields. @@ -76,14 +76,12 @@ func ExampleClient_GetConnection() { } func ExampleClient_ListConnections() { - // import connectionpb "google.golang.org/genproto/googleapis/cloud/bigquery/connection/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.ListConnectionsRequest{ // TODO: Fill request struct fields. @@ -103,13 +101,12 @@ func ExampleClient_ListConnections() { } func ExampleClient_UpdateConnection() { - // import connectionpb "google.golang.org/genproto/googleapis/cloud/bigquery/connection/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.UpdateConnectionRequest{ // TODO: Fill request struct fields. @@ -128,6 +125,7 @@ func ExampleClient_DeleteConnection() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.DeleteConnectionRequest{ // TODO: Fill request struct fields. @@ -139,13 +137,12 @@ func ExampleClient_DeleteConnection() { } func ExampleClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -159,13 +156,12 @@ func ExampleClient_GetIamPolicy() { } func ExampleClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -179,13 +175,12 @@ func ExampleClient_SetIamPolicy() { } func ExampleClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/bigquery/connection/apiv1/doc.go b/bigquery/connection/apiv1/doc.go index a149c12e0924..4db8eb5e93ff 100644 --- a/bigquery/connection/apiv1/doc.go +++ b/bigquery/connection/apiv1/doc.go @@ -28,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package connection // import "cloud.google.com/go/bigquery/connection/apiv1" import ( @@ -48,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/bigquery/connection/apiv1beta1/connection_client.go b/bigquery/connection/apiv1beta1/connection_client.go index 845316afbc1c..4f14f723bc2b 100644 --- a/bigquery/connection/apiv1beta1/connection_client.go +++ b/bigquery/connection/apiv1beta1/connection_client.go @@ -49,7 +49,7 @@ type CallOptions struct { TestIamPermissions []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("bigqueryconnection.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("bigqueryconnection.mtls.googleapis.com:443"), @@ -108,32 +108,139 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from BigQuery Connection API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateConnection(context.Context, *connectionpb.CreateConnectionRequest, ...gax.CallOption) (*connectionpb.Connection, error) + GetConnection(context.Context, *connectionpb.GetConnectionRequest, ...gax.CallOption) (*connectionpb.Connection, error) + ListConnections(context.Context, *connectionpb.ListConnectionsRequest, ...gax.CallOption) (*connectionpb.ListConnectionsResponse, error) + UpdateConnection(context.Context, *connectionpb.UpdateConnectionRequest, ...gax.CallOption) (*connectionpb.Connection, error) + UpdateConnectionCredential(context.Context, *connectionpb.UpdateConnectionCredentialRequest, ...gax.CallOption) error + DeleteConnection(context.Context, *connectionpb.DeleteConnectionRequest, ...gax.CallOption) error + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) +} + // Client is a client for interacting with BigQuery Connection API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Manages external data source connections and credentials. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateConnection creates a new connection. +func (c *Client) CreateConnection(ctx context.Context, req *connectionpb.CreateConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { + return c.internalClient.CreateConnection(ctx, req, opts...) +} + +// GetConnection returns specified connection. +func (c *Client) GetConnection(ctx context.Context, req *connectionpb.GetConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { + return c.internalClient.GetConnection(ctx, req, opts...) +} + +// ListConnections returns a list of connections in the given project. +func (c *Client) ListConnections(ctx context.Context, req *connectionpb.ListConnectionsRequest, opts ...gax.CallOption) (*connectionpb.ListConnectionsResponse, error) { + return c.internalClient.ListConnections(ctx, req, opts...) +} + +// UpdateConnection updates the specified connection. For security reasons, also resets +// credential if connection properties are in the update field mask. +func (c *Client) UpdateConnection(ctx context.Context, req *connectionpb.UpdateConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { + return c.internalClient.UpdateConnection(ctx, req, opts...) +} + +// UpdateConnectionCredential sets the credential for the specified connection. +func (c *Client) UpdateConnectionCredential(ctx context.Context, req *connectionpb.UpdateConnectionCredentialRequest, opts ...gax.CallOption) error { + return c.internalClient.UpdateConnectionCredential(ctx, req, opts...) +} + +// DeleteConnection deletes connection and associated credential. +func (c *Client) DeleteConnection(ctx context.Context, req *connectionpb.DeleteConnectionRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteConnection(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy for a resource. +// Returns an empty policy if the resource exists and does not have a policy +// set. +func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces any +// existing policy. +// +// Can return Public Errors: NOT_FOUND, INVALID_ARGUMENT and PERMISSION_DENIED +func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. +// If the resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building permission-aware +// UIs and command-line tools, not for authorization checking. This operation +// may “fail open” without warning. +func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with BigQuery Connection API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client connectionpb.ConnectionServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new connection service client. +// NewClient creates a new connection service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Manages external data source connections and credentials. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -151,42 +258,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: connectionpb.NewConnectionServiceClient(connPool), + client: connectionpb.NewConnectionServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateConnection creates a new connection. -func (c *Client) CreateConnection(ctx context.Context, req *connectionpb.CreateConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateConnection(ctx context.Context, req *connectionpb.CreateConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -194,7 +303,7 @@ func (c *Client) CreateConnection(ctx context.Context, req *connectionpb.CreateC } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateConnection[0:len(c.CallOptions.CreateConnection):len(c.CallOptions.CreateConnection)], opts...) + opts = append((*c.CallOptions).CreateConnection[0:len((*c.CallOptions).CreateConnection):len((*c.CallOptions).CreateConnection)], opts...) var resp *connectionpb.Connection err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -207,8 +316,7 @@ func (c *Client) CreateConnection(ctx context.Context, req *connectionpb.CreateC return resp, nil } -// GetConnection returns specified connection. -func (c *Client) GetConnection(ctx context.Context, req *connectionpb.GetConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { +func (c *gRPCClient) GetConnection(ctx context.Context, req *connectionpb.GetConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -216,7 +324,7 @@ func (c *Client) GetConnection(ctx context.Context, req *connectionpb.GetConnect } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetConnection[0:len(c.CallOptions.GetConnection):len(c.CallOptions.GetConnection)], opts...) + opts = append((*c.CallOptions).GetConnection[0:len((*c.CallOptions).GetConnection):len((*c.CallOptions).GetConnection)], opts...) var resp *connectionpb.Connection err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -229,8 +337,7 @@ func (c *Client) GetConnection(ctx context.Context, req *connectionpb.GetConnect return resp, nil } -// ListConnections returns a list of connections in the given project. -func (c *Client) ListConnections(ctx context.Context, req *connectionpb.ListConnectionsRequest, opts ...gax.CallOption) (*connectionpb.ListConnectionsResponse, error) { +func (c *gRPCClient) ListConnections(ctx context.Context, req *connectionpb.ListConnectionsRequest, opts ...gax.CallOption) (*connectionpb.ListConnectionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -238,7 +345,7 @@ func (c *Client) ListConnections(ctx context.Context, req *connectionpb.ListConn } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListConnections[0:len(c.CallOptions.ListConnections):len(c.CallOptions.ListConnections)], opts...) + opts = append((*c.CallOptions).ListConnections[0:len((*c.CallOptions).ListConnections):len((*c.CallOptions).ListConnections)], opts...) var resp *connectionpb.ListConnectionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -251,9 +358,7 @@ func (c *Client) ListConnections(ctx context.Context, req *connectionpb.ListConn return resp, nil } -// UpdateConnection updates the specified connection. For security reasons, also resets -// credential if connection properties are in the update field mask. -func (c *Client) UpdateConnection(ctx context.Context, req *connectionpb.UpdateConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { +func (c *gRPCClient) UpdateConnection(ctx context.Context, req *connectionpb.UpdateConnectionRequest, opts ...gax.CallOption) (*connectionpb.Connection, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -261,7 +366,7 @@ func (c *Client) UpdateConnection(ctx context.Context, req *connectionpb.UpdateC } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateConnection[0:len(c.CallOptions.UpdateConnection):len(c.CallOptions.UpdateConnection)], opts...) + opts = append((*c.CallOptions).UpdateConnection[0:len((*c.CallOptions).UpdateConnection):len((*c.CallOptions).UpdateConnection)], opts...) var resp *connectionpb.Connection err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -274,8 +379,7 @@ func (c *Client) UpdateConnection(ctx context.Context, req *connectionpb.UpdateC return resp, nil } -// UpdateConnectionCredential sets the credential for the specified connection. -func (c *Client) UpdateConnectionCredential(ctx context.Context, req *connectionpb.UpdateConnectionCredentialRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) UpdateConnectionCredential(ctx context.Context, req *connectionpb.UpdateConnectionCredentialRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -283,7 +387,7 @@ func (c *Client) UpdateConnectionCredential(ctx context.Context, req *connection } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateConnectionCredential[0:len(c.CallOptions.UpdateConnectionCredential):len(c.CallOptions.UpdateConnectionCredential)], opts...) + opts = append((*c.CallOptions).UpdateConnectionCredential[0:len((*c.CallOptions).UpdateConnectionCredential):len((*c.CallOptions).UpdateConnectionCredential)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.UpdateConnectionCredential(ctx, req, settings.GRPC...) @@ -292,8 +396,7 @@ func (c *Client) UpdateConnectionCredential(ctx context.Context, req *connection return err } -// DeleteConnection deletes connection and associated credential. -func (c *Client) DeleteConnection(ctx context.Context, req *connectionpb.DeleteConnectionRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteConnection(ctx context.Context, req *connectionpb.DeleteConnectionRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -301,7 +404,7 @@ func (c *Client) DeleteConnection(ctx context.Context, req *connectionpb.DeleteC } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteConnection[0:len(c.CallOptions.DeleteConnection):len(c.CallOptions.DeleteConnection)], opts...) + opts = append((*c.CallOptions).DeleteConnection[0:len((*c.CallOptions).DeleteConnection):len((*c.CallOptions).DeleteConnection)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteConnection(ctx, req, settings.GRPC...) @@ -310,10 +413,7 @@ func (c *Client) DeleteConnection(ctx context.Context, req *connectionpb.DeleteC return err } -// GetIamPolicy gets the access control policy for a resource. -// Returns an empty policy if the resource exists and does not have a policy -// set. -func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -321,7 +421,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -334,11 +434,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques return resp, nil } -// SetIamPolicy sets the access control policy on the specified resource. Replaces any -// existing policy. -// -// Can return Public Errors: NOT_FOUND, INVALID_ARGUMENT and PERMISSION_DENIED -func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -346,7 +442,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -359,14 +455,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques return resp, nil } -// TestIamPermissions returns permissions that a caller has on the specified resource. -// If the resource does not exist, this will return an empty set of -// permissions, not a NOT_FOUND error. -// -// Note: This operation is designed to be used for building permission-aware -// UIs and command-line tools, not for authorization checking. This operation -// may “fail open” without warning. -func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *gRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -374,7 +463,7 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/bigquery/connection/apiv1beta1/connection_client_example_test.go b/bigquery/connection/apiv1beta1/connection_client_example_test.go index e76a04401a42..4a85cecdad2a 100644 --- a/bigquery/connection/apiv1beta1/connection_client_example_test.go +++ b/bigquery/connection/apiv1beta1/connection_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateConnection() { - // import connectionpb "google.golang.org/genproto/googleapis/cloud/bigquery/connection/v1beta1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.CreateConnectionRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleClient_CreateConnection() { } func ExampleClient_GetConnection() { - // import connectionpb "google.golang.org/genproto/googleapis/cloud/bigquery/connection/v1beta1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.GetConnectionRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleClient_GetConnection() { } func ExampleClient_ListConnections() { - // import connectionpb "google.golang.org/genproto/googleapis/cloud/bigquery/connection/v1beta1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.ListConnectionsRequest{ // TODO: Fill request struct fields. @@ -95,13 +94,12 @@ func ExampleClient_ListConnections() { } func ExampleClient_UpdateConnection() { - // import connectionpb "google.golang.org/genproto/googleapis/cloud/bigquery/connection/v1beta1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.UpdateConnectionRequest{ // TODO: Fill request struct fields. @@ -120,6 +118,7 @@ func ExampleClient_UpdateConnectionCredential() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.UpdateConnectionCredentialRequest{ // TODO: Fill request struct fields. @@ -136,6 +135,7 @@ func ExampleClient_DeleteConnection() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.DeleteConnectionRequest{ // TODO: Fill request struct fields. @@ -147,13 +147,12 @@ func ExampleClient_DeleteConnection() { } func ExampleClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -167,13 +166,12 @@ func ExampleClient_GetIamPolicy() { } func ExampleClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -187,13 +185,12 @@ func ExampleClient_SetIamPolicy() { } func ExampleClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/bigquery/connection/apiv1beta1/doc.go b/bigquery/connection/apiv1beta1/doc.go index 9994fd3cff1c..72df77080dca 100644 --- a/bigquery/connection/apiv1beta1/doc.go +++ b/bigquery/connection/apiv1beta1/doc.go @@ -19,6 +19,8 @@ // // Allows users to manage BigQuery connections to external data sources. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -28,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package connection // import "cloud.google.com/go/bigquery/connection/apiv1beta1" import ( @@ -48,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/bigquery/datatransfer/apiv1/data_transfer_client.go b/bigquery/datatransfer/apiv1/data_transfer_client.go index c043f5c19b4d..1e4cee34c3e9 100644 --- a/bigquery/datatransfer/apiv1/data_transfer_client.go +++ b/bigquery/datatransfer/apiv1/data_transfer_client.go @@ -55,7 +55,7 @@ type CallOptions struct { CheckValidCreds []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("bigquerydatatransfer.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("bigquerydatatransfer.mtls.googleapis.com:443"), @@ -196,35 +196,181 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from BigQuery Data Transfer API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + GetDataSource(context.Context, *datatransferpb.GetDataSourceRequest, ...gax.CallOption) (*datatransferpb.DataSource, error) + ListDataSources(context.Context, *datatransferpb.ListDataSourcesRequest, ...gax.CallOption) *DataSourceIterator + CreateTransferConfig(context.Context, *datatransferpb.CreateTransferConfigRequest, ...gax.CallOption) (*datatransferpb.TransferConfig, error) + UpdateTransferConfig(context.Context, *datatransferpb.UpdateTransferConfigRequest, ...gax.CallOption) (*datatransferpb.TransferConfig, error) + DeleteTransferConfig(context.Context, *datatransferpb.DeleteTransferConfigRequest, ...gax.CallOption) error + GetTransferConfig(context.Context, *datatransferpb.GetTransferConfigRequest, ...gax.CallOption) (*datatransferpb.TransferConfig, error) + ListTransferConfigs(context.Context, *datatransferpb.ListTransferConfigsRequest, ...gax.CallOption) *TransferConfigIterator + ScheduleTransferRuns(context.Context, *datatransferpb.ScheduleTransferRunsRequest, ...gax.CallOption) (*datatransferpb.ScheduleTransferRunsResponse, error) + StartManualTransferRuns(context.Context, *datatransferpb.StartManualTransferRunsRequest, ...gax.CallOption) (*datatransferpb.StartManualTransferRunsResponse, error) + GetTransferRun(context.Context, *datatransferpb.GetTransferRunRequest, ...gax.CallOption) (*datatransferpb.TransferRun, error) + DeleteTransferRun(context.Context, *datatransferpb.DeleteTransferRunRequest, ...gax.CallOption) error + ListTransferRuns(context.Context, *datatransferpb.ListTransferRunsRequest, ...gax.CallOption) *TransferRunIterator + ListTransferLogs(context.Context, *datatransferpb.ListTransferLogsRequest, ...gax.CallOption) *TransferMessageIterator + CheckValidCreds(context.Context, *datatransferpb.CheckValidCredsRequest, ...gax.CallOption) (*datatransferpb.CheckValidCredsResponse, error) +} + // Client is a client for interacting with BigQuery Data Transfer API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The Google BigQuery Data Transfer Service API enables BigQuery users to +// configure the transfer of their data from other Google Products into +// BigQuery. This service contains methods that are end user exposed. It backs +// up the frontend. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// GetDataSource retrieves a supported data source and returns its settings, +// which can be used for UI rendering. +func (c *Client) GetDataSource(ctx context.Context, req *datatransferpb.GetDataSourceRequest, opts ...gax.CallOption) (*datatransferpb.DataSource, error) { + return c.internalClient.GetDataSource(ctx, req, opts...) +} + +// ListDataSources lists supported data sources and returns their settings, +// which can be used for UI rendering. +func (c *Client) ListDataSources(ctx context.Context, req *datatransferpb.ListDataSourcesRequest, opts ...gax.CallOption) *DataSourceIterator { + return c.internalClient.ListDataSources(ctx, req, opts...) +} + +// CreateTransferConfig creates a new data transfer configuration. +func (c *Client) CreateTransferConfig(ctx context.Context, req *datatransferpb.CreateTransferConfigRequest, opts ...gax.CallOption) (*datatransferpb.TransferConfig, error) { + return c.internalClient.CreateTransferConfig(ctx, req, opts...) +} + +// UpdateTransferConfig updates a data transfer configuration. +// All fields must be set, even if they are not updated. +func (c *Client) UpdateTransferConfig(ctx context.Context, req *datatransferpb.UpdateTransferConfigRequest, opts ...gax.CallOption) (*datatransferpb.TransferConfig, error) { + return c.internalClient.UpdateTransferConfig(ctx, req, opts...) +} + +// DeleteTransferConfig deletes a data transfer configuration, +// including any associated transfer runs and logs. +func (c *Client) DeleteTransferConfig(ctx context.Context, req *datatransferpb.DeleteTransferConfigRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTransferConfig(ctx, req, opts...) +} + +// GetTransferConfig returns information about a data transfer config. +func (c *Client) GetTransferConfig(ctx context.Context, req *datatransferpb.GetTransferConfigRequest, opts ...gax.CallOption) (*datatransferpb.TransferConfig, error) { + return c.internalClient.GetTransferConfig(ctx, req, opts...) +} + +// ListTransferConfigs returns information about all data transfers in the project. +func (c *Client) ListTransferConfigs(ctx context.Context, req *datatransferpb.ListTransferConfigsRequest, opts ...gax.CallOption) *TransferConfigIterator { + return c.internalClient.ListTransferConfigs(ctx, req, opts...) +} + +// ScheduleTransferRuns creates transfer runs for a time range [start_time, end_time]. +// For each date - or whatever granularity the data source supports - in the +// range, one transfer run is created. +// Note that runs are created per UTC time in the time range. +// DEPRECATED: use StartManualTransferRuns instead. +// +// Deprecated: ScheduleTransferRuns may be removed in a future version. +func (c *Client) ScheduleTransferRuns(ctx context.Context, req *datatransferpb.ScheduleTransferRunsRequest, opts ...gax.CallOption) (*datatransferpb.ScheduleTransferRunsResponse, error) { + return c.internalClient.ScheduleTransferRuns(ctx, req, opts...) +} + +// StartManualTransferRuns start manual transfer runs to be executed now with schedule_time equal to +// current time. The transfer runs can be created for a time range where the +// run_time is between start_time (inclusive) and end_time (exclusive), or for +// a specific run_time. +func (c *Client) StartManualTransferRuns(ctx context.Context, req *datatransferpb.StartManualTransferRunsRequest, opts ...gax.CallOption) (*datatransferpb.StartManualTransferRunsResponse, error) { + return c.internalClient.StartManualTransferRuns(ctx, req, opts...) +} + +// GetTransferRun returns information about the particular transfer run. +func (c *Client) GetTransferRun(ctx context.Context, req *datatransferpb.GetTransferRunRequest, opts ...gax.CallOption) (*datatransferpb.TransferRun, error) { + return c.internalClient.GetTransferRun(ctx, req, opts...) +} + +// DeleteTransferRun deletes the specified transfer run. +func (c *Client) DeleteTransferRun(ctx context.Context, req *datatransferpb.DeleteTransferRunRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTransferRun(ctx, req, opts...) +} + +// ListTransferRuns returns information about running and completed jobs. +func (c *Client) ListTransferRuns(ctx context.Context, req *datatransferpb.ListTransferRunsRequest, opts ...gax.CallOption) *TransferRunIterator { + return c.internalClient.ListTransferRuns(ctx, req, opts...) +} + +// ListTransferLogs returns user facing log messages for the data transfer run. +func (c *Client) ListTransferLogs(ctx context.Context, req *datatransferpb.ListTransferLogsRequest, opts ...gax.CallOption) *TransferMessageIterator { + return c.internalClient.ListTransferLogs(ctx, req, opts...) +} + +// CheckValidCreds returns true if valid credentials exist for the given data source and +// requesting user. +// Some data sources doesn’t support service account, so we need to talk to +// them on behalf of the end user. This API just checks whether we have OAuth +// token for the particular user, which is a pre-requisite before user can +// create a transfer config. +func (c *Client) CheckValidCreds(ctx context.Context, req *datatransferpb.CheckValidCredsRequest, opts ...gax.CallOption) (*datatransferpb.CheckValidCredsResponse, error) { + return c.internalClient.CheckValidCreds(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with BigQuery Data Transfer API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client datatransferpb.DataTransferServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new data transfer service client. +// NewClient creates a new data transfer service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The Google BigQuery Data Transfer Service API enables BigQuery users to // configure the transfer of their data from other Google Products into // BigQuery. This service contains methods that are end user exposed. It backs // up the frontend. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -242,43 +388,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: datatransferpb.NewDataTransferServiceClient(connPool), + client: datatransferpb.NewDataTransferServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// GetDataSource retrieves a supported data source and returns its settings, -// which can be used for UI rendering. -func (c *Client) GetDataSource(ctx context.Context, req *datatransferpb.GetDataSourceRequest, opts ...gax.CallOption) (*datatransferpb.DataSource, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) GetDataSource(ctx context.Context, req *datatransferpb.GetDataSourceRequest, opts ...gax.CallOption) (*datatransferpb.DataSource, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -286,7 +433,7 @@ func (c *Client) GetDataSource(ctx context.Context, req *datatransferpb.GetDataS } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetDataSource[0:len(c.CallOptions.GetDataSource):len(c.CallOptions.GetDataSource)], opts...) + opts = append((*c.CallOptions).GetDataSource[0:len((*c.CallOptions).GetDataSource):len((*c.CallOptions).GetDataSource)], opts...) var resp *datatransferpb.DataSource err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -299,12 +446,10 @@ func (c *Client) GetDataSource(ctx context.Context, req *datatransferpb.GetDataS return resp, nil } -// ListDataSources lists supported data sources and returns their settings, -// which can be used for UI rendering. -func (c *Client) ListDataSources(ctx context.Context, req *datatransferpb.ListDataSourcesRequest, opts ...gax.CallOption) *DataSourceIterator { +func (c *gRPCClient) ListDataSources(ctx context.Context, req *datatransferpb.ListDataSourcesRequest, opts ...gax.CallOption) *DataSourceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDataSources[0:len(c.CallOptions.ListDataSources):len(c.CallOptions.ListDataSources)], opts...) + opts = append((*c.CallOptions).ListDataSources[0:len((*c.CallOptions).ListDataSources):len((*c.CallOptions).ListDataSources)], opts...) it := &DataSourceIterator{} req = proto.Clone(req).(*datatransferpb.ListDataSourcesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datatransferpb.DataSource, string, error) { @@ -341,8 +486,7 @@ func (c *Client) ListDataSources(ctx context.Context, req *datatransferpb.ListDa return it } -// CreateTransferConfig creates a new data transfer configuration. -func (c *Client) CreateTransferConfig(ctx context.Context, req *datatransferpb.CreateTransferConfigRequest, opts ...gax.CallOption) (*datatransferpb.TransferConfig, error) { +func (c *gRPCClient) CreateTransferConfig(ctx context.Context, req *datatransferpb.CreateTransferConfigRequest, opts ...gax.CallOption) (*datatransferpb.TransferConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -350,7 +494,7 @@ func (c *Client) CreateTransferConfig(ctx context.Context, req *datatransferpb.C } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTransferConfig[0:len(c.CallOptions.CreateTransferConfig):len(c.CallOptions.CreateTransferConfig)], opts...) + opts = append((*c.CallOptions).CreateTransferConfig[0:len((*c.CallOptions).CreateTransferConfig):len((*c.CallOptions).CreateTransferConfig)], opts...) var resp *datatransferpb.TransferConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -363,9 +507,7 @@ func (c *Client) CreateTransferConfig(ctx context.Context, req *datatransferpb.C return resp, nil } -// UpdateTransferConfig updates a data transfer configuration. -// All fields must be set, even if they are not updated. -func (c *Client) UpdateTransferConfig(ctx context.Context, req *datatransferpb.UpdateTransferConfigRequest, opts ...gax.CallOption) (*datatransferpb.TransferConfig, error) { +func (c *gRPCClient) UpdateTransferConfig(ctx context.Context, req *datatransferpb.UpdateTransferConfigRequest, opts ...gax.CallOption) (*datatransferpb.TransferConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -373,7 +515,7 @@ func (c *Client) UpdateTransferConfig(ctx context.Context, req *datatransferpb.U } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "transfer_config.name", url.QueryEscape(req.GetTransferConfig().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTransferConfig[0:len(c.CallOptions.UpdateTransferConfig):len(c.CallOptions.UpdateTransferConfig)], opts...) + opts = append((*c.CallOptions).UpdateTransferConfig[0:len((*c.CallOptions).UpdateTransferConfig):len((*c.CallOptions).UpdateTransferConfig)], opts...) var resp *datatransferpb.TransferConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -386,9 +528,7 @@ func (c *Client) UpdateTransferConfig(ctx context.Context, req *datatransferpb.U return resp, nil } -// DeleteTransferConfig deletes a data transfer configuration, -// including any associated transfer runs and logs. -func (c *Client) DeleteTransferConfig(ctx context.Context, req *datatransferpb.DeleteTransferConfigRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteTransferConfig(ctx context.Context, req *datatransferpb.DeleteTransferConfigRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -396,7 +536,7 @@ func (c *Client) DeleteTransferConfig(ctx context.Context, req *datatransferpb.D } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTransferConfig[0:len(c.CallOptions.DeleteTransferConfig):len(c.CallOptions.DeleteTransferConfig)], opts...) + opts = append((*c.CallOptions).DeleteTransferConfig[0:len((*c.CallOptions).DeleteTransferConfig):len((*c.CallOptions).DeleteTransferConfig)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteTransferConfig(ctx, req, settings.GRPC...) @@ -405,8 +545,7 @@ func (c *Client) DeleteTransferConfig(ctx context.Context, req *datatransferpb.D return err } -// GetTransferConfig returns information about a data transfer config. -func (c *Client) GetTransferConfig(ctx context.Context, req *datatransferpb.GetTransferConfigRequest, opts ...gax.CallOption) (*datatransferpb.TransferConfig, error) { +func (c *gRPCClient) GetTransferConfig(ctx context.Context, req *datatransferpb.GetTransferConfigRequest, opts ...gax.CallOption) (*datatransferpb.TransferConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -414,7 +553,7 @@ func (c *Client) GetTransferConfig(ctx context.Context, req *datatransferpb.GetT } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTransferConfig[0:len(c.CallOptions.GetTransferConfig):len(c.CallOptions.GetTransferConfig)], opts...) + opts = append((*c.CallOptions).GetTransferConfig[0:len((*c.CallOptions).GetTransferConfig):len((*c.CallOptions).GetTransferConfig)], opts...) var resp *datatransferpb.TransferConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -427,11 +566,10 @@ func (c *Client) GetTransferConfig(ctx context.Context, req *datatransferpb.GetT return resp, nil } -// ListTransferConfigs returns information about all data transfers in the project. -func (c *Client) ListTransferConfigs(ctx context.Context, req *datatransferpb.ListTransferConfigsRequest, opts ...gax.CallOption) *TransferConfigIterator { +func (c *gRPCClient) ListTransferConfigs(ctx context.Context, req *datatransferpb.ListTransferConfigsRequest, opts ...gax.CallOption) *TransferConfigIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTransferConfigs[0:len(c.CallOptions.ListTransferConfigs):len(c.CallOptions.ListTransferConfigs)], opts...) + opts = append((*c.CallOptions).ListTransferConfigs[0:len((*c.CallOptions).ListTransferConfigs):len((*c.CallOptions).ListTransferConfigs)], opts...) it := &TransferConfigIterator{} req = proto.Clone(req).(*datatransferpb.ListTransferConfigsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datatransferpb.TransferConfig, string, error) { @@ -468,12 +606,7 @@ func (c *Client) ListTransferConfigs(ctx context.Context, req *datatransferpb.Li return it } -// ScheduleTransferRuns creates transfer runs for a time range [start_time, end_time]. -// For each date - or whatever granularity the data source supports - in the -// range, one transfer run is created. -// Note that runs are created per UTC time in the time range. -// DEPRECATED: use StartManualTransferRuns instead. -func (c *Client) ScheduleTransferRuns(ctx context.Context, req *datatransferpb.ScheduleTransferRunsRequest, opts ...gax.CallOption) (*datatransferpb.ScheduleTransferRunsResponse, error) { +func (c *gRPCClient) ScheduleTransferRuns(ctx context.Context, req *datatransferpb.ScheduleTransferRunsRequest, opts ...gax.CallOption) (*datatransferpb.ScheduleTransferRunsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -481,7 +614,7 @@ func (c *Client) ScheduleTransferRuns(ctx context.Context, req *datatransferpb.S } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ScheduleTransferRuns[0:len(c.CallOptions.ScheduleTransferRuns):len(c.CallOptions.ScheduleTransferRuns)], opts...) + opts = append((*c.CallOptions).ScheduleTransferRuns[0:len((*c.CallOptions).ScheduleTransferRuns):len((*c.CallOptions).ScheduleTransferRuns)], opts...) var resp *datatransferpb.ScheduleTransferRunsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -494,14 +627,10 @@ func (c *Client) ScheduleTransferRuns(ctx context.Context, req *datatransferpb.S return resp, nil } -// StartManualTransferRuns start manual transfer runs to be executed now with schedule_time equal to -// current time. The transfer runs can be created for a time range where the -// run_time is between start_time (inclusive) and end_time (exclusive), or for -// a specific run_time. -func (c *Client) StartManualTransferRuns(ctx context.Context, req *datatransferpb.StartManualTransferRunsRequest, opts ...gax.CallOption) (*datatransferpb.StartManualTransferRunsResponse, error) { +func (c *gRPCClient) StartManualTransferRuns(ctx context.Context, req *datatransferpb.StartManualTransferRunsRequest, opts ...gax.CallOption) (*datatransferpb.StartManualTransferRunsResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.StartManualTransferRuns[0:len(c.CallOptions.StartManualTransferRuns):len(c.CallOptions.StartManualTransferRuns)], opts...) + opts = append((*c.CallOptions).StartManualTransferRuns[0:len((*c.CallOptions).StartManualTransferRuns):len((*c.CallOptions).StartManualTransferRuns)], opts...) var resp *datatransferpb.StartManualTransferRunsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -514,8 +643,7 @@ func (c *Client) StartManualTransferRuns(ctx context.Context, req *datatransferp return resp, nil } -// GetTransferRun returns information about the particular transfer run. -func (c *Client) GetTransferRun(ctx context.Context, req *datatransferpb.GetTransferRunRequest, opts ...gax.CallOption) (*datatransferpb.TransferRun, error) { +func (c *gRPCClient) GetTransferRun(ctx context.Context, req *datatransferpb.GetTransferRunRequest, opts ...gax.CallOption) (*datatransferpb.TransferRun, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -523,7 +651,7 @@ func (c *Client) GetTransferRun(ctx context.Context, req *datatransferpb.GetTran } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTransferRun[0:len(c.CallOptions.GetTransferRun):len(c.CallOptions.GetTransferRun)], opts...) + opts = append((*c.CallOptions).GetTransferRun[0:len((*c.CallOptions).GetTransferRun):len((*c.CallOptions).GetTransferRun)], opts...) var resp *datatransferpb.TransferRun err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -536,8 +664,7 @@ func (c *Client) GetTransferRun(ctx context.Context, req *datatransferpb.GetTran return resp, nil } -// DeleteTransferRun deletes the specified transfer run. -func (c *Client) DeleteTransferRun(ctx context.Context, req *datatransferpb.DeleteTransferRunRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteTransferRun(ctx context.Context, req *datatransferpb.DeleteTransferRunRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -545,7 +672,7 @@ func (c *Client) DeleteTransferRun(ctx context.Context, req *datatransferpb.Dele } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTransferRun[0:len(c.CallOptions.DeleteTransferRun):len(c.CallOptions.DeleteTransferRun)], opts...) + opts = append((*c.CallOptions).DeleteTransferRun[0:len((*c.CallOptions).DeleteTransferRun):len((*c.CallOptions).DeleteTransferRun)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteTransferRun(ctx, req, settings.GRPC...) @@ -554,11 +681,10 @@ func (c *Client) DeleteTransferRun(ctx context.Context, req *datatransferpb.Dele return err } -// ListTransferRuns returns information about running and completed jobs. -func (c *Client) ListTransferRuns(ctx context.Context, req *datatransferpb.ListTransferRunsRequest, opts ...gax.CallOption) *TransferRunIterator { +func (c *gRPCClient) ListTransferRuns(ctx context.Context, req *datatransferpb.ListTransferRunsRequest, opts ...gax.CallOption) *TransferRunIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTransferRuns[0:len(c.CallOptions.ListTransferRuns):len(c.CallOptions.ListTransferRuns)], opts...) + opts = append((*c.CallOptions).ListTransferRuns[0:len((*c.CallOptions).ListTransferRuns):len((*c.CallOptions).ListTransferRuns)], opts...) it := &TransferRunIterator{} req = proto.Clone(req).(*datatransferpb.ListTransferRunsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datatransferpb.TransferRun, string, error) { @@ -595,11 +721,10 @@ func (c *Client) ListTransferRuns(ctx context.Context, req *datatransferpb.ListT return it } -// ListTransferLogs returns user facing log messages for the data transfer run. -func (c *Client) ListTransferLogs(ctx context.Context, req *datatransferpb.ListTransferLogsRequest, opts ...gax.CallOption) *TransferMessageIterator { +func (c *gRPCClient) ListTransferLogs(ctx context.Context, req *datatransferpb.ListTransferLogsRequest, opts ...gax.CallOption) *TransferMessageIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTransferLogs[0:len(c.CallOptions.ListTransferLogs):len(c.CallOptions.ListTransferLogs)], opts...) + opts = append((*c.CallOptions).ListTransferLogs[0:len((*c.CallOptions).ListTransferLogs):len((*c.CallOptions).ListTransferLogs)], opts...) it := &TransferMessageIterator{} req = proto.Clone(req).(*datatransferpb.ListTransferLogsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datatransferpb.TransferMessage, string, error) { @@ -636,13 +761,7 @@ func (c *Client) ListTransferLogs(ctx context.Context, req *datatransferpb.ListT return it } -// CheckValidCreds returns true if valid credentials exist for the given data source and -// requesting user. -// Some data sources doesn’t support service account, so we need to talk to -// them on behalf of the end user. This API just checks whether we have OAuth -// token for the particular user, which is a pre-requisite before user can -// create a transfer config. -func (c *Client) CheckValidCreds(ctx context.Context, req *datatransferpb.CheckValidCredsRequest, opts ...gax.CallOption) (*datatransferpb.CheckValidCredsResponse, error) { +func (c *gRPCClient) CheckValidCreds(ctx context.Context, req *datatransferpb.CheckValidCredsRequest, opts ...gax.CallOption) (*datatransferpb.CheckValidCredsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -650,7 +769,7 @@ func (c *Client) CheckValidCreds(ctx context.Context, req *datatransferpb.CheckV } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CheckValidCreds[0:len(c.CallOptions.CheckValidCreds):len(c.CallOptions.CheckValidCreds)], opts...) + opts = append((*c.CallOptions).CheckValidCreds[0:len((*c.CallOptions).CheckValidCreds):len((*c.CallOptions).CheckValidCreds)], opts...) var resp *datatransferpb.CheckValidCredsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/bigquery/datatransfer/apiv1/data_transfer_client_example_test.go b/bigquery/datatransfer/apiv1/data_transfer_client_example_test.go index 846f243c3cb7..8698c04720dc 100644 --- a/bigquery/datatransfer/apiv1/data_transfer_client_example_test.go +++ b/bigquery/datatransfer/apiv1/data_transfer_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_GetDataSource() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.GetDataSourceRequest{ // TODO: Fill request struct fields. @@ -55,14 +56,12 @@ func ExampleClient_GetDataSource() { } func ExampleClient_ListDataSources() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.ListDataSourcesRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleClient_ListDataSources() { } func ExampleClient_CreateTransferConfig() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.CreateTransferConfigRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleClient_CreateTransferConfig() { } func ExampleClient_UpdateTransferConfig() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.UpdateTransferConfigRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleClient_DeleteTransferConfig() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.DeleteTransferConfigRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleClient_DeleteTransferConfig() { } func ExampleClient_GetTransferConfig() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.GetTransferConfigRequest{ // TODO: Fill request struct fields. @@ -158,14 +155,12 @@ func ExampleClient_GetTransferConfig() { } func ExampleClient_ListTransferConfigs() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.ListTransferConfigsRequest{ // TODO: Fill request struct fields. @@ -185,13 +180,12 @@ func ExampleClient_ListTransferConfigs() { } func ExampleClient_ScheduleTransferRuns() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.ScheduleTransferRunsRequest{ // TODO: Fill request struct fields. @@ -205,13 +199,12 @@ func ExampleClient_ScheduleTransferRuns() { } func ExampleClient_StartManualTransferRuns() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.StartManualTransferRunsRequest{ // TODO: Fill request struct fields. @@ -225,13 +218,12 @@ func ExampleClient_StartManualTransferRuns() { } func ExampleClient_GetTransferRun() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.GetTransferRunRequest{ // TODO: Fill request struct fields. @@ -250,6 +242,7 @@ func ExampleClient_DeleteTransferRun() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.DeleteTransferRunRequest{ // TODO: Fill request struct fields. @@ -261,14 +254,12 @@ func ExampleClient_DeleteTransferRun() { } func ExampleClient_ListTransferRuns() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.ListTransferRunsRequest{ // TODO: Fill request struct fields. @@ -288,14 +279,12 @@ func ExampleClient_ListTransferRuns() { } func ExampleClient_ListTransferLogs() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.ListTransferLogsRequest{ // TODO: Fill request struct fields. @@ -315,13 +304,12 @@ func ExampleClient_ListTransferLogs() { } func ExampleClient_CheckValidCreds() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.CheckValidCredsRequest{ // TODO: Fill request struct fields. diff --git a/bigquery/datatransfer/apiv1/doc.go b/bigquery/datatransfer/apiv1/doc.go index c0c2f28ea01e..d92d6593222e 100644 --- a/bigquery/datatransfer/apiv1/doc.go +++ b/bigquery/datatransfer/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package datatransfer // import "cloud.google.com/go/bigquery/datatransfer/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/bigquery/go.mod b/bigquery/go.mod index f35c62934c70..eed7d0905183 100644 --- a/bigquery/go.mod +++ b/bigquery/go.mod @@ -9,7 +9,7 @@ require ( github.com/google/go-cmp v0.5.5 github.com/googleapis/gax-go/v2 v2.0.5 golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 - google.golang.org/api v0.46.0 - google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a + google.golang.org/api v0.47.0 + google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d google.golang.org/grpc v1.37.1 ) diff --git a/bigquery/go.sum b/bigquery/go.sum index c8d3dd45bbe2..1face245df93 100644 --- a/bigquery/go.sum +++ b/bigquery/go.sum @@ -147,6 +147,7 @@ github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -182,8 +183,9 @@ golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5 h1:2M3HP5CCK1Si9FQhwnzYhXdG6DXeebvUHFpre8QvbyI= golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 h1:VLliZ0d+/avPrXXH+OakdXhpJuEoBZuwh1m2j7U6Iug= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= @@ -193,8 +195,9 @@ golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.1 h1:Kvvh58BN8Y9/lBi7hTekvtMpm07eUZ0ck5pRHpsMWrY= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -228,6 +231,7 @@ golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420 h1:a8jGStKg0XqKDlKqjLrXn0ioF5MH36pT7Z0BRTqLhbk= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -241,8 +245,8 @@ golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210427180440-81ed05c6b58c h1:SgVl/sCtkicsS7psKkje4H9YtjdEl3xsYh7N+5TDHqY= -golang.org/x/oauth2 v0.0.0-20210427180440-81ed05c6b58c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c h1:pkQiBZBvdos9qq4wBAHqlzuZHEXo07pqV06ef90u1WI= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -289,9 +293,11 @@ golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210503080704-8803ae5d1324 h1:pAwJxDByZctfPwzlNGrDN2BQLsdPb9NkhoTJtUkAO28= -golang.org/x/sys v0.0.0-20210503080704-8803ae5d1324/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015 h1:hZR0X1kPW+nwyJ9xRxqZk1vx5RUObAPBdKVvXPDUH/E= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -350,8 +356,9 @@ golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.0 h1:po9/4sTYwZU9lPhi1tOrb4hCv3qrhiQ77LZfGa2OjwY= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.1 h1:wGiQel/hW0NnEkJUk8lbzkX2gFJU6PFxf1v5OlCfuOs= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -378,8 +385,8 @@ google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34q google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= -google.golang.org/api v0.46.0 h1:jkDWHOBIoNSD0OQpq4rtBVu+Rh325MPjXG1rakAp8JU= -google.golang.org/api v0.46.0/go.mod h1:ceL4oozhkAiTID8XMmJBsIxID/9wMXJVVFXPg4ylg3I= +google.golang.org/api v0.47.0 h1:sQLWZQvP6jPGIP4JGPkJu4zHswrv81iobiyszr3b/0I= +google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -427,9 +434,9 @@ google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= -google.golang.org/genproto v0.0.0-20210429181445-86c259c2b4ab/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= -google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a h1:VA0wtJaR+W1I11P2f535J7D/YxyvEFMTMvcmyeZ9FBE= -google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d h1:bRz6UmsZEz/CzoTjUDp4ZcdguhSWi6CyU299wMQBpZU= +google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= @@ -448,7 +455,6 @@ google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA5 google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.37.1 h1:ARnQJNWxGyYJpdf/JXscNlQr/uv607ZPU9Z7ogHi+iI= google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= diff --git a/bigquery/reservation/apiv1/doc.go b/bigquery/reservation/apiv1/doc.go index 8ebc2485516c..41af7c14a006 100644 --- a/bigquery/reservation/apiv1/doc.go +++ b/bigquery/reservation/apiv1/doc.go @@ -28,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package reservation // import "cloud.google.com/go/bigquery/reservation/apiv1" import ( @@ -48,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/bigquery/reservation/apiv1/reservation_client.go b/bigquery/reservation/apiv1/reservation_client.go index db3d4e0512b0..e28864f4fa3e 100644 --- a/bigquery/reservation/apiv1/reservation_client.go +++ b/bigquery/reservation/apiv1/reservation_client.go @@ -60,7 +60,7 @@ type CallOptions struct { UpdateBiReservation []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("bigqueryreservation.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("bigqueryreservation.mtls.googleapis.com:443"), @@ -206,27 +206,325 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from BigQuery Reservation API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateReservation(context.Context, *reservationpb.CreateReservationRequest, ...gax.CallOption) (*reservationpb.Reservation, error) + ListReservations(context.Context, *reservationpb.ListReservationsRequest, ...gax.CallOption) *ReservationIterator + GetReservation(context.Context, *reservationpb.GetReservationRequest, ...gax.CallOption) (*reservationpb.Reservation, error) + DeleteReservation(context.Context, *reservationpb.DeleteReservationRequest, ...gax.CallOption) error + UpdateReservation(context.Context, *reservationpb.UpdateReservationRequest, ...gax.CallOption) (*reservationpb.Reservation, error) + CreateCapacityCommitment(context.Context, *reservationpb.CreateCapacityCommitmentRequest, ...gax.CallOption) (*reservationpb.CapacityCommitment, error) + ListCapacityCommitments(context.Context, *reservationpb.ListCapacityCommitmentsRequest, ...gax.CallOption) *CapacityCommitmentIterator + GetCapacityCommitment(context.Context, *reservationpb.GetCapacityCommitmentRequest, ...gax.CallOption) (*reservationpb.CapacityCommitment, error) + DeleteCapacityCommitment(context.Context, *reservationpb.DeleteCapacityCommitmentRequest, ...gax.CallOption) error + UpdateCapacityCommitment(context.Context, *reservationpb.UpdateCapacityCommitmentRequest, ...gax.CallOption) (*reservationpb.CapacityCommitment, error) + SplitCapacityCommitment(context.Context, *reservationpb.SplitCapacityCommitmentRequest, ...gax.CallOption) (*reservationpb.SplitCapacityCommitmentResponse, error) + MergeCapacityCommitments(context.Context, *reservationpb.MergeCapacityCommitmentsRequest, ...gax.CallOption) (*reservationpb.CapacityCommitment, error) + CreateAssignment(context.Context, *reservationpb.CreateAssignmentRequest, ...gax.CallOption) (*reservationpb.Assignment, error) + ListAssignments(context.Context, *reservationpb.ListAssignmentsRequest, ...gax.CallOption) *AssignmentIterator + DeleteAssignment(context.Context, *reservationpb.DeleteAssignmentRequest, ...gax.CallOption) error + SearchAssignments(context.Context, *reservationpb.SearchAssignmentsRequest, ...gax.CallOption) *AssignmentIterator + MoveAssignment(context.Context, *reservationpb.MoveAssignmentRequest, ...gax.CallOption) (*reservationpb.Assignment, error) + GetBiReservation(context.Context, *reservationpb.GetBiReservationRequest, ...gax.CallOption) (*reservationpb.BiReservation, error) + UpdateBiReservation(context.Context, *reservationpb.UpdateBiReservationRequest, ...gax.CallOption) (*reservationpb.BiReservation, error) +} + // Client is a client for interacting with BigQuery Reservation API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// This API allows users to manage their flat-rate BigQuery reservations. +// +// A reservation provides computational resource guarantees, in the form of +// slots (at https://cloud.google.com/bigquery/docs/slots), to users. A slot is a +// unit of computational power in BigQuery, and serves as the basic unit of +// parallelism. In a scan of a multi-partitioned table, a single slot operates +// on a single partition of the table. A reservation resource exists as a child +// resource of the admin project and location, e.g.: +// projects/myproject/locations/US/reservations/reservationName. +// +// A capacity commitment is a way to purchase compute capacity for BigQuery jobs +// (in the form of slots) with some committed period of usage. A capacity +// commitment resource exists as a child resource of the admin project and +// location, e.g.: +// projects/myproject/locations/US/capacityCommitments/id. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateReservation creates a new reservation resource. +func (c *Client) CreateReservation(ctx context.Context, req *reservationpb.CreateReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { + return c.internalClient.CreateReservation(ctx, req, opts...) +} + +// ListReservations lists all the reservations for the project in the specified location. +func (c *Client) ListReservations(ctx context.Context, req *reservationpb.ListReservationsRequest, opts ...gax.CallOption) *ReservationIterator { + return c.internalClient.ListReservations(ctx, req, opts...) +} + +// GetReservation returns information about the reservation. +func (c *Client) GetReservation(ctx context.Context, req *reservationpb.GetReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { + return c.internalClient.GetReservation(ctx, req, opts...) +} + +// DeleteReservation deletes a reservation. +// Returns google.rpc.Code.FAILED_PRECONDITION when reservation has +// assignments. +func (c *Client) DeleteReservation(ctx context.Context, req *reservationpb.DeleteReservationRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteReservation(ctx, req, opts...) +} + +// UpdateReservation updates an existing reservation resource. +func (c *Client) UpdateReservation(ctx context.Context, req *reservationpb.UpdateReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { + return c.internalClient.UpdateReservation(ctx, req, opts...) +} + +// CreateCapacityCommitment creates a new capacity commitment resource. +func (c *Client) CreateCapacityCommitment(ctx context.Context, req *reservationpb.CreateCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { + return c.internalClient.CreateCapacityCommitment(ctx, req, opts...) +} + +// ListCapacityCommitments lists all the capacity commitments for the admin project. +func (c *Client) ListCapacityCommitments(ctx context.Context, req *reservationpb.ListCapacityCommitmentsRequest, opts ...gax.CallOption) *CapacityCommitmentIterator { + return c.internalClient.ListCapacityCommitments(ctx, req, opts...) +} + +// GetCapacityCommitment returns information about the capacity commitment. +func (c *Client) GetCapacityCommitment(ctx context.Context, req *reservationpb.GetCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { + return c.internalClient.GetCapacityCommitment(ctx, req, opts...) +} + +// DeleteCapacityCommitment deletes a capacity commitment. Attempting to delete capacity commitment +// before its commitment_end_time will fail with the error code +// google.rpc.Code.FAILED_PRECONDITION. +func (c *Client) DeleteCapacityCommitment(ctx context.Context, req *reservationpb.DeleteCapacityCommitmentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteCapacityCommitment(ctx, req, opts...) +} + +// UpdateCapacityCommitment updates an existing capacity commitment. +// +// Only plan and renewal_plan fields can be updated. +// +// Plan can only be changed to a plan of a longer commitment period. +// Attempting to change to a plan with shorter commitment period will fail +// with the error code google.rpc.Code.FAILED_PRECONDITION. +func (c *Client) UpdateCapacityCommitment(ctx context.Context, req *reservationpb.UpdateCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { + return c.internalClient.UpdateCapacityCommitment(ctx, req, opts...) +} + +// SplitCapacityCommitment splits capacity commitment to two commitments of the same plan and +// commitment_end_time. +// +// A common use case is to enable downgrading commitments. +// +// For example, in order to downgrade from 10000 slots to 8000, you might +// split a 10000 capacity commitment into commitments of 2000 and 8000. Then, +// you would change the plan of the first one to FLEX and then delete it. +func (c *Client) SplitCapacityCommitment(ctx context.Context, req *reservationpb.SplitCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.SplitCapacityCommitmentResponse, error) { + return c.internalClient.SplitCapacityCommitment(ctx, req, opts...) +} + +// MergeCapacityCommitments merges capacity commitments of the same plan into a single commitment. +// +// The resulting capacity commitment has the greater commitment_end_time +// out of the to-be-merged capacity commitments. +// +// Attempting to merge capacity commitments of different plan will fail +// with the error code google.rpc.Code.FAILED_PRECONDITION. +func (c *Client) MergeCapacityCommitments(ctx context.Context, req *reservationpb.MergeCapacityCommitmentsRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { + return c.internalClient.MergeCapacityCommitments(ctx, req, opts...) +} + +// CreateAssignment creates an assignment object which allows the given project to submit jobs +// of a certain type using slots from the specified reservation. +// +// Currently a +// resource (project, folder, organization) can only have one assignment per +// each (job_type, location) combination, and that reservation will be used +// for all jobs of the matching type. +// +// Different assignments can be created on different levels of the +// projects, folders or organization hierarchy. During query execution, +// the assignment is looked up at the project, folder and organization levels +// in that order. The first assignment found is applied to the query. +// +// When creating assignments, it does not matter if other assignments exist at +// higher levels. +// +// Example: +// +// The organization organizationA contains two projects, project1 +// and project2. +// +// Assignments for all three entities (organizationA, project1, and +// project2) could all be created and mapped to the same or different +// reservations. +// +// Returns google.rpc.Code.PERMISSION_DENIED if user does not have +// ‘bigquery.admin’ permissions on the project using the reservation +// and the project that owns this reservation. +// +// Returns google.rpc.Code.INVALID_ARGUMENT when location of the assignment +// does not match location of the reservation. +func (c *Client) CreateAssignment(ctx context.Context, req *reservationpb.CreateAssignmentRequest, opts ...gax.CallOption) (*reservationpb.Assignment, error) { + return c.internalClient.CreateAssignment(ctx, req, opts...) +} + +// ListAssignments lists assignments. +// +// Only explicitly created assignments will be returned. +// +// Example: +// +// Organization organizationA contains two projects, project1 and +// project2. +// +// Reservation res1 exists and was created previously. +// +// CreateAssignment was used previously to define the following +// associations between entities and reservations: +// and +// +// In this example, ListAssignments will just return the above two assignments +// for reservation res1, and no expansion/merge will happen. +// +// The wildcard “-” can be used for +// reservations in the request. In that case all assignments belongs to the +// specified project and location will be listed. +// +// Note "-" cannot be used for projects nor locations. +func (c *Client) ListAssignments(ctx context.Context, req *reservationpb.ListAssignmentsRequest, opts ...gax.CallOption) *AssignmentIterator { + return c.internalClient.ListAssignments(ctx, req, opts...) +} + +// DeleteAssignment deletes a assignment. No expansion will happen. +// +// Example: +// +// Organization organizationA contains two projects, project1 and +// project2. +// +// Reservation res1 exists and was created previously. +// +// CreateAssignment was used previously to define the following +// associations between entities and reservations: +// and +// +// In this example, deletion of the assignment won’t +// affect the other assignment . After said deletion, +// queries from project1 will still use res1 while queries from +// project2 will switch to use on-demand mode. +func (c *Client) DeleteAssignment(ctx context.Context, req *reservationpb.DeleteAssignmentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteAssignment(ctx, req, opts...) +} + +// SearchAssignments looks up assignments for a specified resource for a particular region. +// If the request is about a project: +// +// Assignments created on the project will be returned if they exist. +// +// Otherwise assignments created on the closest ancestor will be +// returned. +// +// Assignments for different JobTypes will all be returned. +// +// The same logic applies if the request is about a folder. +// +// If the request is about an organization, then assignments created on the +// organization will be returned (organization doesn’t have ancestors). +// +// Comparing to ListAssignments, there are some behavior +// differences: +// +// permission on the assignee will be verified in this API. +// +// Hierarchy lookup (project->folder->organization) happens in this API. +// +// Parent here is projects/*/locations/*, instead of +// projects/*/locations/*reservations/*. +// +// Note "-" cannot be used for projects +// nor locations. +func (c *Client) SearchAssignments(ctx context.Context, req *reservationpb.SearchAssignmentsRequest, opts ...gax.CallOption) *AssignmentIterator { + return c.internalClient.SearchAssignments(ctx, req, opts...) +} + +// MoveAssignment moves an assignment under a new reservation. +// +// This differs from removing an existing assignment and recreating a new one +// by providing a transactional change that ensures an assignee always has an +// associated reservation. +func (c *Client) MoveAssignment(ctx context.Context, req *reservationpb.MoveAssignmentRequest, opts ...gax.CallOption) (*reservationpb.Assignment, error) { + return c.internalClient.MoveAssignment(ctx, req, opts...) +} + +// GetBiReservation retrieves a BI reservation. +func (c *Client) GetBiReservation(ctx context.Context, req *reservationpb.GetBiReservationRequest, opts ...gax.CallOption) (*reservationpb.BiReservation, error) { + return c.internalClient.GetBiReservation(ctx, req, opts...) +} + +// UpdateBiReservation updates a BI reservation. +// +// Only fields specified in the field_mask are updated. +// +// A singleton BI reservation always exists with default size 0. +// In order to reserve BI capacity it needs to be updated to an amount +// greater than 0. In order to release BI capacity reservation size +// must be set to 0. +func (c *Client) UpdateBiReservation(ctx context.Context, req *reservationpb.UpdateBiReservationRequest, opts ...gax.CallOption) (*reservationpb.BiReservation, error) { + return c.internalClient.UpdateBiReservation(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with BigQuery Reservation API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client reservationpb.ReservationServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new reservation service client. +// NewClient creates a new reservation service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // This API allows users to manage their flat-rate BigQuery reservations. // @@ -244,8 +542,7 @@ type Client struct { // location, e.g.: // projects/myproject/locations/US/capacityCommitments/id. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -263,42 +560,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: reservationpb.NewReservationServiceClient(connPool), + client: reservationpb.NewReservationServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateReservation creates a new reservation resource. -func (c *Client) CreateReservation(ctx context.Context, req *reservationpb.CreateReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateReservation(ctx context.Context, req *reservationpb.CreateReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -306,7 +605,7 @@ func (c *Client) CreateReservation(ctx context.Context, req *reservationpb.Creat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateReservation[0:len(c.CallOptions.CreateReservation):len(c.CallOptions.CreateReservation)], opts...) + opts = append((*c.CallOptions).CreateReservation[0:len((*c.CallOptions).CreateReservation):len((*c.CallOptions).CreateReservation)], opts...) var resp *reservationpb.Reservation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -319,11 +618,10 @@ func (c *Client) CreateReservation(ctx context.Context, req *reservationpb.Creat return resp, nil } -// ListReservations lists all the reservations for the project in the specified location. -func (c *Client) ListReservations(ctx context.Context, req *reservationpb.ListReservationsRequest, opts ...gax.CallOption) *ReservationIterator { +func (c *gRPCClient) ListReservations(ctx context.Context, req *reservationpb.ListReservationsRequest, opts ...gax.CallOption) *ReservationIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListReservations[0:len(c.CallOptions.ListReservations):len(c.CallOptions.ListReservations)], opts...) + opts = append((*c.CallOptions).ListReservations[0:len((*c.CallOptions).ListReservations):len((*c.CallOptions).ListReservations)], opts...) it := &ReservationIterator{} req = proto.Clone(req).(*reservationpb.ListReservationsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*reservationpb.Reservation, string, error) { @@ -360,8 +658,7 @@ func (c *Client) ListReservations(ctx context.Context, req *reservationpb.ListRe return it } -// GetReservation returns information about the reservation. -func (c *Client) GetReservation(ctx context.Context, req *reservationpb.GetReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { +func (c *gRPCClient) GetReservation(ctx context.Context, req *reservationpb.GetReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -369,7 +666,7 @@ func (c *Client) GetReservation(ctx context.Context, req *reservationpb.GetReser } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetReservation[0:len(c.CallOptions.GetReservation):len(c.CallOptions.GetReservation)], opts...) + opts = append((*c.CallOptions).GetReservation[0:len((*c.CallOptions).GetReservation):len((*c.CallOptions).GetReservation)], opts...) var resp *reservationpb.Reservation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -382,10 +679,7 @@ func (c *Client) GetReservation(ctx context.Context, req *reservationpb.GetReser return resp, nil } -// DeleteReservation deletes a reservation. -// Returns google.rpc.Code.FAILED_PRECONDITION when reservation has -// assignments. -func (c *Client) DeleteReservation(ctx context.Context, req *reservationpb.DeleteReservationRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteReservation(ctx context.Context, req *reservationpb.DeleteReservationRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -393,7 +687,7 @@ func (c *Client) DeleteReservation(ctx context.Context, req *reservationpb.Delet } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteReservation[0:len(c.CallOptions.DeleteReservation):len(c.CallOptions.DeleteReservation)], opts...) + opts = append((*c.CallOptions).DeleteReservation[0:len((*c.CallOptions).DeleteReservation):len((*c.CallOptions).DeleteReservation)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteReservation(ctx, req, settings.GRPC...) @@ -402,8 +696,7 @@ func (c *Client) DeleteReservation(ctx context.Context, req *reservationpb.Delet return err } -// UpdateReservation updates an existing reservation resource. -func (c *Client) UpdateReservation(ctx context.Context, req *reservationpb.UpdateReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { +func (c *gRPCClient) UpdateReservation(ctx context.Context, req *reservationpb.UpdateReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -411,7 +704,7 @@ func (c *Client) UpdateReservation(ctx context.Context, req *reservationpb.Updat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "reservation.name", url.QueryEscape(req.GetReservation().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateReservation[0:len(c.CallOptions.UpdateReservation):len(c.CallOptions.UpdateReservation)], opts...) + opts = append((*c.CallOptions).UpdateReservation[0:len((*c.CallOptions).UpdateReservation):len((*c.CallOptions).UpdateReservation)], opts...) var resp *reservationpb.Reservation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -424,8 +717,7 @@ func (c *Client) UpdateReservation(ctx context.Context, req *reservationpb.Updat return resp, nil } -// CreateCapacityCommitment creates a new capacity commitment resource. -func (c *Client) CreateCapacityCommitment(ctx context.Context, req *reservationpb.CreateCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { +func (c *gRPCClient) CreateCapacityCommitment(ctx context.Context, req *reservationpb.CreateCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -433,7 +725,7 @@ func (c *Client) CreateCapacityCommitment(ctx context.Context, req *reservationp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCapacityCommitment[0:len(c.CallOptions.CreateCapacityCommitment):len(c.CallOptions.CreateCapacityCommitment)], opts...) + opts = append((*c.CallOptions).CreateCapacityCommitment[0:len((*c.CallOptions).CreateCapacityCommitment):len((*c.CallOptions).CreateCapacityCommitment)], opts...) var resp *reservationpb.CapacityCommitment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -446,11 +738,10 @@ func (c *Client) CreateCapacityCommitment(ctx context.Context, req *reservationp return resp, nil } -// ListCapacityCommitments lists all the capacity commitments for the admin project. -func (c *Client) ListCapacityCommitments(ctx context.Context, req *reservationpb.ListCapacityCommitmentsRequest, opts ...gax.CallOption) *CapacityCommitmentIterator { +func (c *gRPCClient) ListCapacityCommitments(ctx context.Context, req *reservationpb.ListCapacityCommitmentsRequest, opts ...gax.CallOption) *CapacityCommitmentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCapacityCommitments[0:len(c.CallOptions.ListCapacityCommitments):len(c.CallOptions.ListCapacityCommitments)], opts...) + opts = append((*c.CallOptions).ListCapacityCommitments[0:len((*c.CallOptions).ListCapacityCommitments):len((*c.CallOptions).ListCapacityCommitments)], opts...) it := &CapacityCommitmentIterator{} req = proto.Clone(req).(*reservationpb.ListCapacityCommitmentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*reservationpb.CapacityCommitment, string, error) { @@ -487,8 +778,7 @@ func (c *Client) ListCapacityCommitments(ctx context.Context, req *reservationpb return it } -// GetCapacityCommitment returns information about the capacity commitment. -func (c *Client) GetCapacityCommitment(ctx context.Context, req *reservationpb.GetCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { +func (c *gRPCClient) GetCapacityCommitment(ctx context.Context, req *reservationpb.GetCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -496,7 +786,7 @@ func (c *Client) GetCapacityCommitment(ctx context.Context, req *reservationpb.G } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCapacityCommitment[0:len(c.CallOptions.GetCapacityCommitment):len(c.CallOptions.GetCapacityCommitment)], opts...) + opts = append((*c.CallOptions).GetCapacityCommitment[0:len((*c.CallOptions).GetCapacityCommitment):len((*c.CallOptions).GetCapacityCommitment)], opts...) var resp *reservationpb.CapacityCommitment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -509,10 +799,7 @@ func (c *Client) GetCapacityCommitment(ctx context.Context, req *reservationpb.G return resp, nil } -// DeleteCapacityCommitment deletes a capacity commitment. Attempting to delete capacity commitment -// before its commitment_end_time will fail with the error code -// google.rpc.Code.FAILED_PRECONDITION. -func (c *Client) DeleteCapacityCommitment(ctx context.Context, req *reservationpb.DeleteCapacityCommitmentRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteCapacityCommitment(ctx context.Context, req *reservationpb.DeleteCapacityCommitmentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -520,7 +807,7 @@ func (c *Client) DeleteCapacityCommitment(ctx context.Context, req *reservationp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteCapacityCommitment[0:len(c.CallOptions.DeleteCapacityCommitment):len(c.CallOptions.DeleteCapacityCommitment)], opts...) + opts = append((*c.CallOptions).DeleteCapacityCommitment[0:len((*c.CallOptions).DeleteCapacityCommitment):len((*c.CallOptions).DeleteCapacityCommitment)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteCapacityCommitment(ctx, req, settings.GRPC...) @@ -529,14 +816,7 @@ func (c *Client) DeleteCapacityCommitment(ctx context.Context, req *reservationp return err } -// UpdateCapacityCommitment updates an existing capacity commitment. -// -// Only plan and renewal_plan fields can be updated. -// -// Plan can only be changed to a plan of a longer commitment period. -// Attempting to change to a plan with shorter commitment period will fail -// with the error code google.rpc.Code.FAILED_PRECONDITION. -func (c *Client) UpdateCapacityCommitment(ctx context.Context, req *reservationpb.UpdateCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { +func (c *gRPCClient) UpdateCapacityCommitment(ctx context.Context, req *reservationpb.UpdateCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -544,7 +824,7 @@ func (c *Client) UpdateCapacityCommitment(ctx context.Context, req *reservationp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "capacity_commitment.name", url.QueryEscape(req.GetCapacityCommitment().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCapacityCommitment[0:len(c.CallOptions.UpdateCapacityCommitment):len(c.CallOptions.UpdateCapacityCommitment)], opts...) + opts = append((*c.CallOptions).UpdateCapacityCommitment[0:len((*c.CallOptions).UpdateCapacityCommitment):len((*c.CallOptions).UpdateCapacityCommitment)], opts...) var resp *reservationpb.CapacityCommitment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -557,15 +837,7 @@ func (c *Client) UpdateCapacityCommitment(ctx context.Context, req *reservationp return resp, nil } -// SplitCapacityCommitment splits capacity commitment to two commitments of the same plan and -// commitment_end_time. -// -// A common use case is to enable downgrading commitments. -// -// For example, in order to downgrade from 10000 slots to 8000, you might -// split a 10000 capacity commitment into commitments of 2000 and 8000. Then, -// you would change the plan of the first one to FLEX and then delete it. -func (c *Client) SplitCapacityCommitment(ctx context.Context, req *reservationpb.SplitCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.SplitCapacityCommitmentResponse, error) { +func (c *gRPCClient) SplitCapacityCommitment(ctx context.Context, req *reservationpb.SplitCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.SplitCapacityCommitmentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -573,7 +845,7 @@ func (c *Client) SplitCapacityCommitment(ctx context.Context, req *reservationpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SplitCapacityCommitment[0:len(c.CallOptions.SplitCapacityCommitment):len(c.CallOptions.SplitCapacityCommitment)], opts...) + opts = append((*c.CallOptions).SplitCapacityCommitment[0:len((*c.CallOptions).SplitCapacityCommitment):len((*c.CallOptions).SplitCapacityCommitment)], opts...) var resp *reservationpb.SplitCapacityCommitmentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -586,14 +858,7 @@ func (c *Client) SplitCapacityCommitment(ctx context.Context, req *reservationpb return resp, nil } -// MergeCapacityCommitments merges capacity commitments of the same plan into a single commitment. -// -// The resulting capacity commitment has the greater commitment_end_time -// out of the to-be-merged capacity commitments. -// -// Attempting to merge capacity commitments of different plan will fail -// with the error code google.rpc.Code.FAILED_PRECONDITION. -func (c *Client) MergeCapacityCommitments(ctx context.Context, req *reservationpb.MergeCapacityCommitmentsRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { +func (c *gRPCClient) MergeCapacityCommitments(ctx context.Context, req *reservationpb.MergeCapacityCommitmentsRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -601,7 +866,7 @@ func (c *Client) MergeCapacityCommitments(ctx context.Context, req *reservationp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.MergeCapacityCommitments[0:len(c.CallOptions.MergeCapacityCommitments):len(c.CallOptions.MergeCapacityCommitments)], opts...) + opts = append((*c.CallOptions).MergeCapacityCommitments[0:len((*c.CallOptions).MergeCapacityCommitments):len((*c.CallOptions).MergeCapacityCommitments)], opts...) var resp *reservationpb.CapacityCommitment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -614,38 +879,7 @@ func (c *Client) MergeCapacityCommitments(ctx context.Context, req *reservationp return resp, nil } -// CreateAssignment creates an assignment object which allows the given project to submit jobs -// of a certain type using slots from the specified reservation. -// -// Currently a -// resource (project, folder, organization) can only have one assignment per -// each (job_type, location) combination, and that reservation will be used -// for all jobs of the matching type. -// -// Different assignments can be created on different levels of the -// projects, folders or organization hierarchy. During query execution, -// the assignment is looked up at the project, folder and organization levels -// in that order. The first assignment found is applied to the query. -// -// When creating assignments, it does not matter if other assignments exist at -// higher levels. -// -// Example: -// -// The organization organizationA contains two projects, project1 -// and project2. -// -// Assignments for all three entities (organizationA, project1, and -// project2) could all be created and mapped to the same or different -// reservations. -// -// Returns google.rpc.Code.PERMISSION_DENIED if user does not have -// ‘bigquery.admin’ permissions on the project using the reservation -// and the project that owns this reservation. -// -// Returns google.rpc.Code.INVALID_ARGUMENT when location of the assignment -// does not match location of the reservation. -func (c *Client) CreateAssignment(ctx context.Context, req *reservationpb.CreateAssignmentRequest, opts ...gax.CallOption) (*reservationpb.Assignment, error) { +func (c *gRPCClient) CreateAssignment(ctx context.Context, req *reservationpb.CreateAssignmentRequest, opts ...gax.CallOption) (*reservationpb.Assignment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -653,7 +887,7 @@ func (c *Client) CreateAssignment(ctx context.Context, req *reservationpb.Create } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateAssignment[0:len(c.CallOptions.CreateAssignment):len(c.CallOptions.CreateAssignment)], opts...) + opts = append((*c.CallOptions).CreateAssignment[0:len((*c.CallOptions).CreateAssignment):len((*c.CallOptions).CreateAssignment)], opts...) var resp *reservationpb.Assignment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -666,33 +900,10 @@ func (c *Client) CreateAssignment(ctx context.Context, req *reservationpb.Create return resp, nil } -// ListAssignments lists assignments. -// -// Only explicitly created assignments will be returned. -// -// Example: -// -// Organization organizationA contains two projects, project1 and -// project2. -// -// Reservation res1 exists and was created previously. -// -// CreateAssignment was used previously to define the following -// associations between entities and reservations: -// and -// -// In this example, ListAssignments will just return the above two assignments -// for reservation res1, and no expansion/merge will happen. -// -// The wildcard “-” can be used for -// reservations in the request. In that case all assignments belongs to the -// specified project and location will be listed. -// -// Note "-" cannot be used for projects nor locations. -func (c *Client) ListAssignments(ctx context.Context, req *reservationpb.ListAssignmentsRequest, opts ...gax.CallOption) *AssignmentIterator { +func (c *gRPCClient) ListAssignments(ctx context.Context, req *reservationpb.ListAssignmentsRequest, opts ...gax.CallOption) *AssignmentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAssignments[0:len(c.CallOptions.ListAssignments):len(c.CallOptions.ListAssignments)], opts...) + opts = append((*c.CallOptions).ListAssignments[0:len((*c.CallOptions).ListAssignments):len((*c.CallOptions).ListAssignments)], opts...) it := &AssignmentIterator{} req = proto.Clone(req).(*reservationpb.ListAssignmentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*reservationpb.Assignment, string, error) { @@ -729,24 +940,7 @@ func (c *Client) ListAssignments(ctx context.Context, req *reservationpb.ListAss return it } -// DeleteAssignment deletes a assignment. No expansion will happen. -// -// Example: -// -// Organization organizationA contains two projects, project1 and -// project2. -// -// Reservation res1 exists and was created previously. -// -// CreateAssignment was used previously to define the following -// associations between entities and reservations: -// and -// -// In this example, deletion of the assignment won’t -// affect the other assignment . After said deletion, -// queries from project1 will still use res1 while queries from -// project2 will switch to use on-demand mode. -func (c *Client) DeleteAssignment(ctx context.Context, req *reservationpb.DeleteAssignmentRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteAssignment(ctx context.Context, req *reservationpb.DeleteAssignmentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -754,7 +948,7 @@ func (c *Client) DeleteAssignment(ctx context.Context, req *reservationpb.Delete } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteAssignment[0:len(c.CallOptions.DeleteAssignment):len(c.CallOptions.DeleteAssignment)], opts...) + opts = append((*c.CallOptions).DeleteAssignment[0:len((*c.CallOptions).DeleteAssignment):len((*c.CallOptions).DeleteAssignment)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteAssignment(ctx, req, settings.GRPC...) @@ -763,37 +957,10 @@ func (c *Client) DeleteAssignment(ctx context.Context, req *reservationpb.Delete return err } -// SearchAssignments looks up assignments for a specified resource for a particular region. -// If the request is about a project: -// -// Assignments created on the project will be returned if they exist. -// -// Otherwise assignments created on the closest ancestor will be -// returned. -// -// Assignments for different JobTypes will all be returned. -// -// The same logic applies if the request is about a folder. -// -// If the request is about an organization, then assignments created on the -// organization will be returned (organization doesn’t have ancestors). -// -// Comparing to ListAssignments, there are some behavior -// differences: -// -// permission on the assignee will be verified in this API. -// -// Hierarchy lookup (project->folder->organization) happens in this API. -// -// Parent here is projects/*/locations/*, instead of -// projects/*/locations/*reservations/*. -// -// Note "-" cannot be used for projects -// nor locations. -func (c *Client) SearchAssignments(ctx context.Context, req *reservationpb.SearchAssignmentsRequest, opts ...gax.CallOption) *AssignmentIterator { +func (c *gRPCClient) SearchAssignments(ctx context.Context, req *reservationpb.SearchAssignmentsRequest, opts ...gax.CallOption) *AssignmentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SearchAssignments[0:len(c.CallOptions.SearchAssignments):len(c.CallOptions.SearchAssignments)], opts...) + opts = append((*c.CallOptions).SearchAssignments[0:len((*c.CallOptions).SearchAssignments):len((*c.CallOptions).SearchAssignments)], opts...) it := &AssignmentIterator{} req = proto.Clone(req).(*reservationpb.SearchAssignmentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*reservationpb.Assignment, string, error) { @@ -830,12 +997,7 @@ func (c *Client) SearchAssignments(ctx context.Context, req *reservationpb.Searc return it } -// MoveAssignment moves an assignment under a new reservation. -// -// This differs from removing an existing assignment and recreating a new one -// by providing a transactional change that ensures an assignee always has an -// associated reservation. -func (c *Client) MoveAssignment(ctx context.Context, req *reservationpb.MoveAssignmentRequest, opts ...gax.CallOption) (*reservationpb.Assignment, error) { +func (c *gRPCClient) MoveAssignment(ctx context.Context, req *reservationpb.MoveAssignmentRequest, opts ...gax.CallOption) (*reservationpb.Assignment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -843,7 +1005,7 @@ func (c *Client) MoveAssignment(ctx context.Context, req *reservationpb.MoveAssi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.MoveAssignment[0:len(c.CallOptions.MoveAssignment):len(c.CallOptions.MoveAssignment)], opts...) + opts = append((*c.CallOptions).MoveAssignment[0:len((*c.CallOptions).MoveAssignment):len((*c.CallOptions).MoveAssignment)], opts...) var resp *reservationpb.Assignment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -856,8 +1018,7 @@ func (c *Client) MoveAssignment(ctx context.Context, req *reservationpb.MoveAssi return resp, nil } -// GetBiReservation retrieves a BI reservation. -func (c *Client) GetBiReservation(ctx context.Context, req *reservationpb.GetBiReservationRequest, opts ...gax.CallOption) (*reservationpb.BiReservation, error) { +func (c *gRPCClient) GetBiReservation(ctx context.Context, req *reservationpb.GetBiReservationRequest, opts ...gax.CallOption) (*reservationpb.BiReservation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -865,7 +1026,7 @@ func (c *Client) GetBiReservation(ctx context.Context, req *reservationpb.GetBiR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetBiReservation[0:len(c.CallOptions.GetBiReservation):len(c.CallOptions.GetBiReservation)], opts...) + opts = append((*c.CallOptions).GetBiReservation[0:len((*c.CallOptions).GetBiReservation):len((*c.CallOptions).GetBiReservation)], opts...) var resp *reservationpb.BiReservation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -878,15 +1039,7 @@ func (c *Client) GetBiReservation(ctx context.Context, req *reservationpb.GetBiR return resp, nil } -// UpdateBiReservation updates a BI reservation. -// -// Only fields specified in the field_mask are updated. -// -// A singleton BI reservation always exists with default size 0. -// In order to reserve BI capacity it needs to be updated to an amount -// greater than 0. In order to release BI capacity reservation size -// must be set to 0. -func (c *Client) UpdateBiReservation(ctx context.Context, req *reservationpb.UpdateBiReservationRequest, opts ...gax.CallOption) (*reservationpb.BiReservation, error) { +func (c *gRPCClient) UpdateBiReservation(ctx context.Context, req *reservationpb.UpdateBiReservationRequest, opts ...gax.CallOption) (*reservationpb.BiReservation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -894,7 +1047,7 @@ func (c *Client) UpdateBiReservation(ctx context.Context, req *reservationpb.Upd } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "bi_reservation.name", url.QueryEscape(req.GetBiReservation().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateBiReservation[0:len(c.CallOptions.UpdateBiReservation):len(c.CallOptions.UpdateBiReservation)], opts...) + opts = append((*c.CallOptions).UpdateBiReservation[0:len((*c.CallOptions).UpdateBiReservation):len((*c.CallOptions).UpdateBiReservation)], opts...) var resp *reservationpb.BiReservation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/bigquery/reservation/apiv1/reservation_client_example_test.go b/bigquery/reservation/apiv1/reservation_client_example_test.go index 731c2acf901c..447a42c19f6e 100644 --- a/bigquery/reservation/apiv1/reservation_client_example_test.go +++ b/bigquery/reservation/apiv1/reservation_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateReservation() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.CreateReservationRequest{ // TODO: Fill request struct fields. @@ -55,14 +56,12 @@ func ExampleClient_CreateReservation() { } func ExampleClient_ListReservations() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.ListReservationsRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleClient_ListReservations() { } func ExampleClient_GetReservation() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.GetReservationRequest{ // TODO: Fill request struct fields. @@ -107,6 +105,7 @@ func ExampleClient_DeleteReservation() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.DeleteReservationRequest{ // TODO: Fill request struct fields. @@ -118,13 +117,12 @@ func ExampleClient_DeleteReservation() { } func ExampleClient_UpdateReservation() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.UpdateReservationRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleClient_UpdateReservation() { } func ExampleClient_CreateCapacityCommitment() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.CreateCapacityCommitmentRequest{ // TODO: Fill request struct fields. @@ -158,14 +155,12 @@ func ExampleClient_CreateCapacityCommitment() { } func ExampleClient_ListCapacityCommitments() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.ListCapacityCommitmentsRequest{ // TODO: Fill request struct fields. @@ -185,13 +180,12 @@ func ExampleClient_ListCapacityCommitments() { } func ExampleClient_GetCapacityCommitment() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.GetCapacityCommitmentRequest{ // TODO: Fill request struct fields. @@ -210,6 +204,7 @@ func ExampleClient_DeleteCapacityCommitment() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.DeleteCapacityCommitmentRequest{ // TODO: Fill request struct fields. @@ -221,13 +216,12 @@ func ExampleClient_DeleteCapacityCommitment() { } func ExampleClient_UpdateCapacityCommitment() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.UpdateCapacityCommitmentRequest{ // TODO: Fill request struct fields. @@ -241,13 +235,12 @@ func ExampleClient_UpdateCapacityCommitment() { } func ExampleClient_SplitCapacityCommitment() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.SplitCapacityCommitmentRequest{ // TODO: Fill request struct fields. @@ -261,13 +254,12 @@ func ExampleClient_SplitCapacityCommitment() { } func ExampleClient_MergeCapacityCommitments() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.MergeCapacityCommitmentsRequest{ // TODO: Fill request struct fields. @@ -281,13 +273,12 @@ func ExampleClient_MergeCapacityCommitments() { } func ExampleClient_CreateAssignment() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.CreateAssignmentRequest{ // TODO: Fill request struct fields. @@ -301,14 +292,12 @@ func ExampleClient_CreateAssignment() { } func ExampleClient_ListAssignments() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.ListAssignmentsRequest{ // TODO: Fill request struct fields. @@ -333,6 +322,7 @@ func ExampleClient_DeleteAssignment() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.DeleteAssignmentRequest{ // TODO: Fill request struct fields. @@ -344,14 +334,12 @@ func ExampleClient_DeleteAssignment() { } func ExampleClient_SearchAssignments() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.SearchAssignmentsRequest{ // TODO: Fill request struct fields. @@ -371,13 +359,12 @@ func ExampleClient_SearchAssignments() { } func ExampleClient_MoveAssignment() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.MoveAssignmentRequest{ // TODO: Fill request struct fields. @@ -391,13 +378,12 @@ func ExampleClient_MoveAssignment() { } func ExampleClient_GetBiReservation() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.GetBiReservationRequest{ // TODO: Fill request struct fields. @@ -411,13 +397,12 @@ func ExampleClient_GetBiReservation() { } func ExampleClient_UpdateBiReservation() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.UpdateBiReservationRequest{ // TODO: Fill request struct fields. diff --git a/bigquery/reservation/apiv1beta1/doc.go b/bigquery/reservation/apiv1beta1/doc.go index 7776de11697c..f93ff2ff25d7 100644 --- a/bigquery/reservation/apiv1beta1/doc.go +++ b/bigquery/reservation/apiv1beta1/doc.go @@ -19,6 +19,8 @@ // // A service to modify your BigQuery flat-rate reservations. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -28,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package reservation // import "cloud.google.com/go/bigquery/reservation/apiv1beta1" import ( @@ -48,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/bigquery/reservation/apiv1beta1/reservation_client.go b/bigquery/reservation/apiv1beta1/reservation_client.go index fc038174cc31..d5f9155a8ea1 100644 --- a/bigquery/reservation/apiv1beta1/reservation_client.go +++ b/bigquery/reservation/apiv1beta1/reservation_client.go @@ -60,7 +60,7 @@ type CallOptions struct { UpdateBiReservation []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("bigqueryreservation.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("bigqueryreservation.mtls.googleapis.com:443"), @@ -206,27 +206,325 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from BigQuery Reservation API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateReservation(context.Context, *reservationpb.CreateReservationRequest, ...gax.CallOption) (*reservationpb.Reservation, error) + ListReservations(context.Context, *reservationpb.ListReservationsRequest, ...gax.CallOption) *ReservationIterator + GetReservation(context.Context, *reservationpb.GetReservationRequest, ...gax.CallOption) (*reservationpb.Reservation, error) + DeleteReservation(context.Context, *reservationpb.DeleteReservationRequest, ...gax.CallOption) error + UpdateReservation(context.Context, *reservationpb.UpdateReservationRequest, ...gax.CallOption) (*reservationpb.Reservation, error) + CreateCapacityCommitment(context.Context, *reservationpb.CreateCapacityCommitmentRequest, ...gax.CallOption) (*reservationpb.CapacityCommitment, error) + ListCapacityCommitments(context.Context, *reservationpb.ListCapacityCommitmentsRequest, ...gax.CallOption) *CapacityCommitmentIterator + GetCapacityCommitment(context.Context, *reservationpb.GetCapacityCommitmentRequest, ...gax.CallOption) (*reservationpb.CapacityCommitment, error) + DeleteCapacityCommitment(context.Context, *reservationpb.DeleteCapacityCommitmentRequest, ...gax.CallOption) error + UpdateCapacityCommitment(context.Context, *reservationpb.UpdateCapacityCommitmentRequest, ...gax.CallOption) (*reservationpb.CapacityCommitment, error) + SplitCapacityCommitment(context.Context, *reservationpb.SplitCapacityCommitmentRequest, ...gax.CallOption) (*reservationpb.SplitCapacityCommitmentResponse, error) + MergeCapacityCommitments(context.Context, *reservationpb.MergeCapacityCommitmentsRequest, ...gax.CallOption) (*reservationpb.CapacityCommitment, error) + CreateAssignment(context.Context, *reservationpb.CreateAssignmentRequest, ...gax.CallOption) (*reservationpb.Assignment, error) + ListAssignments(context.Context, *reservationpb.ListAssignmentsRequest, ...gax.CallOption) *AssignmentIterator + DeleteAssignment(context.Context, *reservationpb.DeleteAssignmentRequest, ...gax.CallOption) error + SearchAssignments(context.Context, *reservationpb.SearchAssignmentsRequest, ...gax.CallOption) *AssignmentIterator + MoveAssignment(context.Context, *reservationpb.MoveAssignmentRequest, ...gax.CallOption) (*reservationpb.Assignment, error) + GetBiReservation(context.Context, *reservationpb.GetBiReservationRequest, ...gax.CallOption) (*reservationpb.BiReservation, error) + UpdateBiReservation(context.Context, *reservationpb.UpdateBiReservationRequest, ...gax.CallOption) (*reservationpb.BiReservation, error) +} + // Client is a client for interacting with BigQuery Reservation API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// This API allows users to manage their flat-rate BigQuery reservations. +// +// A reservation provides computational resource guarantees, in the form of +// slots (at https://cloud.google.com/bigquery/docs/slots), to users. A slot is a +// unit of computational power in BigQuery, and serves as the basic unit of +// parallelism. In a scan of a multi-partitioned table, a single slot operates +// on a single partition of the table. A reservation resource exists as a child +// resource of the admin project and location, e.g.: +// projects/myproject/locations/US/reservations/reservationName. +// +// A capacity commitment is a way to purchase compute capacity for BigQuery jobs +// (in the form of slots) with some committed period of usage. A capacity +// commitment resource exists as a child resource of the admin project and +// location, e.g.: +// projects/myproject/locations/US/capacityCommitments/id. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateReservation creates a new reservation resource. +func (c *Client) CreateReservation(ctx context.Context, req *reservationpb.CreateReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { + return c.internalClient.CreateReservation(ctx, req, opts...) +} + +// ListReservations lists all the reservations for the project in the specified location. +func (c *Client) ListReservations(ctx context.Context, req *reservationpb.ListReservationsRequest, opts ...gax.CallOption) *ReservationIterator { + return c.internalClient.ListReservations(ctx, req, opts...) +} + +// GetReservation returns information about the reservation. +func (c *Client) GetReservation(ctx context.Context, req *reservationpb.GetReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { + return c.internalClient.GetReservation(ctx, req, opts...) +} + +// DeleteReservation deletes a reservation. +// Returns google.rpc.Code.FAILED_PRECONDITION when reservation has +// assignments. +func (c *Client) DeleteReservation(ctx context.Context, req *reservationpb.DeleteReservationRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteReservation(ctx, req, opts...) +} + +// UpdateReservation updates an existing reservation resource. +func (c *Client) UpdateReservation(ctx context.Context, req *reservationpb.UpdateReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { + return c.internalClient.UpdateReservation(ctx, req, opts...) +} + +// CreateCapacityCommitment creates a new capacity commitment resource. +func (c *Client) CreateCapacityCommitment(ctx context.Context, req *reservationpb.CreateCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { + return c.internalClient.CreateCapacityCommitment(ctx, req, opts...) +} + +// ListCapacityCommitments lists all the capacity commitments for the admin project. +func (c *Client) ListCapacityCommitments(ctx context.Context, req *reservationpb.ListCapacityCommitmentsRequest, opts ...gax.CallOption) *CapacityCommitmentIterator { + return c.internalClient.ListCapacityCommitments(ctx, req, opts...) +} + +// GetCapacityCommitment returns information about the capacity commitment. +func (c *Client) GetCapacityCommitment(ctx context.Context, req *reservationpb.GetCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { + return c.internalClient.GetCapacityCommitment(ctx, req, opts...) +} + +// DeleteCapacityCommitment deletes a capacity commitment. Attempting to delete capacity commitment +// before its commitment_end_time will fail with the error code +// google.rpc.Code.FAILED_PRECONDITION. +func (c *Client) DeleteCapacityCommitment(ctx context.Context, req *reservationpb.DeleteCapacityCommitmentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteCapacityCommitment(ctx, req, opts...) +} + +// UpdateCapacityCommitment updates an existing capacity commitment. +// +// Only plan and renewal_plan fields can be updated. +// +// Plan can only be changed to a plan of a longer commitment period. +// Attempting to change to a plan with shorter commitment period will fail +// with the error code google.rpc.Code.FAILED_PRECONDITION. +func (c *Client) UpdateCapacityCommitment(ctx context.Context, req *reservationpb.UpdateCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { + return c.internalClient.UpdateCapacityCommitment(ctx, req, opts...) +} + +// SplitCapacityCommitment splits capacity commitment to two commitments of the same plan and +// commitment_end_time. +// +// A common use case is to enable downgrading commitments. +// +// For example, in order to downgrade from 10000 slots to 8000, you might +// split a 10000 capacity commitment into commitments of 2000 and 8000. Then, +// you would change the plan of the first one to FLEX and then delete it. +func (c *Client) SplitCapacityCommitment(ctx context.Context, req *reservationpb.SplitCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.SplitCapacityCommitmentResponse, error) { + return c.internalClient.SplitCapacityCommitment(ctx, req, opts...) +} + +// MergeCapacityCommitments merges capacity commitments of the same plan into a single commitment. +// +// The resulting capacity commitment has the greater commitment_end_time +// out of the to-be-merged capacity commitments. +// +// Attempting to merge capacity commitments of different plan will fail +// with the error code google.rpc.Code.FAILED_PRECONDITION. +func (c *Client) MergeCapacityCommitments(ctx context.Context, req *reservationpb.MergeCapacityCommitmentsRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { + return c.internalClient.MergeCapacityCommitments(ctx, req, opts...) +} + +// CreateAssignment creates an assignment object which allows the given project to submit jobs +// of a certain type using slots from the specified reservation. +// +// Currently a +// resource (project, folder, organization) can only have one assignment per +// each (job_type, location) combination, and that reservation will be used +// for all jobs of the matching type. +// +// Different assignments can be created on different levels of the +// projects, folders or organization hierarchy. During query execution, +// the assignment is looked up at the project, folder and organization levels +// in that order. The first assignment found is applied to the query. +// +// When creating assignments, it does not matter if other assignments exist at +// higher levels. +// +// Example: +// +// The organization organizationA contains two projects, project1 +// and project2. +// +// Assignments for all three entities (organizationA, project1, and +// project2) could all be created and mapped to the same or different +// reservations. +// +// Returns google.rpc.Code.PERMISSION_DENIED if user does not have +// ‘bigquery.admin’ permissions on the project using the reservation +// and the project that owns this reservation. +// +// Returns google.rpc.Code.INVALID_ARGUMENT when location of the assignment +// does not match location of the reservation. +func (c *Client) CreateAssignment(ctx context.Context, req *reservationpb.CreateAssignmentRequest, opts ...gax.CallOption) (*reservationpb.Assignment, error) { + return c.internalClient.CreateAssignment(ctx, req, opts...) +} + +// ListAssignments lists assignments. +// +// Only explicitly created assignments will be returned. +// +// Example: +// +// Organization organizationA contains two projects, project1 and +// project2. +// +// Reservation res1 exists and was created previously. +// +// CreateAssignment was used previously to define the following +// associations between entities and reservations: +// and +// +// In this example, ListAssignments will just return the above two assignments +// for reservation res1, and no expansion/merge will happen. +// +// The wildcard “-” can be used for +// reservations in the request. In that case all assignments belongs to the +// specified project and location will be listed. +// +// Note "-" cannot be used for projects nor locations. +func (c *Client) ListAssignments(ctx context.Context, req *reservationpb.ListAssignmentsRequest, opts ...gax.CallOption) *AssignmentIterator { + return c.internalClient.ListAssignments(ctx, req, opts...) +} + +// DeleteAssignment deletes a assignment. No expansion will happen. +// +// Example: +// +// Organization organizationA contains two projects, project1 and +// project2. +// +// Reservation res1 exists and was created previously. +// +// CreateAssignment was used previously to define the following +// associations between entities and reservations: +// and +// +// In this example, deletion of the assignment won’t +// affect the other assignment . After said deletion, +// queries from project1 will still use res1 while queries from +// project2 will switch to use on-demand mode. +func (c *Client) DeleteAssignment(ctx context.Context, req *reservationpb.DeleteAssignmentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteAssignment(ctx, req, opts...) +} + +// SearchAssignments looks up assignments for a specified resource for a particular region. +// If the request is about a project: +// +// Assignments created on the project will be returned if they exist. +// +// Otherwise assignments created on the closest ancestor will be +// returned. +// +// Assignments for different JobTypes will all be returned. +// +// The same logic applies if the request is about a folder. +// +// If the request is about an organization, then assignments created on the +// organization will be returned (organization doesn’t have ancestors). +// +// Comparing to ListAssignments, there are some behavior +// differences: +// +// permission on the assignee will be verified in this API. +// +// Hierarchy lookup (project->folder->organization) happens in this API. +// +// Parent here is projects/*/locations/*, instead of +// projects/*/locations/*reservations/*. +// +// Note "-" cannot be used for projects +// nor locations. +func (c *Client) SearchAssignments(ctx context.Context, req *reservationpb.SearchAssignmentsRequest, opts ...gax.CallOption) *AssignmentIterator { + return c.internalClient.SearchAssignments(ctx, req, opts...) +} + +// MoveAssignment moves an assignment under a new reservation. +// +// This differs from removing an existing assignment and recreating a new one +// by providing a transactional change that ensures an assignee always has an +// associated reservation. +func (c *Client) MoveAssignment(ctx context.Context, req *reservationpb.MoveAssignmentRequest, opts ...gax.CallOption) (*reservationpb.Assignment, error) { + return c.internalClient.MoveAssignment(ctx, req, opts...) +} + +// GetBiReservation retrieves a BI reservation. +func (c *Client) GetBiReservation(ctx context.Context, req *reservationpb.GetBiReservationRequest, opts ...gax.CallOption) (*reservationpb.BiReservation, error) { + return c.internalClient.GetBiReservation(ctx, req, opts...) +} + +// UpdateBiReservation updates a BI reservation. +// +// Only fields specified in the field_mask are updated. +// +// A singleton BI reservation always exists with default size 0. +// In order to reserve BI capacity it needs to be updated to an amount +// greater than 0. In order to release BI capacity reservation size +// must be set to 0. +func (c *Client) UpdateBiReservation(ctx context.Context, req *reservationpb.UpdateBiReservationRequest, opts ...gax.CallOption) (*reservationpb.BiReservation, error) { + return c.internalClient.UpdateBiReservation(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with BigQuery Reservation API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client reservationpb.ReservationServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new reservation service client. +// NewClient creates a new reservation service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // This API allows users to manage their flat-rate BigQuery reservations. // @@ -244,8 +542,7 @@ type Client struct { // location, e.g.: // projects/myproject/locations/US/capacityCommitments/id. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -263,42 +560,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: reservationpb.NewReservationServiceClient(connPool), + client: reservationpb.NewReservationServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateReservation creates a new reservation resource. -func (c *Client) CreateReservation(ctx context.Context, req *reservationpb.CreateReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateReservation(ctx context.Context, req *reservationpb.CreateReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -306,7 +605,7 @@ func (c *Client) CreateReservation(ctx context.Context, req *reservationpb.Creat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateReservation[0:len(c.CallOptions.CreateReservation):len(c.CallOptions.CreateReservation)], opts...) + opts = append((*c.CallOptions).CreateReservation[0:len((*c.CallOptions).CreateReservation):len((*c.CallOptions).CreateReservation)], opts...) var resp *reservationpb.Reservation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -319,11 +618,10 @@ func (c *Client) CreateReservation(ctx context.Context, req *reservationpb.Creat return resp, nil } -// ListReservations lists all the reservations for the project in the specified location. -func (c *Client) ListReservations(ctx context.Context, req *reservationpb.ListReservationsRequest, opts ...gax.CallOption) *ReservationIterator { +func (c *gRPCClient) ListReservations(ctx context.Context, req *reservationpb.ListReservationsRequest, opts ...gax.CallOption) *ReservationIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListReservations[0:len(c.CallOptions.ListReservations):len(c.CallOptions.ListReservations)], opts...) + opts = append((*c.CallOptions).ListReservations[0:len((*c.CallOptions).ListReservations):len((*c.CallOptions).ListReservations)], opts...) it := &ReservationIterator{} req = proto.Clone(req).(*reservationpb.ListReservationsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*reservationpb.Reservation, string, error) { @@ -360,8 +658,7 @@ func (c *Client) ListReservations(ctx context.Context, req *reservationpb.ListRe return it } -// GetReservation returns information about the reservation. -func (c *Client) GetReservation(ctx context.Context, req *reservationpb.GetReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { +func (c *gRPCClient) GetReservation(ctx context.Context, req *reservationpb.GetReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -369,7 +666,7 @@ func (c *Client) GetReservation(ctx context.Context, req *reservationpb.GetReser } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetReservation[0:len(c.CallOptions.GetReservation):len(c.CallOptions.GetReservation)], opts...) + opts = append((*c.CallOptions).GetReservation[0:len((*c.CallOptions).GetReservation):len((*c.CallOptions).GetReservation)], opts...) var resp *reservationpb.Reservation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -382,10 +679,7 @@ func (c *Client) GetReservation(ctx context.Context, req *reservationpb.GetReser return resp, nil } -// DeleteReservation deletes a reservation. -// Returns google.rpc.Code.FAILED_PRECONDITION when reservation has -// assignments. -func (c *Client) DeleteReservation(ctx context.Context, req *reservationpb.DeleteReservationRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteReservation(ctx context.Context, req *reservationpb.DeleteReservationRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -393,7 +687,7 @@ func (c *Client) DeleteReservation(ctx context.Context, req *reservationpb.Delet } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteReservation[0:len(c.CallOptions.DeleteReservation):len(c.CallOptions.DeleteReservation)], opts...) + opts = append((*c.CallOptions).DeleteReservation[0:len((*c.CallOptions).DeleteReservation):len((*c.CallOptions).DeleteReservation)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteReservation(ctx, req, settings.GRPC...) @@ -402,8 +696,7 @@ func (c *Client) DeleteReservation(ctx context.Context, req *reservationpb.Delet return err } -// UpdateReservation updates an existing reservation resource. -func (c *Client) UpdateReservation(ctx context.Context, req *reservationpb.UpdateReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { +func (c *gRPCClient) UpdateReservation(ctx context.Context, req *reservationpb.UpdateReservationRequest, opts ...gax.CallOption) (*reservationpb.Reservation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -411,7 +704,7 @@ func (c *Client) UpdateReservation(ctx context.Context, req *reservationpb.Updat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "reservation.name", url.QueryEscape(req.GetReservation().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateReservation[0:len(c.CallOptions.UpdateReservation):len(c.CallOptions.UpdateReservation)], opts...) + opts = append((*c.CallOptions).UpdateReservation[0:len((*c.CallOptions).UpdateReservation):len((*c.CallOptions).UpdateReservation)], opts...) var resp *reservationpb.Reservation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -424,8 +717,7 @@ func (c *Client) UpdateReservation(ctx context.Context, req *reservationpb.Updat return resp, nil } -// CreateCapacityCommitment creates a new capacity commitment resource. -func (c *Client) CreateCapacityCommitment(ctx context.Context, req *reservationpb.CreateCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { +func (c *gRPCClient) CreateCapacityCommitment(ctx context.Context, req *reservationpb.CreateCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -433,7 +725,7 @@ func (c *Client) CreateCapacityCommitment(ctx context.Context, req *reservationp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCapacityCommitment[0:len(c.CallOptions.CreateCapacityCommitment):len(c.CallOptions.CreateCapacityCommitment)], opts...) + opts = append((*c.CallOptions).CreateCapacityCommitment[0:len((*c.CallOptions).CreateCapacityCommitment):len((*c.CallOptions).CreateCapacityCommitment)], opts...) var resp *reservationpb.CapacityCommitment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -446,11 +738,10 @@ func (c *Client) CreateCapacityCommitment(ctx context.Context, req *reservationp return resp, nil } -// ListCapacityCommitments lists all the capacity commitments for the admin project. -func (c *Client) ListCapacityCommitments(ctx context.Context, req *reservationpb.ListCapacityCommitmentsRequest, opts ...gax.CallOption) *CapacityCommitmentIterator { +func (c *gRPCClient) ListCapacityCommitments(ctx context.Context, req *reservationpb.ListCapacityCommitmentsRequest, opts ...gax.CallOption) *CapacityCommitmentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCapacityCommitments[0:len(c.CallOptions.ListCapacityCommitments):len(c.CallOptions.ListCapacityCommitments)], opts...) + opts = append((*c.CallOptions).ListCapacityCommitments[0:len((*c.CallOptions).ListCapacityCommitments):len((*c.CallOptions).ListCapacityCommitments)], opts...) it := &CapacityCommitmentIterator{} req = proto.Clone(req).(*reservationpb.ListCapacityCommitmentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*reservationpb.CapacityCommitment, string, error) { @@ -487,8 +778,7 @@ func (c *Client) ListCapacityCommitments(ctx context.Context, req *reservationpb return it } -// GetCapacityCommitment returns information about the capacity commitment. -func (c *Client) GetCapacityCommitment(ctx context.Context, req *reservationpb.GetCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { +func (c *gRPCClient) GetCapacityCommitment(ctx context.Context, req *reservationpb.GetCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -496,7 +786,7 @@ func (c *Client) GetCapacityCommitment(ctx context.Context, req *reservationpb.G } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCapacityCommitment[0:len(c.CallOptions.GetCapacityCommitment):len(c.CallOptions.GetCapacityCommitment)], opts...) + opts = append((*c.CallOptions).GetCapacityCommitment[0:len((*c.CallOptions).GetCapacityCommitment):len((*c.CallOptions).GetCapacityCommitment)], opts...) var resp *reservationpb.CapacityCommitment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -509,10 +799,7 @@ func (c *Client) GetCapacityCommitment(ctx context.Context, req *reservationpb.G return resp, nil } -// DeleteCapacityCommitment deletes a capacity commitment. Attempting to delete capacity commitment -// before its commitment_end_time will fail with the error code -// google.rpc.Code.FAILED_PRECONDITION. -func (c *Client) DeleteCapacityCommitment(ctx context.Context, req *reservationpb.DeleteCapacityCommitmentRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteCapacityCommitment(ctx context.Context, req *reservationpb.DeleteCapacityCommitmentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -520,7 +807,7 @@ func (c *Client) DeleteCapacityCommitment(ctx context.Context, req *reservationp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteCapacityCommitment[0:len(c.CallOptions.DeleteCapacityCommitment):len(c.CallOptions.DeleteCapacityCommitment)], opts...) + opts = append((*c.CallOptions).DeleteCapacityCommitment[0:len((*c.CallOptions).DeleteCapacityCommitment):len((*c.CallOptions).DeleteCapacityCommitment)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteCapacityCommitment(ctx, req, settings.GRPC...) @@ -529,14 +816,7 @@ func (c *Client) DeleteCapacityCommitment(ctx context.Context, req *reservationp return err } -// UpdateCapacityCommitment updates an existing capacity commitment. -// -// Only plan and renewal_plan fields can be updated. -// -// Plan can only be changed to a plan of a longer commitment period. -// Attempting to change to a plan with shorter commitment period will fail -// with the error code google.rpc.Code.FAILED_PRECONDITION. -func (c *Client) UpdateCapacityCommitment(ctx context.Context, req *reservationpb.UpdateCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { +func (c *gRPCClient) UpdateCapacityCommitment(ctx context.Context, req *reservationpb.UpdateCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -544,7 +824,7 @@ func (c *Client) UpdateCapacityCommitment(ctx context.Context, req *reservationp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "capacity_commitment.name", url.QueryEscape(req.GetCapacityCommitment().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCapacityCommitment[0:len(c.CallOptions.UpdateCapacityCommitment):len(c.CallOptions.UpdateCapacityCommitment)], opts...) + opts = append((*c.CallOptions).UpdateCapacityCommitment[0:len((*c.CallOptions).UpdateCapacityCommitment):len((*c.CallOptions).UpdateCapacityCommitment)], opts...) var resp *reservationpb.CapacityCommitment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -557,15 +837,7 @@ func (c *Client) UpdateCapacityCommitment(ctx context.Context, req *reservationp return resp, nil } -// SplitCapacityCommitment splits capacity commitment to two commitments of the same plan and -// commitment_end_time. -// -// A common use case is to enable downgrading commitments. -// -// For example, in order to downgrade from 10000 slots to 8000, you might -// split a 10000 capacity commitment into commitments of 2000 and 8000. Then, -// you would change the plan of the first one to FLEX and then delete it. -func (c *Client) SplitCapacityCommitment(ctx context.Context, req *reservationpb.SplitCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.SplitCapacityCommitmentResponse, error) { +func (c *gRPCClient) SplitCapacityCommitment(ctx context.Context, req *reservationpb.SplitCapacityCommitmentRequest, opts ...gax.CallOption) (*reservationpb.SplitCapacityCommitmentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -573,7 +845,7 @@ func (c *Client) SplitCapacityCommitment(ctx context.Context, req *reservationpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SplitCapacityCommitment[0:len(c.CallOptions.SplitCapacityCommitment):len(c.CallOptions.SplitCapacityCommitment)], opts...) + opts = append((*c.CallOptions).SplitCapacityCommitment[0:len((*c.CallOptions).SplitCapacityCommitment):len((*c.CallOptions).SplitCapacityCommitment)], opts...) var resp *reservationpb.SplitCapacityCommitmentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -586,14 +858,7 @@ func (c *Client) SplitCapacityCommitment(ctx context.Context, req *reservationpb return resp, nil } -// MergeCapacityCommitments merges capacity commitments of the same plan into a single commitment. -// -// The resulting capacity commitment has the greater commitment_end_time -// out of the to-be-merged capacity commitments. -// -// Attempting to merge capacity commitments of different plan will fail -// with the error code google.rpc.Code.FAILED_PRECONDITION. -func (c *Client) MergeCapacityCommitments(ctx context.Context, req *reservationpb.MergeCapacityCommitmentsRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { +func (c *gRPCClient) MergeCapacityCommitments(ctx context.Context, req *reservationpb.MergeCapacityCommitmentsRequest, opts ...gax.CallOption) (*reservationpb.CapacityCommitment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -601,7 +866,7 @@ func (c *Client) MergeCapacityCommitments(ctx context.Context, req *reservationp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.MergeCapacityCommitments[0:len(c.CallOptions.MergeCapacityCommitments):len(c.CallOptions.MergeCapacityCommitments)], opts...) + opts = append((*c.CallOptions).MergeCapacityCommitments[0:len((*c.CallOptions).MergeCapacityCommitments):len((*c.CallOptions).MergeCapacityCommitments)], opts...) var resp *reservationpb.CapacityCommitment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -614,38 +879,7 @@ func (c *Client) MergeCapacityCommitments(ctx context.Context, req *reservationp return resp, nil } -// CreateAssignment creates an assignment object which allows the given project to submit jobs -// of a certain type using slots from the specified reservation. -// -// Currently a -// resource (project, folder, organization) can only have one assignment per -// each (job_type, location) combination, and that reservation will be used -// for all jobs of the matching type. -// -// Different assignments can be created on different levels of the -// projects, folders or organization hierarchy. During query execution, -// the assignment is looked up at the project, folder and organization levels -// in that order. The first assignment found is applied to the query. -// -// When creating assignments, it does not matter if other assignments exist at -// higher levels. -// -// Example: -// -// The organization organizationA contains two projects, project1 -// and project2. -// -// Assignments for all three entities (organizationA, project1, and -// project2) could all be created and mapped to the same or different -// reservations. -// -// Returns google.rpc.Code.PERMISSION_DENIED if user does not have -// ‘bigquery.admin’ permissions on the project using the reservation -// and the project that owns this reservation. -// -// Returns google.rpc.Code.INVALID_ARGUMENT when location of the assignment -// does not match location of the reservation. -func (c *Client) CreateAssignment(ctx context.Context, req *reservationpb.CreateAssignmentRequest, opts ...gax.CallOption) (*reservationpb.Assignment, error) { +func (c *gRPCClient) CreateAssignment(ctx context.Context, req *reservationpb.CreateAssignmentRequest, opts ...gax.CallOption) (*reservationpb.Assignment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -653,7 +887,7 @@ func (c *Client) CreateAssignment(ctx context.Context, req *reservationpb.Create } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateAssignment[0:len(c.CallOptions.CreateAssignment):len(c.CallOptions.CreateAssignment)], opts...) + opts = append((*c.CallOptions).CreateAssignment[0:len((*c.CallOptions).CreateAssignment):len((*c.CallOptions).CreateAssignment)], opts...) var resp *reservationpb.Assignment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -666,33 +900,10 @@ func (c *Client) CreateAssignment(ctx context.Context, req *reservationpb.Create return resp, nil } -// ListAssignments lists assignments. -// -// Only explicitly created assignments will be returned. -// -// Example: -// -// Organization organizationA contains two projects, project1 and -// project2. -// -// Reservation res1 exists and was created previously. -// -// CreateAssignment was used previously to define the following -// associations between entities and reservations: -// and -// -// In this example, ListAssignments will just return the above two assignments -// for reservation res1, and no expansion/merge will happen. -// -// The wildcard “-” can be used for -// reservations in the request. In that case all assignments belongs to the -// specified project and location will be listed. -// -// Note "-" cannot be used for projects nor locations. -func (c *Client) ListAssignments(ctx context.Context, req *reservationpb.ListAssignmentsRequest, opts ...gax.CallOption) *AssignmentIterator { +func (c *gRPCClient) ListAssignments(ctx context.Context, req *reservationpb.ListAssignmentsRequest, opts ...gax.CallOption) *AssignmentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAssignments[0:len(c.CallOptions.ListAssignments):len(c.CallOptions.ListAssignments)], opts...) + opts = append((*c.CallOptions).ListAssignments[0:len((*c.CallOptions).ListAssignments):len((*c.CallOptions).ListAssignments)], opts...) it := &AssignmentIterator{} req = proto.Clone(req).(*reservationpb.ListAssignmentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*reservationpb.Assignment, string, error) { @@ -729,24 +940,7 @@ func (c *Client) ListAssignments(ctx context.Context, req *reservationpb.ListAss return it } -// DeleteAssignment deletes a assignment. No expansion will happen. -// -// Example: -// -// Organization organizationA contains two projects, project1 and -// project2. -// -// Reservation res1 exists and was created previously. -// -// CreateAssignment was used previously to define the following -// associations between entities and reservations: -// and -// -// In this example, deletion of the assignment won’t -// affect the other assignment . After said deletion, -// queries from project1 will still use res1 while queries from -// project2 will switch to use on-demand mode. -func (c *Client) DeleteAssignment(ctx context.Context, req *reservationpb.DeleteAssignmentRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteAssignment(ctx context.Context, req *reservationpb.DeleteAssignmentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -754,7 +948,7 @@ func (c *Client) DeleteAssignment(ctx context.Context, req *reservationpb.Delete } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteAssignment[0:len(c.CallOptions.DeleteAssignment):len(c.CallOptions.DeleteAssignment)], opts...) + opts = append((*c.CallOptions).DeleteAssignment[0:len((*c.CallOptions).DeleteAssignment):len((*c.CallOptions).DeleteAssignment)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteAssignment(ctx, req, settings.GRPC...) @@ -763,37 +957,10 @@ func (c *Client) DeleteAssignment(ctx context.Context, req *reservationpb.Delete return err } -// SearchAssignments looks up assignments for a specified resource for a particular region. -// If the request is about a project: -// -// Assignments created on the project will be returned if they exist. -// -// Otherwise assignments created on the closest ancestor will be -// returned. -// -// Assignments for different JobTypes will all be returned. -// -// The same logic applies if the request is about a folder. -// -// If the request is about an organization, then assignments created on the -// organization will be returned (organization doesn’t have ancestors). -// -// Comparing to ListAssignments, there are some behavior -// differences: -// -// permission on the assignee will be verified in this API. -// -// Hierarchy lookup (project->folder->organization) happens in this API. -// -// Parent here is projects/*/locations/*, instead of -// projects/*/locations/*reservations/*. -// -// Note "-" cannot be used for projects -// nor locations. -func (c *Client) SearchAssignments(ctx context.Context, req *reservationpb.SearchAssignmentsRequest, opts ...gax.CallOption) *AssignmentIterator { +func (c *gRPCClient) SearchAssignments(ctx context.Context, req *reservationpb.SearchAssignmentsRequest, opts ...gax.CallOption) *AssignmentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SearchAssignments[0:len(c.CallOptions.SearchAssignments):len(c.CallOptions.SearchAssignments)], opts...) + opts = append((*c.CallOptions).SearchAssignments[0:len((*c.CallOptions).SearchAssignments):len((*c.CallOptions).SearchAssignments)], opts...) it := &AssignmentIterator{} req = proto.Clone(req).(*reservationpb.SearchAssignmentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*reservationpb.Assignment, string, error) { @@ -830,12 +997,7 @@ func (c *Client) SearchAssignments(ctx context.Context, req *reservationpb.Searc return it } -// MoveAssignment moves an assignment under a new reservation. -// -// This differs from removing an existing assignment and recreating a new one -// by providing a transactional change that ensures an assignee always has an -// associated reservation. -func (c *Client) MoveAssignment(ctx context.Context, req *reservationpb.MoveAssignmentRequest, opts ...gax.CallOption) (*reservationpb.Assignment, error) { +func (c *gRPCClient) MoveAssignment(ctx context.Context, req *reservationpb.MoveAssignmentRequest, opts ...gax.CallOption) (*reservationpb.Assignment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -843,7 +1005,7 @@ func (c *Client) MoveAssignment(ctx context.Context, req *reservationpb.MoveAssi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.MoveAssignment[0:len(c.CallOptions.MoveAssignment):len(c.CallOptions.MoveAssignment)], opts...) + opts = append((*c.CallOptions).MoveAssignment[0:len((*c.CallOptions).MoveAssignment):len((*c.CallOptions).MoveAssignment)], opts...) var resp *reservationpb.Assignment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -856,8 +1018,7 @@ func (c *Client) MoveAssignment(ctx context.Context, req *reservationpb.MoveAssi return resp, nil } -// GetBiReservation retrieves a BI reservation. -func (c *Client) GetBiReservation(ctx context.Context, req *reservationpb.GetBiReservationRequest, opts ...gax.CallOption) (*reservationpb.BiReservation, error) { +func (c *gRPCClient) GetBiReservation(ctx context.Context, req *reservationpb.GetBiReservationRequest, opts ...gax.CallOption) (*reservationpb.BiReservation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -865,7 +1026,7 @@ func (c *Client) GetBiReservation(ctx context.Context, req *reservationpb.GetBiR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetBiReservation[0:len(c.CallOptions.GetBiReservation):len(c.CallOptions.GetBiReservation)], opts...) + opts = append((*c.CallOptions).GetBiReservation[0:len((*c.CallOptions).GetBiReservation):len((*c.CallOptions).GetBiReservation)], opts...) var resp *reservationpb.BiReservation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -878,15 +1039,7 @@ func (c *Client) GetBiReservation(ctx context.Context, req *reservationpb.GetBiR return resp, nil } -// UpdateBiReservation updates a BI reservation. -// -// Only fields specified in the field_mask are updated. -// -// A singleton BI reservation always exists with default size 0. -// In order to reserve BI capacity it needs to be updated to an amount -// greater than 0. In order to release BI capacity reservation size -// must be set to 0. -func (c *Client) UpdateBiReservation(ctx context.Context, req *reservationpb.UpdateBiReservationRequest, opts ...gax.CallOption) (*reservationpb.BiReservation, error) { +func (c *gRPCClient) UpdateBiReservation(ctx context.Context, req *reservationpb.UpdateBiReservationRequest, opts ...gax.CallOption) (*reservationpb.BiReservation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -894,7 +1047,7 @@ func (c *Client) UpdateBiReservation(ctx context.Context, req *reservationpb.Upd } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "reservation.name", url.QueryEscape(req.GetReservation().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateBiReservation[0:len(c.CallOptions.UpdateBiReservation):len(c.CallOptions.UpdateBiReservation)], opts...) + opts = append((*c.CallOptions).UpdateBiReservation[0:len((*c.CallOptions).UpdateBiReservation):len((*c.CallOptions).UpdateBiReservation)], opts...) var resp *reservationpb.BiReservation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/bigquery/reservation/apiv1beta1/reservation_client_example_test.go b/bigquery/reservation/apiv1beta1/reservation_client_example_test.go index 5139e6268857..63fc9b494514 100644 --- a/bigquery/reservation/apiv1beta1/reservation_client_example_test.go +++ b/bigquery/reservation/apiv1beta1/reservation_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateReservation() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.CreateReservationRequest{ // TODO: Fill request struct fields. @@ -55,14 +56,12 @@ func ExampleClient_CreateReservation() { } func ExampleClient_ListReservations() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.ListReservationsRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleClient_ListReservations() { } func ExampleClient_GetReservation() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.GetReservationRequest{ // TODO: Fill request struct fields. @@ -107,6 +105,7 @@ func ExampleClient_DeleteReservation() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.DeleteReservationRequest{ // TODO: Fill request struct fields. @@ -118,13 +117,12 @@ func ExampleClient_DeleteReservation() { } func ExampleClient_UpdateReservation() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.UpdateReservationRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleClient_UpdateReservation() { } func ExampleClient_CreateCapacityCommitment() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.CreateCapacityCommitmentRequest{ // TODO: Fill request struct fields. @@ -158,14 +155,12 @@ func ExampleClient_CreateCapacityCommitment() { } func ExampleClient_ListCapacityCommitments() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.ListCapacityCommitmentsRequest{ // TODO: Fill request struct fields. @@ -185,13 +180,12 @@ func ExampleClient_ListCapacityCommitments() { } func ExampleClient_GetCapacityCommitment() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.GetCapacityCommitmentRequest{ // TODO: Fill request struct fields. @@ -210,6 +204,7 @@ func ExampleClient_DeleteCapacityCommitment() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.DeleteCapacityCommitmentRequest{ // TODO: Fill request struct fields. @@ -221,13 +216,12 @@ func ExampleClient_DeleteCapacityCommitment() { } func ExampleClient_UpdateCapacityCommitment() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.UpdateCapacityCommitmentRequest{ // TODO: Fill request struct fields. @@ -241,13 +235,12 @@ func ExampleClient_UpdateCapacityCommitment() { } func ExampleClient_SplitCapacityCommitment() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.SplitCapacityCommitmentRequest{ // TODO: Fill request struct fields. @@ -261,13 +254,12 @@ func ExampleClient_SplitCapacityCommitment() { } func ExampleClient_MergeCapacityCommitments() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.MergeCapacityCommitmentsRequest{ // TODO: Fill request struct fields. @@ -281,13 +273,12 @@ func ExampleClient_MergeCapacityCommitments() { } func ExampleClient_CreateAssignment() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.CreateAssignmentRequest{ // TODO: Fill request struct fields. @@ -301,14 +292,12 @@ func ExampleClient_CreateAssignment() { } func ExampleClient_ListAssignments() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.ListAssignmentsRequest{ // TODO: Fill request struct fields. @@ -333,6 +322,7 @@ func ExampleClient_DeleteAssignment() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.DeleteAssignmentRequest{ // TODO: Fill request struct fields. @@ -344,14 +334,12 @@ func ExampleClient_DeleteAssignment() { } func ExampleClient_SearchAssignments() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.SearchAssignmentsRequest{ // TODO: Fill request struct fields. @@ -371,13 +359,12 @@ func ExampleClient_SearchAssignments() { } func ExampleClient_MoveAssignment() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.MoveAssignmentRequest{ // TODO: Fill request struct fields. @@ -391,13 +378,12 @@ func ExampleClient_MoveAssignment() { } func ExampleClient_GetBiReservation() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.GetBiReservationRequest{ // TODO: Fill request struct fields. @@ -411,13 +397,12 @@ func ExampleClient_GetBiReservation() { } func ExampleClient_UpdateBiReservation() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.UpdateBiReservationRequest{ // TODO: Fill request struct fields. diff --git a/bigquery/storage/apiv1/big_query_read_client.go b/bigquery/storage/apiv1/big_query_read_client.go index e2b252e1747b..727852444c65 100644 --- a/bigquery/storage/apiv1/big_query_read_client.go +++ b/bigquery/storage/apiv1/big_query_read_client.go @@ -42,7 +42,7 @@ type BigQueryReadCallOptions struct { SplitReadStream []gax.CallOption } -func defaultBigQueryReadClientOptions() []option.ClientOption { +func defaultBigQueryReadGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("bigquerystorage.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("bigquerystorage.mtls.googleapis.com:443"), @@ -94,34 +94,130 @@ func defaultBigQueryReadCallOptions() *BigQueryReadCallOptions { } } +// internalBigQueryReadClient is an interface that defines the methods availaible from BigQuery Storage API. +type internalBigQueryReadClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateReadSession(context.Context, *storagepb.CreateReadSessionRequest, ...gax.CallOption) (*storagepb.ReadSession, error) + ReadRows(context.Context, *storagepb.ReadRowsRequest, ...gax.CallOption) (storagepb.BigQueryRead_ReadRowsClient, error) + SplitReadStream(context.Context, *storagepb.SplitReadStreamRequest, ...gax.CallOption) (*storagepb.SplitReadStreamResponse, error) +} + // BigQueryReadClient is a client for interacting with BigQuery Storage API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// BigQuery Read API. +// +// The Read API can be used to read data from BigQuery. type BigQueryReadClient struct { + // The internal transport-dependent client. + internalClient internalBigQueryReadClient + + // The call options for this service. + CallOptions *BigQueryReadCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *BigQueryReadClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *BigQueryReadClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *BigQueryReadClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateReadSession creates a new read session. A read session divides the contents of a +// BigQuery table into one or more streams, which can then be used to read +// data from the table. The read session also specifies properties of the +// data to be read, such as a list of columns or a push-down filter describing +// the rows to be returned. +// +// A particular row can be read by at most one stream. When the caller has +// reached the end of each stream in the session, then all the data in the +// table has been read. +// +// Data is assigned to each stream such that roughly the same number of +// rows can be read from each stream. Because the server-side unit for +// assigning data is collections of rows, the API does not guarantee that +// each stream will return the same number or rows. Additionally, the +// limits are enforced based on the number of pre-filtered rows, so some +// filters can lead to lopsided assignments. +// +// Read sessions automatically expire 24 hours after they are created and do +// not require manual clean-up by the caller. +func (c *BigQueryReadClient) CreateReadSession(ctx context.Context, req *storagepb.CreateReadSessionRequest, opts ...gax.CallOption) (*storagepb.ReadSession, error) { + return c.internalClient.CreateReadSession(ctx, req, opts...) +} + +// ReadRows reads rows from the stream in the format prescribed by the ReadSession. +// Each response contains one or more table rows, up to a maximum of 100 MiB +// per response; read requests which attempt to read individual rows larger +// than 100 MiB will fail. +// +// Each request also returns a set of stream statistics reflecting the current +// state of the stream. +func (c *BigQueryReadClient) ReadRows(ctx context.Context, req *storagepb.ReadRowsRequest, opts ...gax.CallOption) (storagepb.BigQueryRead_ReadRowsClient, error) { + return c.internalClient.ReadRows(ctx, req, opts...) +} + +// SplitReadStream splits a given ReadStream into two ReadStream objects. These +// ReadStream objects are referred to as the primary and the residual +// streams of the split. The original ReadStream can still be read from in +// the same manner as before. Both of the returned ReadStream objects can +// also be read from, and the rows returned by both child streams will be +// the same as the rows read from the original stream. +// +// Moreover, the two child streams will be allocated back-to-back in the +// original ReadStream. Concretely, it is guaranteed that for streams +// original, primary, and residual, that original[0-j] = primary[0-j] and +// original[j-n] = residual[0-m] once the streams have been read to +// completion. +func (c *BigQueryReadClient) SplitReadStream(ctx context.Context, req *storagepb.SplitReadStreamRequest, opts ...gax.CallOption) (*storagepb.SplitReadStreamResponse, error) { + return c.internalClient.SplitReadStream(ctx, req, opts...) +} + +// bigQueryReadGRPCClient is a client for interacting with BigQuery Storage API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type bigQueryReadGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing BigQueryReadClient + CallOptions **BigQueryReadCallOptions + // The gRPC API client. bigQueryReadClient storagepb.BigQueryReadClient - // The call options for this service. - CallOptions *BigQueryReadCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewBigQueryReadClient creates a new big query read client. +// NewBigQueryReadClient creates a new big query read client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // BigQuery Read API. // // The Read API can be used to read data from BigQuery. func NewBigQueryReadClient(ctx context.Context, opts ...option.ClientOption) (*BigQueryReadClient, error) { - clientOpts := defaultBigQueryReadClientOptions() - + clientOpts := defaultBigQueryReadGRPCClientOptions() if newBigQueryReadClientHook != nil { hookOpts, err := newBigQueryReadClientHook(ctx, clientHookParams{}) if err != nil { @@ -139,60 +235,44 @@ func NewBigQueryReadClient(ctx context.Context, opts ...option.ClientOption) (*B if err != nil { return nil, err } - c := &BigQueryReadClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultBigQueryReadCallOptions(), + client := BigQueryReadClient{CallOptions: defaultBigQueryReadCallOptions()} + c := &bigQueryReadGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, bigQueryReadClient: storagepb.NewBigQueryReadClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *BigQueryReadClient) Connection() *grpc.ClientConn { +func (c *bigQueryReadGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *BigQueryReadClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *BigQueryReadClient) setGoogleClientInfo(keyval ...string) { +func (c *bigQueryReadGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateReadSession creates a new read session. A read session divides the contents of a -// BigQuery table into one or more streams, which can then be used to read -// data from the table. The read session also specifies properties of the -// data to be read, such as a list of columns or a push-down filter describing -// the rows to be returned. -// -// A particular row can be read by at most one stream. When the caller has -// reached the end of each stream in the session, then all the data in the -// table has been read. -// -// Data is assigned to each stream such that roughly the same number of -// rows can be read from each stream. Because the server-side unit for -// assigning data is collections of rows, the API does not guarantee that -// each stream will return the same number or rows. Additionally, the -// limits are enforced based on the number of pre-filtered rows, so some -// filters can lead to lopsided assignments. -// -// Read sessions automatically expire 24 hours after they are created and do -// not require manual clean-up by the caller. -func (c *BigQueryReadClient) CreateReadSession(ctx context.Context, req *storagepb.CreateReadSessionRequest, opts ...gax.CallOption) (*storagepb.ReadSession, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *bigQueryReadGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *bigQueryReadGRPCClient) CreateReadSession(ctx context.Context, req *storagepb.CreateReadSessionRequest, opts ...gax.CallOption) (*storagepb.ReadSession, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -200,7 +280,7 @@ func (c *BigQueryReadClient) CreateReadSession(ctx context.Context, req *storage } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "read_session.table", url.QueryEscape(req.GetReadSession().GetTable()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateReadSession[0:len(c.CallOptions.CreateReadSession):len(c.CallOptions.CreateReadSession)], opts...) + opts = append((*c.CallOptions).CreateReadSession[0:len((*c.CallOptions).CreateReadSession):len((*c.CallOptions).CreateReadSession)], opts...) var resp *storagepb.ReadSession err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -213,17 +293,9 @@ func (c *BigQueryReadClient) CreateReadSession(ctx context.Context, req *storage return resp, nil } -// ReadRows reads rows from the stream in the format prescribed by the ReadSession. -// Each response contains one or more table rows, up to a maximum of 100 MiB -// per response; read requests which attempt to read individual rows larger -// than 100 MiB will fail. -// -// Each request also returns a set of stream statistics reflecting the current -// state of the stream. -func (c *BigQueryReadClient) ReadRows(ctx context.Context, req *storagepb.ReadRowsRequest, opts ...gax.CallOption) (storagepb.BigQueryRead_ReadRowsClient, error) { +func (c *bigQueryReadGRPCClient) ReadRows(ctx context.Context, req *storagepb.ReadRowsRequest, opts ...gax.CallOption) (storagepb.BigQueryRead_ReadRowsClient, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "read_stream", url.QueryEscape(req.GetReadStream()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ReadRows[0:len(c.CallOptions.ReadRows):len(c.CallOptions.ReadRows)], opts...) var resp storagepb.BigQueryRead_ReadRowsClient err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -236,19 +308,7 @@ func (c *BigQueryReadClient) ReadRows(ctx context.Context, req *storagepb.ReadRo return resp, nil } -// SplitReadStream splits a given ReadStream into two ReadStream objects. These -// ReadStream objects are referred to as the primary and the residual -// streams of the split. The original ReadStream can still be read from in -// the same manner as before. Both of the returned ReadStream objects can -// also be read from, and the rows returned by both child streams will be -// the same as the rows read from the original stream. -// -// Moreover, the two child streams will be allocated back-to-back in the -// original ReadStream. Concretely, it is guaranteed that for streams -// original, primary, and residual, that original[0-j] = primary[0-j] and -// original[j-n] = residual[0-m] once the streams have been read to -// completion. -func (c *BigQueryReadClient) SplitReadStream(ctx context.Context, req *storagepb.SplitReadStreamRequest, opts ...gax.CallOption) (*storagepb.SplitReadStreamResponse, error) { +func (c *bigQueryReadGRPCClient) SplitReadStream(ctx context.Context, req *storagepb.SplitReadStreamRequest, opts ...gax.CallOption) (*storagepb.SplitReadStreamResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -256,7 +316,7 @@ func (c *BigQueryReadClient) SplitReadStream(ctx context.Context, req *storagepb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SplitReadStream[0:len(c.CallOptions.SplitReadStream):len(c.CallOptions.SplitReadStream)], opts...) + opts = append((*c.CallOptions).SplitReadStream[0:len((*c.CallOptions).SplitReadStream):len((*c.CallOptions).SplitReadStream)], opts...) var resp *storagepb.SplitReadStreamResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/bigquery/storage/apiv1/big_query_read_client_example_test.go b/bigquery/storage/apiv1/big_query_read_client_example_test.go index 575f54da4135..072c696f1a02 100644 --- a/bigquery/storage/apiv1/big_query_read_client_example_test.go +++ b/bigquery/storage/apiv1/big_query_read_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewBigQueryReadClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleBigQueryReadClient_CreateReadSession() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1" - ctx := context.Background() c, err := storage.NewBigQueryReadClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.CreateReadSessionRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleBigQueryReadClient_CreateReadSession() { } func ExampleBigQueryReadClient_SplitReadStream() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1" - ctx := context.Background() c, err := storage.NewBigQueryReadClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.SplitReadStreamRequest{ // TODO: Fill request struct fields. diff --git a/bigquery/storage/apiv1/doc.go b/bigquery/storage/apiv1/doc.go index c10c7d132ea7..9b932362610d 100644 --- a/bigquery/storage/apiv1/doc.go +++ b/bigquery/storage/apiv1/doc.go @@ -26,7 +26,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package storage // import "cloud.google.com/go/bigquery/storage/apiv1" import ( @@ -46,7 +46,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/bigquery/storage/apiv1beta1/big_query_storage_client.go b/bigquery/storage/apiv1beta1/big_query_storage_client.go index 746b6bf04edb..1ec2a5c84102 100644 --- a/bigquery/storage/apiv1beta1/big_query_storage_client.go +++ b/bigquery/storage/apiv1beta1/big_query_storage_client.go @@ -44,7 +44,7 @@ type BigQueryStorageCallOptions struct { SplitReadStream []gax.CallOption } -func defaultBigQueryStorageClientOptions() []option.ClientOption { +func defaultBigQueryStorageGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("bigquerystorage.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("bigquerystorage.mtls.googleapis.com:443"), @@ -120,34 +120,153 @@ func defaultBigQueryStorageCallOptions() *BigQueryStorageCallOptions { } } +// internalBigQueryStorageClient is an interface that defines the methods availaible from BigQuery Storage API. +type internalBigQueryStorageClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateReadSession(context.Context, *storagepb.CreateReadSessionRequest, ...gax.CallOption) (*storagepb.ReadSession, error) + ReadRows(context.Context, *storagepb.ReadRowsRequest, ...gax.CallOption) (storagepb.BigQueryStorage_ReadRowsClient, error) + BatchCreateReadSessionStreams(context.Context, *storagepb.BatchCreateReadSessionStreamsRequest, ...gax.CallOption) (*storagepb.BatchCreateReadSessionStreamsResponse, error) + FinalizeStream(context.Context, *storagepb.FinalizeStreamRequest, ...gax.CallOption) error + SplitReadStream(context.Context, *storagepb.SplitReadStreamRequest, ...gax.CallOption) (*storagepb.SplitReadStreamResponse, error) +} + // BigQueryStorageClient is a client for interacting with BigQuery Storage API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// BigQuery storage API. +// +// The BigQuery storage API can be used to read data stored in BigQuery. type BigQueryStorageClient struct { + // The internal transport-dependent client. + internalClient internalBigQueryStorageClient + + // The call options for this service. + CallOptions *BigQueryStorageCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *BigQueryStorageClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *BigQueryStorageClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *BigQueryStorageClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateReadSession creates a new read session. A read session divides the contents of a +// BigQuery table into one or more streams, which can then be used to read +// data from the table. The read session also specifies properties of the +// data to be read, such as a list of columns or a push-down filter describing +// the rows to be returned. +// +// A particular row can be read by at most one stream. When the caller has +// reached the end of each stream in the session, then all the data in the +// table has been read. +// +// Read sessions automatically expire 24 hours after they are created and do +// not require manual clean-up by the caller. +func (c *BigQueryStorageClient) CreateReadSession(ctx context.Context, req *storagepb.CreateReadSessionRequest, opts ...gax.CallOption) (*storagepb.ReadSession, error) { + return c.internalClient.CreateReadSession(ctx, req, opts...) +} + +// ReadRows reads rows from the table in the format prescribed by the read session. +// Each response contains one or more table rows, up to a maximum of 10 MiB +// per response; read requests which attempt to read individual rows larger +// than this will fail. +// +// Each request also returns a set of stream statistics reflecting the +// estimated total number of rows in the read stream. This number is computed +// based on the total table size and the number of active streams in the read +// session, and may change as other streams continue to read data. +func (c *BigQueryStorageClient) ReadRows(ctx context.Context, req *storagepb.ReadRowsRequest, opts ...gax.CallOption) (storagepb.BigQueryStorage_ReadRowsClient, error) { + return c.internalClient.ReadRows(ctx, req, opts...) +} + +// BatchCreateReadSessionStreams creates additional streams for a ReadSession. This API can be used to +// dynamically adjust the parallelism of a batch processing task upwards by +// adding additional workers. +func (c *BigQueryStorageClient) BatchCreateReadSessionStreams(ctx context.Context, req *storagepb.BatchCreateReadSessionStreamsRequest, opts ...gax.CallOption) (*storagepb.BatchCreateReadSessionStreamsResponse, error) { + return c.internalClient.BatchCreateReadSessionStreams(ctx, req, opts...) +} + +// FinalizeStream triggers the graceful termination of a single stream in a ReadSession. This +// API can be used to dynamically adjust the parallelism of a batch processing +// task downwards without losing data. +// +// This API does not delete the stream – it remains visible in the +// ReadSession, and any data processed by the stream is not released to other +// streams. However, no additional data will be assigned to the stream once +// this call completes. Callers must continue reading data on the stream until +// the end of the stream is reached so that data which has already been +// assigned to the stream will be processed. +// +// This method will return an error if there are no other live streams +// in the Session, or if SplitReadStream() has been called on the given +// Stream. +func (c *BigQueryStorageClient) FinalizeStream(ctx context.Context, req *storagepb.FinalizeStreamRequest, opts ...gax.CallOption) error { + return c.internalClient.FinalizeStream(ctx, req, opts...) +} + +// SplitReadStream splits a given read stream into two Streams. These streams are referred to +// as the primary and the residual of the split. The original stream can still +// be read from in the same manner as before. Both of the returned streams can +// also be read from, and the total rows return by both child streams will be +// the same as the rows read from the original stream. +// +// Moreover, the two child streams will be allocated back to back in the +// original Stream. Concretely, it is guaranteed that for streams Original, +// Primary, and Residual, that Original[0-j] = Primary[0-j] and +// Original[j-n] = Residual[0-m] once the streams have been read to +// completion. +// +// This method is guaranteed to be idempotent. +func (c *BigQueryStorageClient) SplitReadStream(ctx context.Context, req *storagepb.SplitReadStreamRequest, opts ...gax.CallOption) (*storagepb.SplitReadStreamResponse, error) { + return c.internalClient.SplitReadStream(ctx, req, opts...) +} + +// bigQueryStorageGRPCClient is a client for interacting with BigQuery Storage API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type bigQueryStorageGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing BigQueryStorageClient + CallOptions **BigQueryStorageCallOptions + // The gRPC API client. bigQueryStorageClient storagepb.BigQueryStorageClient - // The call options for this service. - CallOptions *BigQueryStorageCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewBigQueryStorageClient creates a new big query storage client. +// NewBigQueryStorageClient creates a new big query storage client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // BigQuery storage API. // // The BigQuery storage API can be used to read data stored in BigQuery. func NewBigQueryStorageClient(ctx context.Context, opts ...option.ClientOption) (*BigQueryStorageClient, error) { - clientOpts := defaultBigQueryStorageClientOptions() - + clientOpts := defaultBigQueryStorageGRPCClientOptions() if newBigQueryStorageClientHook != nil { hookOpts, err := newBigQueryStorageClientHook(ctx, clientHookParams{}) if err != nil { @@ -165,53 +284,44 @@ func NewBigQueryStorageClient(ctx context.Context, opts ...option.ClientOption) if err != nil { return nil, err } - c := &BigQueryStorageClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultBigQueryStorageCallOptions(), + client := BigQueryStorageClient{CallOptions: defaultBigQueryStorageCallOptions()} + c := &bigQueryStorageGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, bigQueryStorageClient: storagepb.NewBigQueryStorageClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *BigQueryStorageClient) Connection() *grpc.ClientConn { +func (c *bigQueryStorageGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *BigQueryStorageClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *BigQueryStorageClient) setGoogleClientInfo(keyval ...string) { +func (c *bigQueryStorageGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateReadSession creates a new read session. A read session divides the contents of a -// BigQuery table into one or more streams, which can then be used to read -// data from the table. The read session also specifies properties of the -// data to be read, such as a list of columns or a push-down filter describing -// the rows to be returned. -// -// A particular row can be read by at most one stream. When the caller has -// reached the end of each stream in the session, then all the data in the -// table has been read. -// -// Read sessions automatically expire 24 hours after they are created and do -// not require manual clean-up by the caller. -func (c *BigQueryStorageClient) CreateReadSession(ctx context.Context, req *storagepb.CreateReadSessionRequest, opts ...gax.CallOption) (*storagepb.ReadSession, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *bigQueryStorageGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *bigQueryStorageGRPCClient) CreateReadSession(ctx context.Context, req *storagepb.CreateReadSessionRequest, opts ...gax.CallOption) (*storagepb.ReadSession, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -219,7 +329,7 @@ func (c *BigQueryStorageClient) CreateReadSession(ctx context.Context, req *stor } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "table_reference.project_id", url.QueryEscape(req.GetTableReference().GetProjectId()), "table_reference.dataset_id", url.QueryEscape(req.GetTableReference().GetDatasetId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateReadSession[0:len(c.CallOptions.CreateReadSession):len(c.CallOptions.CreateReadSession)], opts...) + opts = append((*c.CallOptions).CreateReadSession[0:len((*c.CallOptions).CreateReadSession):len((*c.CallOptions).CreateReadSession)], opts...) var resp *storagepb.ReadSession err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -232,19 +342,9 @@ func (c *BigQueryStorageClient) CreateReadSession(ctx context.Context, req *stor return resp, nil } -// ReadRows reads rows from the table in the format prescribed by the read session. -// Each response contains one or more table rows, up to a maximum of 10 MiB -// per response; read requests which attempt to read individual rows larger -// than this will fail. -// -// Each request also returns a set of stream statistics reflecting the -// estimated total number of rows in the read stream. This number is computed -// based on the total table size and the number of active streams in the read -// session, and may change as other streams continue to read data. -func (c *BigQueryStorageClient) ReadRows(ctx context.Context, req *storagepb.ReadRowsRequest, opts ...gax.CallOption) (storagepb.BigQueryStorage_ReadRowsClient, error) { +func (c *bigQueryStorageGRPCClient) ReadRows(ctx context.Context, req *storagepb.ReadRowsRequest, opts ...gax.CallOption) (storagepb.BigQueryStorage_ReadRowsClient, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "read_position.stream.name", url.QueryEscape(req.GetReadPosition().GetStream().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ReadRows[0:len(c.CallOptions.ReadRows):len(c.CallOptions.ReadRows)], opts...) var resp storagepb.BigQueryStorage_ReadRowsClient err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -257,10 +357,7 @@ func (c *BigQueryStorageClient) ReadRows(ctx context.Context, req *storagepb.Rea return resp, nil } -// BatchCreateReadSessionStreams creates additional streams for a ReadSession. This API can be used to -// dynamically adjust the parallelism of a batch processing task upwards by -// adding additional workers. -func (c *BigQueryStorageClient) BatchCreateReadSessionStreams(ctx context.Context, req *storagepb.BatchCreateReadSessionStreamsRequest, opts ...gax.CallOption) (*storagepb.BatchCreateReadSessionStreamsResponse, error) { +func (c *bigQueryStorageGRPCClient) BatchCreateReadSessionStreams(ctx context.Context, req *storagepb.BatchCreateReadSessionStreamsRequest, opts ...gax.CallOption) (*storagepb.BatchCreateReadSessionStreamsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -268,7 +365,7 @@ func (c *BigQueryStorageClient) BatchCreateReadSessionStreams(ctx context.Contex } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session.name", url.QueryEscape(req.GetSession().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchCreateReadSessionStreams[0:len(c.CallOptions.BatchCreateReadSessionStreams):len(c.CallOptions.BatchCreateReadSessionStreams)], opts...) + opts = append((*c.CallOptions).BatchCreateReadSessionStreams[0:len((*c.CallOptions).BatchCreateReadSessionStreams):len((*c.CallOptions).BatchCreateReadSessionStreams)], opts...) var resp *storagepb.BatchCreateReadSessionStreamsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -281,21 +378,7 @@ func (c *BigQueryStorageClient) BatchCreateReadSessionStreams(ctx context.Contex return resp, nil } -// FinalizeStream triggers the graceful termination of a single stream in a ReadSession. This -// API can be used to dynamically adjust the parallelism of a batch processing -// task downwards without losing data. -// -// This API does not delete the stream – it remains visible in the -// ReadSession, and any data processed by the stream is not released to other -// streams. However, no additional data will be assigned to the stream once -// this call completes. Callers must continue reading data on the stream until -// the end of the stream is reached so that data which has already been -// assigned to the stream will be processed. -// -// This method will return an error if there are no other live streams -// in the Session, or if SplitReadStream() has been called on the given -// Stream. -func (c *BigQueryStorageClient) FinalizeStream(ctx context.Context, req *storagepb.FinalizeStreamRequest, opts ...gax.CallOption) error { +func (c *bigQueryStorageGRPCClient) FinalizeStream(ctx context.Context, req *storagepb.FinalizeStreamRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -303,7 +386,7 @@ func (c *BigQueryStorageClient) FinalizeStream(ctx context.Context, req *storage } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "stream.name", url.QueryEscape(req.GetStream().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.FinalizeStream[0:len(c.CallOptions.FinalizeStream):len(c.CallOptions.FinalizeStream)], opts...) + opts = append((*c.CallOptions).FinalizeStream[0:len((*c.CallOptions).FinalizeStream):len((*c.CallOptions).FinalizeStream)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.bigQueryStorageClient.FinalizeStream(ctx, req, settings.GRPC...) @@ -312,20 +395,7 @@ func (c *BigQueryStorageClient) FinalizeStream(ctx context.Context, req *storage return err } -// SplitReadStream splits a given read stream into two Streams. These streams are referred to -// as the primary and the residual of the split. The original stream can still -// be read from in the same manner as before. Both of the returned streams can -// also be read from, and the total rows return by both child streams will be -// the same as the rows read from the original stream. -// -// Moreover, the two child streams will be allocated back to back in the -// original Stream. Concretely, it is guaranteed that for streams Original, -// Primary, and Residual, that Original[0-j] = Primary[0-j] and -// Original[j-n] = Residual[0-m] once the streams have been read to -// completion. -// -// This method is guaranteed to be idempotent. -func (c *BigQueryStorageClient) SplitReadStream(ctx context.Context, req *storagepb.SplitReadStreamRequest, opts ...gax.CallOption) (*storagepb.SplitReadStreamResponse, error) { +func (c *bigQueryStorageGRPCClient) SplitReadStream(ctx context.Context, req *storagepb.SplitReadStreamRequest, opts ...gax.CallOption) (*storagepb.SplitReadStreamResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -333,7 +403,7 @@ func (c *BigQueryStorageClient) SplitReadStream(ctx context.Context, req *storag } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "original_stream.name", url.QueryEscape(req.GetOriginalStream().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SplitReadStream[0:len(c.CallOptions.SplitReadStream):len(c.CallOptions.SplitReadStream)], opts...) + opts = append((*c.CallOptions).SplitReadStream[0:len((*c.CallOptions).SplitReadStream):len((*c.CallOptions).SplitReadStream)], opts...) var resp *storagepb.SplitReadStreamResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/bigquery/storage/apiv1beta1/big_query_storage_client_example_test.go b/bigquery/storage/apiv1beta1/big_query_storage_client_example_test.go index 3cd5d5277d66..3081794495c5 100644 --- a/bigquery/storage/apiv1beta1/big_query_storage_client_example_test.go +++ b/bigquery/storage/apiv1beta1/big_query_storage_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewBigQueryStorageClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleBigQueryStorageClient_CreateReadSession() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta1" - ctx := context.Background() c, err := storage.NewBigQueryStorageClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.CreateReadSessionRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleBigQueryStorageClient_CreateReadSession() { } func ExampleBigQueryStorageClient_BatchCreateReadSessionStreams() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta1" - ctx := context.Background() c, err := storage.NewBigQueryStorageClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.BatchCreateReadSessionStreamsRequest{ // TODO: Fill request struct fields. @@ -79,6 +79,7 @@ func ExampleBigQueryStorageClient_FinalizeStream() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.FinalizeStreamRequest{ // TODO: Fill request struct fields. @@ -90,13 +91,12 @@ func ExampleBigQueryStorageClient_FinalizeStream() { } func ExampleBigQueryStorageClient_SplitReadStream() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta1" - ctx := context.Background() c, err := storage.NewBigQueryStorageClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.SplitReadStreamRequest{ // TODO: Fill request struct fields. diff --git a/bigquery/storage/apiv1beta1/doc.go b/bigquery/storage/apiv1beta1/doc.go index 6361646776fb..87dc0185543d 100644 --- a/bigquery/storage/apiv1beta1/doc.go +++ b/bigquery/storage/apiv1beta1/doc.go @@ -17,6 +17,8 @@ // Package storage is an auto-generated package for the // BigQuery Storage API. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -26,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package storage // import "cloud.google.com/go/bigquery/storage/apiv1beta1" import ( @@ -46,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/bigquery/storage/apiv1beta2/big_query_read_client.go b/bigquery/storage/apiv1beta2/big_query_read_client.go index 57369ada5b93..8eff0dbf9555 100644 --- a/bigquery/storage/apiv1beta2/big_query_read_client.go +++ b/bigquery/storage/apiv1beta2/big_query_read_client.go @@ -42,7 +42,7 @@ type BigQueryReadCallOptions struct { SplitReadStream []gax.CallOption } -func defaultBigQueryReadClientOptions() []option.ClientOption { +func defaultBigQueryReadGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("bigquerystorage.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("bigquerystorage.mtls.googleapis.com:443"), @@ -94,27 +94,127 @@ func defaultBigQueryReadCallOptions() *BigQueryReadCallOptions { } } +// internalBigQueryReadClient is an interface that defines the methods availaible from BigQuery Storage API. +type internalBigQueryReadClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateReadSession(context.Context, *storagepb.CreateReadSessionRequest, ...gax.CallOption) (*storagepb.ReadSession, error) + ReadRows(context.Context, *storagepb.ReadRowsRequest, ...gax.CallOption) (storagepb.BigQueryRead_ReadRowsClient, error) + SplitReadStream(context.Context, *storagepb.SplitReadStreamRequest, ...gax.CallOption) (*storagepb.SplitReadStreamResponse, error) +} + // BigQueryReadClient is a client for interacting with BigQuery Storage API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// BigQuery Read API. +// +// The Read API can be used to read data from BigQuery. +// +// New code should use the v1 Read API going forward, if they don’t use Write +// API at the same time. type BigQueryReadClient struct { + // The internal transport-dependent client. + internalClient internalBigQueryReadClient + + // The call options for this service. + CallOptions *BigQueryReadCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *BigQueryReadClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *BigQueryReadClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *BigQueryReadClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateReadSession creates a new read session. A read session divides the contents of a +// BigQuery table into one or more streams, which can then be used to read +// data from the table. The read session also specifies properties of the +// data to be read, such as a list of columns or a push-down filter describing +// the rows to be returned. +// +// A particular row can be read by at most one stream. When the caller has +// reached the end of each stream in the session, then all the data in the +// table has been read. +// +// Data is assigned to each stream such that roughly the same number of +// rows can be read from each stream. Because the server-side unit for +// assigning data is collections of rows, the API does not guarantee that +// each stream will return the same number or rows. Additionally, the +// limits are enforced based on the number of pre-filtered rows, so some +// filters can lead to lopsided assignments. +// +// Read sessions automatically expire 24 hours after they are created and do +// not require manual clean-up by the caller. +func (c *BigQueryReadClient) CreateReadSession(ctx context.Context, req *storagepb.CreateReadSessionRequest, opts ...gax.CallOption) (*storagepb.ReadSession, error) { + return c.internalClient.CreateReadSession(ctx, req, opts...) +} + +// ReadRows reads rows from the stream in the format prescribed by the ReadSession. +// Each response contains one or more table rows, up to a maximum of 100 MiB +// per response; read requests which attempt to read individual rows larger +// than 100 MiB will fail. +// +// Each request also returns a set of stream statistics reflecting the current +// state of the stream. +func (c *BigQueryReadClient) ReadRows(ctx context.Context, req *storagepb.ReadRowsRequest, opts ...gax.CallOption) (storagepb.BigQueryRead_ReadRowsClient, error) { + return c.internalClient.ReadRows(ctx, req, opts...) +} + +// SplitReadStream splits a given ReadStream into two ReadStream objects. These +// ReadStream objects are referred to as the primary and the residual +// streams of the split. The original ReadStream can still be read from in +// the same manner as before. Both of the returned ReadStream objects can +// also be read from, and the rows returned by both child streams will be +// the same as the rows read from the original stream. +// +// Moreover, the two child streams will be allocated back-to-back in the +// original ReadStream. Concretely, it is guaranteed that for streams +// original, primary, and residual, that original[0-j] = primary[0-j] and +// original[j-n] = residual[0-m] once the streams have been read to +// completion. +func (c *BigQueryReadClient) SplitReadStream(ctx context.Context, req *storagepb.SplitReadStreamRequest, opts ...gax.CallOption) (*storagepb.SplitReadStreamResponse, error) { + return c.internalClient.SplitReadStream(ctx, req, opts...) +} + +// bigQueryReadGRPCClient is a client for interacting with BigQuery Storage API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type bigQueryReadGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing BigQueryReadClient + CallOptions **BigQueryReadCallOptions + // The gRPC API client. bigQueryReadClient storagepb.BigQueryReadClient - // The call options for this service. - CallOptions *BigQueryReadCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewBigQueryReadClient creates a new big query read client. +// NewBigQueryReadClient creates a new big query read client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // BigQuery Read API. // @@ -123,8 +223,7 @@ type BigQueryReadClient struct { // New code should use the v1 Read API going forward, if they don’t use Write // API at the same time. func NewBigQueryReadClient(ctx context.Context, opts ...option.ClientOption) (*BigQueryReadClient, error) { - clientOpts := defaultBigQueryReadClientOptions() - + clientOpts := defaultBigQueryReadGRPCClientOptions() if newBigQueryReadClientHook != nil { hookOpts, err := newBigQueryReadClientHook(ctx, clientHookParams{}) if err != nil { @@ -142,60 +241,44 @@ func NewBigQueryReadClient(ctx context.Context, opts ...option.ClientOption) (*B if err != nil { return nil, err } - c := &BigQueryReadClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultBigQueryReadCallOptions(), + client := BigQueryReadClient{CallOptions: defaultBigQueryReadCallOptions()} + c := &bigQueryReadGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, bigQueryReadClient: storagepb.NewBigQueryReadClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *BigQueryReadClient) Connection() *grpc.ClientConn { +func (c *bigQueryReadGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *BigQueryReadClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *BigQueryReadClient) setGoogleClientInfo(keyval ...string) { +func (c *bigQueryReadGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateReadSession creates a new read session. A read session divides the contents of a -// BigQuery table into one or more streams, which can then be used to read -// data from the table. The read session also specifies properties of the -// data to be read, such as a list of columns or a push-down filter describing -// the rows to be returned. -// -// A particular row can be read by at most one stream. When the caller has -// reached the end of each stream in the session, then all the data in the -// table has been read. -// -// Data is assigned to each stream such that roughly the same number of -// rows can be read from each stream. Because the server-side unit for -// assigning data is collections of rows, the API does not guarantee that -// each stream will return the same number or rows. Additionally, the -// limits are enforced based on the number of pre-filtered rows, so some -// filters can lead to lopsided assignments. -// -// Read sessions automatically expire 24 hours after they are created and do -// not require manual clean-up by the caller. -func (c *BigQueryReadClient) CreateReadSession(ctx context.Context, req *storagepb.CreateReadSessionRequest, opts ...gax.CallOption) (*storagepb.ReadSession, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *bigQueryReadGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *bigQueryReadGRPCClient) CreateReadSession(ctx context.Context, req *storagepb.CreateReadSessionRequest, opts ...gax.CallOption) (*storagepb.ReadSession, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -203,7 +286,7 @@ func (c *BigQueryReadClient) CreateReadSession(ctx context.Context, req *storage } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "read_session.table", url.QueryEscape(req.GetReadSession().GetTable()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateReadSession[0:len(c.CallOptions.CreateReadSession):len(c.CallOptions.CreateReadSession)], opts...) + opts = append((*c.CallOptions).CreateReadSession[0:len((*c.CallOptions).CreateReadSession):len((*c.CallOptions).CreateReadSession)], opts...) var resp *storagepb.ReadSession err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -216,17 +299,9 @@ func (c *BigQueryReadClient) CreateReadSession(ctx context.Context, req *storage return resp, nil } -// ReadRows reads rows from the stream in the format prescribed by the ReadSession. -// Each response contains one or more table rows, up to a maximum of 100 MiB -// per response; read requests which attempt to read individual rows larger -// than 100 MiB will fail. -// -// Each request also returns a set of stream statistics reflecting the current -// state of the stream. -func (c *BigQueryReadClient) ReadRows(ctx context.Context, req *storagepb.ReadRowsRequest, opts ...gax.CallOption) (storagepb.BigQueryRead_ReadRowsClient, error) { +func (c *bigQueryReadGRPCClient) ReadRows(ctx context.Context, req *storagepb.ReadRowsRequest, opts ...gax.CallOption) (storagepb.BigQueryRead_ReadRowsClient, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "read_stream", url.QueryEscape(req.GetReadStream()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ReadRows[0:len(c.CallOptions.ReadRows):len(c.CallOptions.ReadRows)], opts...) var resp storagepb.BigQueryRead_ReadRowsClient err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -239,19 +314,7 @@ func (c *BigQueryReadClient) ReadRows(ctx context.Context, req *storagepb.ReadRo return resp, nil } -// SplitReadStream splits a given ReadStream into two ReadStream objects. These -// ReadStream objects are referred to as the primary and the residual -// streams of the split. The original ReadStream can still be read from in -// the same manner as before. Both of the returned ReadStream objects can -// also be read from, and the rows returned by both child streams will be -// the same as the rows read from the original stream. -// -// Moreover, the two child streams will be allocated back-to-back in the -// original ReadStream. Concretely, it is guaranteed that for streams -// original, primary, and residual, that original[0-j] = primary[0-j] and -// original[j-n] = residual[0-m] once the streams have been read to -// completion. -func (c *BigQueryReadClient) SplitReadStream(ctx context.Context, req *storagepb.SplitReadStreamRequest, opts ...gax.CallOption) (*storagepb.SplitReadStreamResponse, error) { +func (c *bigQueryReadGRPCClient) SplitReadStream(ctx context.Context, req *storagepb.SplitReadStreamRequest, opts ...gax.CallOption) (*storagepb.SplitReadStreamResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -259,7 +322,7 @@ func (c *BigQueryReadClient) SplitReadStream(ctx context.Context, req *storagepb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SplitReadStream[0:len(c.CallOptions.SplitReadStream):len(c.CallOptions.SplitReadStream)], opts...) + opts = append((*c.CallOptions).SplitReadStream[0:len((*c.CallOptions).SplitReadStream):len((*c.CallOptions).SplitReadStream)], opts...) var resp *storagepb.SplitReadStreamResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/bigquery/storage/apiv1beta2/big_query_read_client_example_test.go b/bigquery/storage/apiv1beta2/big_query_read_client_example_test.go index f7e5ac55478a..346abef99522 100644 --- a/bigquery/storage/apiv1beta2/big_query_read_client_example_test.go +++ b/bigquery/storage/apiv1beta2/big_query_read_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewBigQueryReadClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleBigQueryReadClient_CreateReadSession() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta2" - ctx := context.Background() c, err := storage.NewBigQueryReadClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.CreateReadSessionRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleBigQueryReadClient_CreateReadSession() { } func ExampleBigQueryReadClient_SplitReadStream() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta2" - ctx := context.Background() c, err := storage.NewBigQueryReadClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.SplitReadStreamRequest{ // TODO: Fill request struct fields. diff --git a/bigquery/storage/apiv1beta2/big_query_write_client.go b/bigquery/storage/apiv1beta2/big_query_write_client.go index 59b617828635..7ae08da80a6e 100644 --- a/bigquery/storage/apiv1beta2/big_query_write_client.go +++ b/bigquery/storage/apiv1beta2/big_query_write_client.go @@ -45,7 +45,7 @@ type BigQueryWriteCallOptions struct { FlushRows []gax.CallOption } -func defaultBigQueryWriteClientOptions() []option.ClientOption { +func defaultBigQueryWriteGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("bigquerystorage.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("bigquerystorage.mtls.googleapis.com:443"), @@ -135,34 +135,146 @@ func defaultBigQueryWriteCallOptions() *BigQueryWriteCallOptions { } } +// internalBigQueryWriteClient is an interface that defines the methods availaible from BigQuery Storage API. +type internalBigQueryWriteClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateWriteStream(context.Context, *storagepb.CreateWriteStreamRequest, ...gax.CallOption) (*storagepb.WriteStream, error) + AppendRows(context.Context, ...gax.CallOption) (storagepb.BigQueryWrite_AppendRowsClient, error) + GetWriteStream(context.Context, *storagepb.GetWriteStreamRequest, ...gax.CallOption) (*storagepb.WriteStream, error) + FinalizeWriteStream(context.Context, *storagepb.FinalizeWriteStreamRequest, ...gax.CallOption) (*storagepb.FinalizeWriteStreamResponse, error) + BatchCommitWriteStreams(context.Context, *storagepb.BatchCommitWriteStreamsRequest, ...gax.CallOption) (*storagepb.BatchCommitWriteStreamsResponse, error) + FlushRows(context.Context, *storagepb.FlushRowsRequest, ...gax.CallOption) (*storagepb.FlushRowsResponse, error) +} + // BigQueryWriteClient is a client for interacting with BigQuery Storage API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// BigQuery Write API. +// +// The Write API can be used to write data to BigQuery. type BigQueryWriteClient struct { + // The internal transport-dependent client. + internalClient internalBigQueryWriteClient + + // The call options for this service. + CallOptions *BigQueryWriteCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *BigQueryWriteClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *BigQueryWriteClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *BigQueryWriteClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateWriteStream creates a write stream to the given table. +// Additionally, every table has a special COMMITTED stream named ‘_default’ +// to which data can be written. This stream doesn’t need to be created using +// CreateWriteStream. It is a stream that can be used simultaneously by any +// number of clients. Data written to this stream is considered committed as +// soon as an acknowledgement is received. +func (c *BigQueryWriteClient) CreateWriteStream(ctx context.Context, req *storagepb.CreateWriteStreamRequest, opts ...gax.CallOption) (*storagepb.WriteStream, error) { + return c.internalClient.CreateWriteStream(ctx, req, opts...) +} + +// AppendRows appends data to the given stream. +// +// If offset is specified, the offset is checked against the end of +// stream. The server returns OUT_OF_RANGE in AppendRowsResponse if an +// attempt is made to append to an offset beyond the current end of the stream +// or ALREADY_EXISTS if user provids an offset that has already been +// written to. User can retry with adjusted offset within the same RPC +// stream. If offset is not specified, append happens at the end of the +// stream. +// +// The response contains the offset at which the append happened. Responses +// are received in the same order in which requests are sent. There will be +// one response for each successful request. If the offset is not set in +// response, it means append didn’t happen due to some errors. If one request +// fails, all the subsequent requests will also fail until a success request +// is made again. +// +// If the stream is of PENDING type, data will only be available for read +// operations after the stream is committed. +func (c *BigQueryWriteClient) AppendRows(ctx context.Context, opts ...gax.CallOption) (storagepb.BigQueryWrite_AppendRowsClient, error) { + return c.internalClient.AppendRows(ctx, opts...) +} + +// GetWriteStream gets a write stream. +func (c *BigQueryWriteClient) GetWriteStream(ctx context.Context, req *storagepb.GetWriteStreamRequest, opts ...gax.CallOption) (*storagepb.WriteStream, error) { + return c.internalClient.GetWriteStream(ctx, req, opts...) +} + +// FinalizeWriteStream finalize a write stream so that no new data can be appended to the +// stream. Finalize is not supported on the ‘_default’ stream. +func (c *BigQueryWriteClient) FinalizeWriteStream(ctx context.Context, req *storagepb.FinalizeWriteStreamRequest, opts ...gax.CallOption) (*storagepb.FinalizeWriteStreamResponse, error) { + return c.internalClient.FinalizeWriteStream(ctx, req, opts...) +} + +// BatchCommitWriteStreams atomically commits a group of PENDING streams that belong to the same +// parent table. +// Streams must be finalized before commit and cannot be committed multiple +// times. Once a stream is committed, data in the stream becomes available +// for read operations. +func (c *BigQueryWriteClient) BatchCommitWriteStreams(ctx context.Context, req *storagepb.BatchCommitWriteStreamsRequest, opts ...gax.CallOption) (*storagepb.BatchCommitWriteStreamsResponse, error) { + return c.internalClient.BatchCommitWriteStreams(ctx, req, opts...) +} + +// FlushRows flushes rows to a BUFFERED stream. +// If users are appending rows to BUFFERED stream, flush operation is +// required in order for the rows to become available for reading. A +// Flush operation flushes up to any previously flushed offset in a BUFFERED +// stream, to the offset specified in the request. +// Flush is not supported on the _default stream, since it is not BUFFERED. +func (c *BigQueryWriteClient) FlushRows(ctx context.Context, req *storagepb.FlushRowsRequest, opts ...gax.CallOption) (*storagepb.FlushRowsResponse, error) { + return c.internalClient.FlushRows(ctx, req, opts...) +} + +// bigQueryWriteGRPCClient is a client for interacting with BigQuery Storage API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type bigQueryWriteGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing BigQueryWriteClient + CallOptions **BigQueryWriteCallOptions + // The gRPC API client. bigQueryWriteClient storagepb.BigQueryWriteClient - // The call options for this service. - CallOptions *BigQueryWriteCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewBigQueryWriteClient creates a new big query write client. +// NewBigQueryWriteClient creates a new big query write client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // BigQuery Write API. // // The Write API can be used to write data to BigQuery. func NewBigQueryWriteClient(ctx context.Context, opts ...option.ClientOption) (*BigQueryWriteClient, error) { - clientOpts := defaultBigQueryWriteClientOptions() - + clientOpts := defaultBigQueryWriteGRPCClientOptions() if newBigQueryWriteClientHook != nil { hookOpts, err := newBigQueryWriteClientHook(ctx, clientHookParams{}) if err != nil { @@ -180,47 +292,44 @@ func NewBigQueryWriteClient(ctx context.Context, opts ...option.ClientOption) (* if err != nil { return nil, err } - c := &BigQueryWriteClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultBigQueryWriteCallOptions(), + client := BigQueryWriteClient{CallOptions: defaultBigQueryWriteCallOptions()} + c := &bigQueryWriteGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, bigQueryWriteClient: storagepb.NewBigQueryWriteClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *BigQueryWriteClient) Connection() *grpc.ClientConn { +func (c *bigQueryWriteGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *BigQueryWriteClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *BigQueryWriteClient) setGoogleClientInfo(keyval ...string) { +func (c *bigQueryWriteGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateWriteStream creates a write stream to the given table. -// Additionally, every table has a special COMMITTED stream named ‘_default’ -// to which data can be written. This stream doesn’t need to be created using -// CreateWriteStream. It is a stream that can be used simultaneously by any -// number of clients. Data written to this stream is considered committed as -// soon as an acknowledgement is received. -func (c *BigQueryWriteClient) CreateWriteStream(ctx context.Context, req *storagepb.CreateWriteStreamRequest, opts ...gax.CallOption) (*storagepb.WriteStream, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *bigQueryWriteGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *bigQueryWriteGRPCClient) CreateWriteStream(ctx context.Context, req *storagepb.CreateWriteStreamRequest, opts ...gax.CallOption) (*storagepb.WriteStream, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -228,7 +337,7 @@ func (c *BigQueryWriteClient) CreateWriteStream(ctx context.Context, req *storag } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateWriteStream[0:len(c.CallOptions.CreateWriteStream):len(c.CallOptions.CreateWriteStream)], opts...) + opts = append((*c.CallOptions).CreateWriteStream[0:len((*c.CallOptions).CreateWriteStream):len((*c.CallOptions).CreateWriteStream)], opts...) var resp *storagepb.WriteStream err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -241,29 +350,10 @@ func (c *BigQueryWriteClient) CreateWriteStream(ctx context.Context, req *storag return resp, nil } -// AppendRows appends data to the given stream. -// -// If offset is specified, the offset is checked against the end of -// stream. The server returns OUT_OF_RANGE in AppendRowsResponse if an -// attempt is made to append to an offset beyond the current end of the stream -// or ALREADY_EXISTS if user provids an offset that has already been -// written to. User can retry with adjusted offset within the same RPC -// stream. If offset is not specified, append happens at the end of the -// stream. -// -// The response contains the offset at which the append happened. Responses -// are received in the same order in which requests are sent. There will be -// one response for each successful request. If the offset is not set in -// response, it means append didn’t happen due to some errors. If one request -// fails, all the subsequent requests will also fail until a success request -// is made again. -// -// If the stream is of PENDING type, data will only be available for read -// operations after the stream is committed. -func (c *BigQueryWriteClient) AppendRows(ctx context.Context, opts ...gax.CallOption) (storagepb.BigQueryWrite_AppendRowsClient, error) { +func (c *bigQueryWriteGRPCClient) AppendRows(ctx context.Context, opts ...gax.CallOption) (storagepb.BigQueryWrite_AppendRowsClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.AppendRows[0:len(c.CallOptions.AppendRows):len(c.CallOptions.AppendRows)], opts...) var resp storagepb.BigQueryWrite_AppendRowsClient + opts = append((*c.CallOptions).AppendRows[0:len((*c.CallOptions).AppendRows):len((*c.CallOptions).AppendRows)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.bigQueryWriteClient.AppendRows(ctx, settings.GRPC...) @@ -275,8 +365,7 @@ func (c *BigQueryWriteClient) AppendRows(ctx context.Context, opts ...gax.CallOp return resp, nil } -// GetWriteStream gets a write stream. -func (c *BigQueryWriteClient) GetWriteStream(ctx context.Context, req *storagepb.GetWriteStreamRequest, opts ...gax.CallOption) (*storagepb.WriteStream, error) { +func (c *bigQueryWriteGRPCClient) GetWriteStream(ctx context.Context, req *storagepb.GetWriteStreamRequest, opts ...gax.CallOption) (*storagepb.WriteStream, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -284,7 +373,7 @@ func (c *BigQueryWriteClient) GetWriteStream(ctx context.Context, req *storagepb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetWriteStream[0:len(c.CallOptions.GetWriteStream):len(c.CallOptions.GetWriteStream)], opts...) + opts = append((*c.CallOptions).GetWriteStream[0:len((*c.CallOptions).GetWriteStream):len((*c.CallOptions).GetWriteStream)], opts...) var resp *storagepb.WriteStream err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -297,9 +386,7 @@ func (c *BigQueryWriteClient) GetWriteStream(ctx context.Context, req *storagepb return resp, nil } -// FinalizeWriteStream finalize a write stream so that no new data can be appended to the -// stream. Finalize is not supported on the ‘_default’ stream. -func (c *BigQueryWriteClient) FinalizeWriteStream(ctx context.Context, req *storagepb.FinalizeWriteStreamRequest, opts ...gax.CallOption) (*storagepb.FinalizeWriteStreamResponse, error) { +func (c *bigQueryWriteGRPCClient) FinalizeWriteStream(ctx context.Context, req *storagepb.FinalizeWriteStreamRequest, opts ...gax.CallOption) (*storagepb.FinalizeWriteStreamResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -307,7 +394,7 @@ func (c *BigQueryWriteClient) FinalizeWriteStream(ctx context.Context, req *stor } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.FinalizeWriteStream[0:len(c.CallOptions.FinalizeWriteStream):len(c.CallOptions.FinalizeWriteStream)], opts...) + opts = append((*c.CallOptions).FinalizeWriteStream[0:len((*c.CallOptions).FinalizeWriteStream):len((*c.CallOptions).FinalizeWriteStream)], opts...) var resp *storagepb.FinalizeWriteStreamResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -320,12 +407,7 @@ func (c *BigQueryWriteClient) FinalizeWriteStream(ctx context.Context, req *stor return resp, nil } -// BatchCommitWriteStreams atomically commits a group of PENDING streams that belong to the same -// parent table. -// Streams must be finalized before commit and cannot be committed multiple -// times. Once a stream is committed, data in the stream becomes available -// for read operations. -func (c *BigQueryWriteClient) BatchCommitWriteStreams(ctx context.Context, req *storagepb.BatchCommitWriteStreamsRequest, opts ...gax.CallOption) (*storagepb.BatchCommitWriteStreamsResponse, error) { +func (c *bigQueryWriteGRPCClient) BatchCommitWriteStreams(ctx context.Context, req *storagepb.BatchCommitWriteStreamsRequest, opts ...gax.CallOption) (*storagepb.BatchCommitWriteStreamsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -333,7 +415,7 @@ func (c *BigQueryWriteClient) BatchCommitWriteStreams(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchCommitWriteStreams[0:len(c.CallOptions.BatchCommitWriteStreams):len(c.CallOptions.BatchCommitWriteStreams)], opts...) + opts = append((*c.CallOptions).BatchCommitWriteStreams[0:len((*c.CallOptions).BatchCommitWriteStreams):len((*c.CallOptions).BatchCommitWriteStreams)], opts...) var resp *storagepb.BatchCommitWriteStreamsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -346,13 +428,7 @@ func (c *BigQueryWriteClient) BatchCommitWriteStreams(ctx context.Context, req * return resp, nil } -// FlushRows flushes rows to a BUFFERED stream. -// If users are appending rows to BUFFERED stream, flush operation is -// required in order for the rows to become available for reading. A -// Flush operation flushes up to any previously flushed offset in a BUFFERED -// stream, to the offset specified in the request. -// Flush is not supported on the _default stream, since it is not BUFFERED. -func (c *BigQueryWriteClient) FlushRows(ctx context.Context, req *storagepb.FlushRowsRequest, opts ...gax.CallOption) (*storagepb.FlushRowsResponse, error) { +func (c *bigQueryWriteGRPCClient) FlushRows(ctx context.Context, req *storagepb.FlushRowsRequest, opts ...gax.CallOption) (*storagepb.FlushRowsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -360,7 +436,7 @@ func (c *BigQueryWriteClient) FlushRows(ctx context.Context, req *storagepb.Flus } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "write_stream", url.QueryEscape(req.GetWriteStream()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.FlushRows[0:len(c.CallOptions.FlushRows):len(c.CallOptions.FlushRows)], opts...) + opts = append((*c.CallOptions).FlushRows[0:len((*c.CallOptions).FlushRows):len((*c.CallOptions).FlushRows)], opts...) var resp *storagepb.FlushRowsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/bigquery/storage/apiv1beta2/big_query_write_client_example_test.go b/bigquery/storage/apiv1beta2/big_query_write_client_example_test.go index 2d9808f6060b..78e08050fb97 100644 --- a/bigquery/storage/apiv1beta2/big_query_write_client_example_test.go +++ b/bigquery/storage/apiv1beta2/big_query_write_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewBigQueryWriteClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleBigQueryWriteClient_CreateWriteStream() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta2" - ctx := context.Background() c, err := storage.NewBigQueryWriteClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.CreateWriteStreamRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleBigQueryWriteClient_CreateWriteStream() { } func ExampleBigQueryWriteClient_AppendRows() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta2" - ctx := context.Background() c, err := storage.NewBigQueryWriteClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.AppendRows(ctx) if err != nil { // TODO: Handle error. @@ -91,13 +91,12 @@ func ExampleBigQueryWriteClient_AppendRows() { } func ExampleBigQueryWriteClient_GetWriteStream() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta2" - ctx := context.Background() c, err := storage.NewBigQueryWriteClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.GetWriteStreamRequest{ // TODO: Fill request struct fields. @@ -111,13 +110,12 @@ func ExampleBigQueryWriteClient_GetWriteStream() { } func ExampleBigQueryWriteClient_FinalizeWriteStream() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta2" - ctx := context.Background() c, err := storage.NewBigQueryWriteClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.FinalizeWriteStreamRequest{ // TODO: Fill request struct fields. @@ -131,13 +129,12 @@ func ExampleBigQueryWriteClient_FinalizeWriteStream() { } func ExampleBigQueryWriteClient_BatchCommitWriteStreams() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta2" - ctx := context.Background() c, err := storage.NewBigQueryWriteClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.BatchCommitWriteStreamsRequest{ // TODO: Fill request struct fields. @@ -151,13 +148,12 @@ func ExampleBigQueryWriteClient_BatchCommitWriteStreams() { } func ExampleBigQueryWriteClient_FlushRows() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta2" - ctx := context.Background() c, err := storage.NewBigQueryWriteClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.FlushRowsRequest{ // TODO: Fill request struct fields. diff --git a/bigquery/storage/apiv1beta2/doc.go b/bigquery/storage/apiv1beta2/doc.go index 7ee4cb78287d..8bb05dbe2f1e 100644 --- a/bigquery/storage/apiv1beta2/doc.go +++ b/bigquery/storage/apiv1beta2/doc.go @@ -17,6 +17,8 @@ // Package storage is an auto-generated package for the // BigQuery Storage API. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -26,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package storage // import "cloud.google.com/go/bigquery/storage/apiv1beta2" import ( @@ -46,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/billing/apiv1/cloud_billing_client.go b/billing/apiv1/cloud_billing_client.go index f7a3ced30be7..1a98496250c6 100644 --- a/billing/apiv1/cloud_billing_client.go +++ b/billing/apiv1/cloud_billing_client.go @@ -52,7 +52,7 @@ type CloudBillingCallOptions struct { TestIamPermissions []gax.CallOption } -func defaultCloudBillingClientOptions() []option.ClientOption { +func defaultCloudBillingGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudbilling.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudbilling.mtls.googleapis.com:443"), @@ -178,32 +178,194 @@ func defaultCloudBillingCallOptions() *CloudBillingCallOptions { } } +// internalCloudBillingClient is an interface that defines the methods availaible from Cloud Billing API. +type internalCloudBillingClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + GetBillingAccount(context.Context, *billingpb.GetBillingAccountRequest, ...gax.CallOption) (*billingpb.BillingAccount, error) + ListBillingAccounts(context.Context, *billingpb.ListBillingAccountsRequest, ...gax.CallOption) *BillingAccountIterator + UpdateBillingAccount(context.Context, *billingpb.UpdateBillingAccountRequest, ...gax.CallOption) (*billingpb.BillingAccount, error) + CreateBillingAccount(context.Context, *billingpb.CreateBillingAccountRequest, ...gax.CallOption) (*billingpb.BillingAccount, error) + ListProjectBillingInfo(context.Context, *billingpb.ListProjectBillingInfoRequest, ...gax.CallOption) *ProjectBillingInfoIterator + GetProjectBillingInfo(context.Context, *billingpb.GetProjectBillingInfoRequest, ...gax.CallOption) (*billingpb.ProjectBillingInfo, error) + UpdateProjectBillingInfo(context.Context, *billingpb.UpdateProjectBillingInfoRequest, ...gax.CallOption) (*billingpb.ProjectBillingInfo, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) +} + // CloudBillingClient is a client for interacting with Cloud Billing API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Retrieves GCP Console billing accounts and associates them with projects. type CloudBillingClient struct { + // The internal transport-dependent client. + internalClient internalCloudBillingClient + + // The call options for this service. + CallOptions *CloudBillingCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CloudBillingClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CloudBillingClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CloudBillingClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// GetBillingAccount gets information about a billing account. The current authenticated user +// must be a viewer of the billing +// account (at https://cloud.google.com/billing/docs/how-to/billing-access). +func (c *CloudBillingClient) GetBillingAccount(ctx context.Context, req *billingpb.GetBillingAccountRequest, opts ...gax.CallOption) (*billingpb.BillingAccount, error) { + return c.internalClient.GetBillingAccount(ctx, req, opts...) +} + +// ListBillingAccounts lists the billing accounts that the current authenticated user has +// permission to +// view (at https://cloud.google.com/billing/docs/how-to/billing-access). +func (c *CloudBillingClient) ListBillingAccounts(ctx context.Context, req *billingpb.ListBillingAccountsRequest, opts ...gax.CallOption) *BillingAccountIterator { + return c.internalClient.ListBillingAccounts(ctx, req, opts...) +} + +// UpdateBillingAccount updates a billing account’s fields. +// Currently the only field that can be edited is display_name. +// The current authenticated user must have the billing.accounts.update +// IAM permission, which is typically given to the +// administrator (at https://cloud.google.com/billing/docs/how-to/billing-access) +// of the billing account. +func (c *CloudBillingClient) UpdateBillingAccount(ctx context.Context, req *billingpb.UpdateBillingAccountRequest, opts ...gax.CallOption) (*billingpb.BillingAccount, error) { + return c.internalClient.UpdateBillingAccount(ctx, req, opts...) +} + +// CreateBillingAccount creates a billing account. +// This method can only be used to create +// billing subaccounts (at https://cloud.google.com/billing/docs/concepts) +// by GCP resellers. +// When creating a subaccount, the current authenticated user must have the +// billing.accounts.update IAM permission on the master account, which is +// typically given to billing account +// administrators (at https://cloud.google.com/billing/docs/how-to/billing-access). +// This method will return an error if the master account has not been +// provisioned as a reseller account. +func (c *CloudBillingClient) CreateBillingAccount(ctx context.Context, req *billingpb.CreateBillingAccountRequest, opts ...gax.CallOption) (*billingpb.BillingAccount, error) { + return c.internalClient.CreateBillingAccount(ctx, req, opts...) +} + +// ListProjectBillingInfo lists the projects associated with a billing account. The current +// authenticated user must have the billing.resourceAssociations.list IAM +// permission, which is often given to billing account +// viewers (at https://cloud.google.com/billing/docs/how-to/billing-access). +func (c *CloudBillingClient) ListProjectBillingInfo(ctx context.Context, req *billingpb.ListProjectBillingInfoRequest, opts ...gax.CallOption) *ProjectBillingInfoIterator { + return c.internalClient.ListProjectBillingInfo(ctx, req, opts...) +} + +// GetProjectBillingInfo gets the billing information for a project. The current authenticated user +// must have permission to view the +// project (at https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo). +func (c *CloudBillingClient) GetProjectBillingInfo(ctx context.Context, req *billingpb.GetProjectBillingInfoRequest, opts ...gax.CallOption) (*billingpb.ProjectBillingInfo, error) { + return c.internalClient.GetProjectBillingInfo(ctx, req, opts...) +} + +// UpdateProjectBillingInfo sets or updates the billing account associated with a project. You specify +// the new billing account by setting the billing_account_name in the +// ProjectBillingInfo resource to the resource name of a billing account. +// Associating a project with an open billing account enables billing on the +// project and allows charges for resource usage. If the project already had a +// billing account, this method changes the billing account used for resource +// usage charges. +// +// Note: Incurred charges that have not yet been reported in the transaction +// history of the GCP Console might be billed to the new billing +// account, even if the charge occurred before the new billing account was +// assigned to the project. +// +// The current authenticated user must have ownership privileges for both the +// project (at https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo) and the billing +// account (at https://cloud.google.com/billing/docs/how-to/billing-access). +// +// You can disable billing on the project by setting the +// billing_account_name field to empty. This action disassociates the +// current billing account from the project. Any billable activity of your +// in-use services will stop, and your application could stop functioning as +// expected. Any unbilled charges to date will be billed to the previously +// associated account. The current authenticated user must be either an owner +// of the project or an owner of the billing account for the project. +// +// Note that associating a project with a closed billing account will have +// much the same effect as disabling billing on the project: any paid +// resources used by the project will be shut down. Thus, unless you wish to +// disable billing, you should always call this method with the name of an +// open billing account. +func (c *CloudBillingClient) UpdateProjectBillingInfo(ctx context.Context, req *billingpb.UpdateProjectBillingInfoRequest, opts ...gax.CallOption) (*billingpb.ProjectBillingInfo, error) { + return c.internalClient.UpdateProjectBillingInfo(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy for a billing account. +// The caller must have the billing.accounts.getIamPolicy permission on the +// account, which is often given to billing account +// viewers (at https://cloud.google.com/billing/docs/how-to/billing-access). +func (c *CloudBillingClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// SetIamPolicy sets the access control policy for a billing account. Replaces any existing +// policy. +// The caller must have the billing.accounts.setIamPolicy permission on the +// account, which is often given to billing account +// administrators (at https://cloud.google.com/billing/docs/how-to/billing-access). +func (c *CloudBillingClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions tests the access control policy for a billing account. This method takes +// the resource and a set of permissions as input and returns the subset of +// the input permissions that the caller is allowed for that resource. +func (c *CloudBillingClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// cloudBillingGRPCClient is a client for interacting with Cloud Billing API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudBillingGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CloudBillingClient + CallOptions **CloudBillingCallOptions + // The gRPC API client. cloudBillingClient billingpb.CloudBillingClient - // The call options for this service. - CallOptions *CloudBillingCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCloudBillingClient creates a new cloud billing client. +// NewCloudBillingClient creates a new cloud billing client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Retrieves GCP Console billing accounts and associates them with projects. func NewCloudBillingClient(ctx context.Context, opts ...option.ClientOption) (*CloudBillingClient, error) { - clientOpts := defaultCloudBillingClientOptions() - + clientOpts := defaultCloudBillingGRPCClientOptions() if newCloudBillingClientHook != nil { hookOpts, err := newCloudBillingClientHook(ctx, clientHookParams{}) if err != nil { @@ -221,44 +383,44 @@ func NewCloudBillingClient(ctx context.Context, opts ...option.ClientOption) (*C if err != nil { return nil, err } - c := &CloudBillingClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultCloudBillingCallOptions(), + client := CloudBillingClient{CallOptions: defaultCloudBillingCallOptions()} + c := &cloudBillingGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, cloudBillingClient: billingpb.NewCloudBillingClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CloudBillingClient) Connection() *grpc.ClientConn { +func (c *cloudBillingGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CloudBillingClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CloudBillingClient) setGoogleClientInfo(keyval ...string) { +func (c *cloudBillingGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// GetBillingAccount gets information about a billing account. The current authenticated user -// must be a viewer of the billing -// account (at https://cloud.google.com/billing/docs/how-to/billing-access). -func (c *CloudBillingClient) GetBillingAccount(ctx context.Context, req *billingpb.GetBillingAccountRequest, opts ...gax.CallOption) (*billingpb.BillingAccount, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudBillingGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *cloudBillingGRPCClient) GetBillingAccount(ctx context.Context, req *billingpb.GetBillingAccountRequest, opts ...gax.CallOption) (*billingpb.BillingAccount, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -266,7 +428,7 @@ func (c *CloudBillingClient) GetBillingAccount(ctx context.Context, req *billing } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetBillingAccount[0:len(c.CallOptions.GetBillingAccount):len(c.CallOptions.GetBillingAccount)], opts...) + opts = append((*c.CallOptions).GetBillingAccount[0:len((*c.CallOptions).GetBillingAccount):len((*c.CallOptions).GetBillingAccount)], opts...) var resp *billingpb.BillingAccount err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -279,12 +441,9 @@ func (c *CloudBillingClient) GetBillingAccount(ctx context.Context, req *billing return resp, nil } -// ListBillingAccounts lists the billing accounts that the current authenticated user has -// permission to -// view (at https://cloud.google.com/billing/docs/how-to/billing-access). -func (c *CloudBillingClient) ListBillingAccounts(ctx context.Context, req *billingpb.ListBillingAccountsRequest, opts ...gax.CallOption) *BillingAccountIterator { +func (c *cloudBillingGRPCClient) ListBillingAccounts(ctx context.Context, req *billingpb.ListBillingAccountsRequest, opts ...gax.CallOption) *BillingAccountIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListBillingAccounts[0:len(c.CallOptions.ListBillingAccounts):len(c.CallOptions.ListBillingAccounts)], opts...) + opts = append((*c.CallOptions).ListBillingAccounts[0:len((*c.CallOptions).ListBillingAccounts):len((*c.CallOptions).ListBillingAccounts)], opts...) it := &BillingAccountIterator{} req = proto.Clone(req).(*billingpb.ListBillingAccountsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*billingpb.BillingAccount, string, error) { @@ -321,13 +480,7 @@ func (c *CloudBillingClient) ListBillingAccounts(ctx context.Context, req *billi return it } -// UpdateBillingAccount updates a billing account’s fields. -// Currently the only field that can be edited is display_name. -// The current authenticated user must have the billing.accounts.update -// IAM permission, which is typically given to the -// administrator (at https://cloud.google.com/billing/docs/how-to/billing-access) -// of the billing account. -func (c *CloudBillingClient) UpdateBillingAccount(ctx context.Context, req *billingpb.UpdateBillingAccountRequest, opts ...gax.CallOption) (*billingpb.BillingAccount, error) { +func (c *cloudBillingGRPCClient) UpdateBillingAccount(ctx context.Context, req *billingpb.UpdateBillingAccountRequest, opts ...gax.CallOption) (*billingpb.BillingAccount, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -335,7 +488,7 @@ func (c *CloudBillingClient) UpdateBillingAccount(ctx context.Context, req *bill } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateBillingAccount[0:len(c.CallOptions.UpdateBillingAccount):len(c.CallOptions.UpdateBillingAccount)], opts...) + opts = append((*c.CallOptions).UpdateBillingAccount[0:len((*c.CallOptions).UpdateBillingAccount):len((*c.CallOptions).UpdateBillingAccount)], opts...) var resp *billingpb.BillingAccount err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -348,24 +501,14 @@ func (c *CloudBillingClient) UpdateBillingAccount(ctx context.Context, req *bill return resp, nil } -// CreateBillingAccount creates a billing account. -// This method can only be used to create -// billing subaccounts (at https://cloud.google.com/billing/docs/concepts) -// by GCP resellers. -// When creating a subaccount, the current authenticated user must have the -// billing.accounts.update IAM permission on the master account, which is -// typically given to billing account -// administrators (at https://cloud.google.com/billing/docs/how-to/billing-access). -// This method will return an error if the master account has not been -// provisioned as a reseller account. -func (c *CloudBillingClient) CreateBillingAccount(ctx context.Context, req *billingpb.CreateBillingAccountRequest, opts ...gax.CallOption) (*billingpb.BillingAccount, error) { +func (c *cloudBillingGRPCClient) CreateBillingAccount(ctx context.Context, req *billingpb.CreateBillingAccountRequest, opts ...gax.CallOption) (*billingpb.BillingAccount, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.CreateBillingAccount[0:len(c.CallOptions.CreateBillingAccount):len(c.CallOptions.CreateBillingAccount)], opts...) + opts = append((*c.CallOptions).CreateBillingAccount[0:len((*c.CallOptions).CreateBillingAccount):len((*c.CallOptions).CreateBillingAccount)], opts...) var resp *billingpb.BillingAccount err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -378,14 +521,10 @@ func (c *CloudBillingClient) CreateBillingAccount(ctx context.Context, req *bill return resp, nil } -// ListProjectBillingInfo lists the projects associated with a billing account. The current -// authenticated user must have the billing.resourceAssociations.list IAM -// permission, which is often given to billing account -// viewers (at https://cloud.google.com/billing/docs/how-to/billing-access). -func (c *CloudBillingClient) ListProjectBillingInfo(ctx context.Context, req *billingpb.ListProjectBillingInfoRequest, opts ...gax.CallOption) *ProjectBillingInfoIterator { +func (c *cloudBillingGRPCClient) ListProjectBillingInfo(ctx context.Context, req *billingpb.ListProjectBillingInfoRequest, opts ...gax.CallOption) *ProjectBillingInfoIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListProjectBillingInfo[0:len(c.CallOptions.ListProjectBillingInfo):len(c.CallOptions.ListProjectBillingInfo)], opts...) + opts = append((*c.CallOptions).ListProjectBillingInfo[0:len((*c.CallOptions).ListProjectBillingInfo):len((*c.CallOptions).ListProjectBillingInfo)], opts...) it := &ProjectBillingInfoIterator{} req = proto.Clone(req).(*billingpb.ListProjectBillingInfoRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*billingpb.ProjectBillingInfo, string, error) { @@ -422,10 +561,7 @@ func (c *CloudBillingClient) ListProjectBillingInfo(ctx context.Context, req *bi return it } -// GetProjectBillingInfo gets the billing information for a project. The current authenticated user -// must have permission to view the -// project (at https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo). -func (c *CloudBillingClient) GetProjectBillingInfo(ctx context.Context, req *billingpb.GetProjectBillingInfoRequest, opts ...gax.CallOption) (*billingpb.ProjectBillingInfo, error) { +func (c *cloudBillingGRPCClient) GetProjectBillingInfo(ctx context.Context, req *billingpb.GetProjectBillingInfoRequest, opts ...gax.CallOption) (*billingpb.ProjectBillingInfo, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -433,7 +569,7 @@ func (c *CloudBillingClient) GetProjectBillingInfo(ctx context.Context, req *bil } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetProjectBillingInfo[0:len(c.CallOptions.GetProjectBillingInfo):len(c.CallOptions.GetProjectBillingInfo)], opts...) + opts = append((*c.CallOptions).GetProjectBillingInfo[0:len((*c.CallOptions).GetProjectBillingInfo):len((*c.CallOptions).GetProjectBillingInfo)], opts...) var resp *billingpb.ProjectBillingInfo err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -446,37 +582,7 @@ func (c *CloudBillingClient) GetProjectBillingInfo(ctx context.Context, req *bil return resp, nil } -// UpdateProjectBillingInfo sets or updates the billing account associated with a project. You specify -// the new billing account by setting the billing_account_name in the -// ProjectBillingInfo resource to the resource name of a billing account. -// Associating a project with an open billing account enables billing on the -// project and allows charges for resource usage. If the project already had a -// billing account, this method changes the billing account used for resource -// usage charges. -// -// Note: Incurred charges that have not yet been reported in the transaction -// history of the GCP Console might be billed to the new billing -// account, even if the charge occurred before the new billing account was -// assigned to the project. -// -// The current authenticated user must have ownership privileges for both the -// project (at https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo) and the billing -// account (at https://cloud.google.com/billing/docs/how-to/billing-access). -// -// You can disable billing on the project by setting the -// billing_account_name field to empty. This action disassociates the -// current billing account from the project. Any billable activity of your -// in-use services will stop, and your application could stop functioning as -// expected. Any unbilled charges to date will be billed to the previously -// associated account. The current authenticated user must be either an owner -// of the project or an owner of the billing account for the project. -// -// Note that associating a project with a closed billing account will have -// much the same effect as disabling billing on the project: any paid -// resources used by the project will be shut down. Thus, unless you wish to -// disable billing, you should always call this method with the name of an -// open billing account. -func (c *CloudBillingClient) UpdateProjectBillingInfo(ctx context.Context, req *billingpb.UpdateProjectBillingInfoRequest, opts ...gax.CallOption) (*billingpb.ProjectBillingInfo, error) { +func (c *cloudBillingGRPCClient) UpdateProjectBillingInfo(ctx context.Context, req *billingpb.UpdateProjectBillingInfoRequest, opts ...gax.CallOption) (*billingpb.ProjectBillingInfo, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -484,7 +590,7 @@ func (c *CloudBillingClient) UpdateProjectBillingInfo(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateProjectBillingInfo[0:len(c.CallOptions.UpdateProjectBillingInfo):len(c.CallOptions.UpdateProjectBillingInfo)], opts...) + opts = append((*c.CallOptions).UpdateProjectBillingInfo[0:len((*c.CallOptions).UpdateProjectBillingInfo):len((*c.CallOptions).UpdateProjectBillingInfo)], opts...) var resp *billingpb.ProjectBillingInfo err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -497,11 +603,7 @@ func (c *CloudBillingClient) UpdateProjectBillingInfo(ctx context.Context, req * return resp, nil } -// GetIamPolicy gets the access control policy for a billing account. -// The caller must have the billing.accounts.getIamPolicy permission on the -// account, which is often given to billing account -// viewers (at https://cloud.google.com/billing/docs/how-to/billing-access). -func (c *CloudBillingClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *cloudBillingGRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -509,7 +611,7 @@ func (c *CloudBillingClient) GetIamPolicy(ctx context.Context, req *iampb.GetIam } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -522,12 +624,7 @@ func (c *CloudBillingClient) GetIamPolicy(ctx context.Context, req *iampb.GetIam return resp, nil } -// SetIamPolicy sets the access control policy for a billing account. Replaces any existing -// policy. -// The caller must have the billing.accounts.setIamPolicy permission on the -// account, which is often given to billing account -// administrators (at https://cloud.google.com/billing/docs/how-to/billing-access). -func (c *CloudBillingClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *cloudBillingGRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -535,7 +632,7 @@ func (c *CloudBillingClient) SetIamPolicy(ctx context.Context, req *iampb.SetIam } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -548,10 +645,7 @@ func (c *CloudBillingClient) SetIamPolicy(ctx context.Context, req *iampb.SetIam return resp, nil } -// TestIamPermissions tests the access control policy for a billing account. This method takes -// the resource and a set of permissions as input and returns the subset of -// the input permissions that the caller is allowed for that resource. -func (c *CloudBillingClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *cloudBillingGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -559,7 +653,7 @@ func (c *CloudBillingClient) TestIamPermissions(ctx context.Context, req *iampb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/billing/apiv1/cloud_billing_client_example_test.go b/billing/apiv1/cloud_billing_client_example_test.go index 878a31a31990..755977674678 100644 --- a/billing/apiv1/cloud_billing_client_example_test.go +++ b/billing/apiv1/cloud_billing_client_example_test.go @@ -31,18 +31,19 @@ func ExampleNewCloudBillingClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCloudBillingClient_GetBillingAccount() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.GetBillingAccountRequest{ // TODO: Fill request struct fields. @@ -56,14 +57,12 @@ func ExampleCloudBillingClient_GetBillingAccount() { } func ExampleCloudBillingClient_ListBillingAccounts() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.ListBillingAccountsRequest{ // TODO: Fill request struct fields. @@ -83,13 +82,12 @@ func ExampleCloudBillingClient_ListBillingAccounts() { } func ExampleCloudBillingClient_UpdateBillingAccount() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.UpdateBillingAccountRequest{ // TODO: Fill request struct fields. @@ -103,13 +101,12 @@ func ExampleCloudBillingClient_UpdateBillingAccount() { } func ExampleCloudBillingClient_CreateBillingAccount() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.CreateBillingAccountRequest{ // TODO: Fill request struct fields. @@ -123,14 +120,12 @@ func ExampleCloudBillingClient_CreateBillingAccount() { } func ExampleCloudBillingClient_ListProjectBillingInfo() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.ListProjectBillingInfoRequest{ // TODO: Fill request struct fields. @@ -150,13 +145,12 @@ func ExampleCloudBillingClient_ListProjectBillingInfo() { } func ExampleCloudBillingClient_GetProjectBillingInfo() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.GetProjectBillingInfoRequest{ // TODO: Fill request struct fields. @@ -170,13 +164,12 @@ func ExampleCloudBillingClient_GetProjectBillingInfo() { } func ExampleCloudBillingClient_UpdateProjectBillingInfo() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.UpdateProjectBillingInfoRequest{ // TODO: Fill request struct fields. @@ -190,13 +183,12 @@ func ExampleCloudBillingClient_UpdateProjectBillingInfo() { } func ExampleCloudBillingClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -210,13 +202,12 @@ func ExampleCloudBillingClient_GetIamPolicy() { } func ExampleCloudBillingClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -230,13 +221,12 @@ func ExampleCloudBillingClient_SetIamPolicy() { } func ExampleCloudBillingClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/billing/apiv1/cloud_catalog_client.go b/billing/apiv1/cloud_catalog_client.go index 6e8e7828f95d..1a6b3a62dfbe 100644 --- a/billing/apiv1/cloud_catalog_client.go +++ b/billing/apiv1/cloud_catalog_client.go @@ -41,7 +41,7 @@ type CloudCatalogCallOptions struct { ListSkus []gax.CallOption } -func defaultCloudCatalogClientOptions() []option.ClientOption { +func defaultCloudCatalogGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudbilling.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudbilling.mtls.googleapis.com:443"), @@ -60,34 +60,89 @@ func defaultCloudCatalogCallOptions() *CloudCatalogCallOptions { } } +// internalCloudCatalogClient is an interface that defines the methods availaible from Cloud Billing API. +type internalCloudCatalogClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListServices(context.Context, *billingpb.ListServicesRequest, ...gax.CallOption) *ServiceIterator + ListSkus(context.Context, *billingpb.ListSkusRequest, ...gax.CallOption) *SkuIterator +} + // CloudCatalogClient is a client for interacting with Cloud Billing API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A catalog of Google Cloud Platform services and SKUs. +// Provides pricing information and metadata on Google Cloud Platform services +// and SKUs. type CloudCatalogClient struct { + // The internal transport-dependent client. + internalClient internalCloudCatalogClient + + // The call options for this service. + CallOptions *CloudCatalogCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CloudCatalogClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CloudCatalogClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CloudCatalogClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListServices lists all public cloud services. +func (c *CloudCatalogClient) ListServices(ctx context.Context, req *billingpb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { + return c.internalClient.ListServices(ctx, req, opts...) +} + +// ListSkus lists all publicly available SKUs for a given cloud service. +func (c *CloudCatalogClient) ListSkus(ctx context.Context, req *billingpb.ListSkusRequest, opts ...gax.CallOption) *SkuIterator { + return c.internalClient.ListSkus(ctx, req, opts...) +} + +// cloudCatalogGRPCClient is a client for interacting with Cloud Billing API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudCatalogGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CloudCatalogClient + CallOptions **CloudCatalogCallOptions + // The gRPC API client. cloudCatalogClient billingpb.CloudCatalogClient - // The call options for this service. - CallOptions *CloudCatalogCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCloudCatalogClient creates a new cloud catalog client. +// NewCloudCatalogClient creates a new cloud catalog client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A catalog of Google Cloud Platform services and SKUs. // Provides pricing information and metadata on Google Cloud Platform services // and SKUs. func NewCloudCatalogClient(ctx context.Context, opts ...option.ClientOption) (*CloudCatalogClient, error) { - clientOpts := defaultCloudCatalogClientOptions() - + clientOpts := defaultCloudCatalogGRPCClientOptions() if newCloudCatalogClientHook != nil { hookOpts, err := newCloudCatalogClientHook(ctx, clientHookParams{}) if err != nil { @@ -105,44 +160,46 @@ func NewCloudCatalogClient(ctx context.Context, opts ...option.ClientOption) (*C if err != nil { return nil, err } - c := &CloudCatalogClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultCloudCatalogCallOptions(), + client := CloudCatalogClient{CallOptions: defaultCloudCatalogCallOptions()} + c := &cloudCatalogGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, cloudCatalogClient: billingpb.NewCloudCatalogClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CloudCatalogClient) Connection() *grpc.ClientConn { +func (c *cloudCatalogGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CloudCatalogClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CloudCatalogClient) setGoogleClientInfo(keyval ...string) { +func (c *cloudCatalogGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListServices lists all public cloud services. -func (c *CloudCatalogClient) ListServices(ctx context.Context, req *billingpb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudCatalogGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *cloudCatalogGRPCClient) ListServices(ctx context.Context, req *billingpb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListServices[0:len(c.CallOptions.ListServices):len(c.CallOptions.ListServices)], opts...) + opts = append((*c.CallOptions).ListServices[0:len((*c.CallOptions).ListServices):len((*c.CallOptions).ListServices)], opts...) it := &ServiceIterator{} req = proto.Clone(req).(*billingpb.ListServicesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*billingpb.Service, string, error) { @@ -179,11 +236,10 @@ func (c *CloudCatalogClient) ListServices(ctx context.Context, req *billingpb.Li return it } -// ListSkus lists all publicly available SKUs for a given cloud service. -func (c *CloudCatalogClient) ListSkus(ctx context.Context, req *billingpb.ListSkusRequest, opts ...gax.CallOption) *SkuIterator { +func (c *cloudCatalogGRPCClient) ListSkus(ctx context.Context, req *billingpb.ListSkusRequest, opts ...gax.CallOption) *SkuIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSkus[0:len(c.CallOptions.ListSkus):len(c.CallOptions.ListSkus)], opts...) + opts = append((*c.CallOptions).ListSkus[0:len((*c.CallOptions).ListSkus):len((*c.CallOptions).ListSkus)], opts...) it := &SkuIterator{} req = proto.Clone(req).(*billingpb.ListSkusRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*billingpb.Sku, string, error) { diff --git a/billing/apiv1/cloud_catalog_client_example_test.go b/billing/apiv1/cloud_catalog_client_example_test.go index 7c1fe8738314..79c974acda92 100644 --- a/billing/apiv1/cloud_catalog_client_example_test.go +++ b/billing/apiv1/cloud_catalog_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewCloudCatalogClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCloudCatalogClient_ListServices() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := billing.NewCloudCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.ListServicesRequest{ // TODO: Fill request struct fields. @@ -62,14 +62,12 @@ func ExampleCloudCatalogClient_ListServices() { } func ExampleCloudCatalogClient_ListSkus() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := billing.NewCloudCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.ListSkusRequest{ // TODO: Fill request struct fields. diff --git a/billing/apiv1/doc.go b/billing/apiv1/doc.go index 43d012fc854c..e86de2535f11 100644 --- a/billing/apiv1/doc.go +++ b/billing/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package billing // import "cloud.google.com/go/billing/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/billing/budgets/apiv1/budget_client.go b/billing/budgets/apiv1/budget_client.go index 06602e5b9ef4..2e7899167ee0 100644 --- a/billing/budgets/apiv1/budget_client.go +++ b/billing/budgets/apiv1/budget_client.go @@ -46,7 +46,7 @@ type BudgetCallOptions struct { DeleteBudget []gax.CallOption } -func defaultBudgetClientOptions() []option.ClientOption { +func defaultBudgetGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("billingbudgets.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("billingbudgets.mtls.googleapis.com:443"), @@ -112,33 +112,121 @@ func defaultBudgetCallOptions() *BudgetCallOptions { } } +// internalBudgetClient is an interface that defines the methods availaible from Cloud Billing Budget API. +type internalBudgetClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateBudget(context.Context, *budgetspb.CreateBudgetRequest, ...gax.CallOption) (*budgetspb.Budget, error) + UpdateBudget(context.Context, *budgetspb.UpdateBudgetRequest, ...gax.CallOption) (*budgetspb.Budget, error) + GetBudget(context.Context, *budgetspb.GetBudgetRequest, ...gax.CallOption) (*budgetspb.Budget, error) + ListBudgets(context.Context, *budgetspb.ListBudgetsRequest, ...gax.CallOption) *BudgetIterator + DeleteBudget(context.Context, *budgetspb.DeleteBudgetRequest, ...gax.CallOption) error +} + // BudgetClient is a client for interacting with Cloud Billing Budget API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// BudgetService stores Cloud Billing budgets, which define a +// budget plan and rules to execute as we track spend against that plan. type BudgetClient struct { + // The internal transport-dependent client. + internalClient internalBudgetClient + + // The call options for this service. + CallOptions *BudgetCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *BudgetClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *BudgetClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *BudgetClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateBudget creates a new budget. See +// Quotas and limits (at https://cloud.google.com/billing/quotas) +// for more information on the limits of the number of budgets you can create. +func (c *BudgetClient) CreateBudget(ctx context.Context, req *budgetspb.CreateBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { + return c.internalClient.CreateBudget(ctx, req, opts...) +} + +// UpdateBudget updates a budget and returns the updated budget. +// +// WARNING: There are some fields exposed on the Google Cloud Console that +// aren’t available on this API. Budget fields that are not exposed in +// this API will not be changed by this method. +func (c *BudgetClient) UpdateBudget(ctx context.Context, req *budgetspb.UpdateBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { + return c.internalClient.UpdateBudget(ctx, req, opts...) +} + +// GetBudget returns a budget. +// +// WARNING: There are some fields exposed on the Google Cloud Console that +// aren’t available on this API. When reading from the API, you will not +// see these fields in the return value, though they may have been set +// in the Cloud Console. +func (c *BudgetClient) GetBudget(ctx context.Context, req *budgetspb.GetBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { + return c.internalClient.GetBudget(ctx, req, opts...) +} + +// ListBudgets returns a list of budgets for a billing account. +// +// WARNING: There are some fields exposed on the Google Cloud Console that +// aren’t available on this API. When reading from the API, you will not +// see these fields in the return value, though they may have been set +// in the Cloud Console. +func (c *BudgetClient) ListBudgets(ctx context.Context, req *budgetspb.ListBudgetsRequest, opts ...gax.CallOption) *BudgetIterator { + return c.internalClient.ListBudgets(ctx, req, opts...) +} + +// DeleteBudget deletes a budget. Returns successfully if already deleted. +func (c *BudgetClient) DeleteBudget(ctx context.Context, req *budgetspb.DeleteBudgetRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteBudget(ctx, req, opts...) +} + +// budgetGRPCClient is a client for interacting with Cloud Billing Budget API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type budgetGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing BudgetClient + CallOptions **BudgetCallOptions + // The gRPC API client. budgetClient budgetspb.BudgetServiceClient - // The call options for this service. - CallOptions *BudgetCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewBudgetClient creates a new budget service client. +// NewBudgetClient creates a new budget service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // BudgetService stores Cloud Billing budgets, which define a // budget plan and rules to execute as we track spend against that plan. func NewBudgetClient(ctx context.Context, opts ...option.ClientOption) (*BudgetClient, error) { - clientOpts := defaultBudgetClientOptions() - + clientOpts := defaultBudgetGRPCClientOptions() if newBudgetClientHook != nil { hookOpts, err := newBudgetClientHook(ctx, clientHookParams{}) if err != nil { @@ -156,44 +244,44 @@ func NewBudgetClient(ctx context.Context, opts ...option.ClientOption) (*BudgetC if err != nil { return nil, err } - c := &BudgetClient{ + client := BudgetClient{CallOptions: defaultBudgetCallOptions()} + + c := &budgetGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultBudgetCallOptions(), - - budgetClient: budgetspb.NewBudgetServiceClient(connPool), + budgetClient: budgetspb.NewBudgetServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *BudgetClient) Connection() *grpc.ClientConn { +func (c *budgetGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *BudgetClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *BudgetClient) setGoogleClientInfo(keyval ...string) { +func (c *budgetGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateBudget creates a new budget. See -// Quotas and limits (at https://cloud.google.com/billing/quotas) -// for more information on the limits of the number of budgets you can create. -func (c *BudgetClient) CreateBudget(ctx context.Context, req *budgetspb.CreateBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *budgetGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *budgetGRPCClient) CreateBudget(ctx context.Context, req *budgetspb.CreateBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -201,7 +289,7 @@ func (c *BudgetClient) CreateBudget(ctx context.Context, req *budgetspb.CreateBu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateBudget[0:len(c.CallOptions.CreateBudget):len(c.CallOptions.CreateBudget)], opts...) + opts = append((*c.CallOptions).CreateBudget[0:len((*c.CallOptions).CreateBudget):len((*c.CallOptions).CreateBudget)], opts...) var resp *budgetspb.Budget err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -214,12 +302,7 @@ func (c *BudgetClient) CreateBudget(ctx context.Context, req *budgetspb.CreateBu return resp, nil } -// UpdateBudget updates a budget and returns the updated budget. -// -// WARNING: There are some fields exposed on the Google Cloud Console that -// aren’t available on this API. Budget fields that are not exposed in -// this API will not be changed by this method. -func (c *BudgetClient) UpdateBudget(ctx context.Context, req *budgetspb.UpdateBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { +func (c *budgetGRPCClient) UpdateBudget(ctx context.Context, req *budgetspb.UpdateBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -227,7 +310,7 @@ func (c *BudgetClient) UpdateBudget(ctx context.Context, req *budgetspb.UpdateBu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "budget.name", url.QueryEscape(req.GetBudget().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateBudget[0:len(c.CallOptions.UpdateBudget):len(c.CallOptions.UpdateBudget)], opts...) + opts = append((*c.CallOptions).UpdateBudget[0:len((*c.CallOptions).UpdateBudget):len((*c.CallOptions).UpdateBudget)], opts...) var resp *budgetspb.Budget err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -240,13 +323,7 @@ func (c *BudgetClient) UpdateBudget(ctx context.Context, req *budgetspb.UpdateBu return resp, nil } -// GetBudget returns a budget. -// -// WARNING: There are some fields exposed on the Google Cloud Console that -// aren’t available on this API. When reading from the API, you will not -// see these fields in the return value, though they may have been set -// in the Cloud Console. -func (c *BudgetClient) GetBudget(ctx context.Context, req *budgetspb.GetBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { +func (c *budgetGRPCClient) GetBudget(ctx context.Context, req *budgetspb.GetBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -254,7 +331,7 @@ func (c *BudgetClient) GetBudget(ctx context.Context, req *budgetspb.GetBudgetRe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetBudget[0:len(c.CallOptions.GetBudget):len(c.CallOptions.GetBudget)], opts...) + opts = append((*c.CallOptions).GetBudget[0:len((*c.CallOptions).GetBudget):len((*c.CallOptions).GetBudget)], opts...) var resp *budgetspb.Budget err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -267,16 +344,10 @@ func (c *BudgetClient) GetBudget(ctx context.Context, req *budgetspb.GetBudgetRe return resp, nil } -// ListBudgets returns a list of budgets for a billing account. -// -// WARNING: There are some fields exposed on the Google Cloud Console that -// aren’t available on this API. When reading from the API, you will not -// see these fields in the return value, though they may have been set -// in the Cloud Console. -func (c *BudgetClient) ListBudgets(ctx context.Context, req *budgetspb.ListBudgetsRequest, opts ...gax.CallOption) *BudgetIterator { +func (c *budgetGRPCClient) ListBudgets(ctx context.Context, req *budgetspb.ListBudgetsRequest, opts ...gax.CallOption) *BudgetIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListBudgets[0:len(c.CallOptions.ListBudgets):len(c.CallOptions.ListBudgets)], opts...) + opts = append((*c.CallOptions).ListBudgets[0:len((*c.CallOptions).ListBudgets):len((*c.CallOptions).ListBudgets)], opts...) it := &BudgetIterator{} req = proto.Clone(req).(*budgetspb.ListBudgetsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*budgetspb.Budget, string, error) { @@ -313,8 +384,7 @@ func (c *BudgetClient) ListBudgets(ctx context.Context, req *budgetspb.ListBudge return it } -// DeleteBudget deletes a budget. Returns successfully if already deleted. -func (c *BudgetClient) DeleteBudget(ctx context.Context, req *budgetspb.DeleteBudgetRequest, opts ...gax.CallOption) error { +func (c *budgetGRPCClient) DeleteBudget(ctx context.Context, req *budgetspb.DeleteBudgetRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -322,7 +392,7 @@ func (c *BudgetClient) DeleteBudget(ctx context.Context, req *budgetspb.DeleteBu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteBudget[0:len(c.CallOptions.DeleteBudget):len(c.CallOptions.DeleteBudget)], opts...) + opts = append((*c.CallOptions).DeleteBudget[0:len((*c.CallOptions).DeleteBudget):len((*c.CallOptions).DeleteBudget)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.budgetClient.DeleteBudget(ctx, req, settings.GRPC...) diff --git a/billing/budgets/apiv1/budget_client_example_test.go b/billing/budgets/apiv1/budget_client_example_test.go index b0c8a903c7e0..e121663d9072 100644 --- a/billing/budgets/apiv1/budget_client_example_test.go +++ b/billing/budgets/apiv1/budget_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewBudgetClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleBudgetClient_CreateBudget() { - // import budgetspb "google.golang.org/genproto/googleapis/cloud/billing/budgets/v1" - ctx := context.Background() c, err := budgets.NewBudgetClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.CreateBudgetRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleBudgetClient_CreateBudget() { } func ExampleBudgetClient_UpdateBudget() { - // import budgetspb "google.golang.org/genproto/googleapis/cloud/billing/budgets/v1" - ctx := context.Background() c, err := budgets.NewBudgetClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.UpdateBudgetRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleBudgetClient_UpdateBudget() { } func ExampleBudgetClient_GetBudget() { - // import budgetspb "google.golang.org/genproto/googleapis/cloud/billing/budgets/v1" - ctx := context.Background() c, err := budgets.NewBudgetClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.GetBudgetRequest{ // TODO: Fill request struct fields. @@ -95,14 +94,12 @@ func ExampleBudgetClient_GetBudget() { } func ExampleBudgetClient_ListBudgets() { - // import budgetspb "google.golang.org/genproto/googleapis/cloud/billing/budgets/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := budgets.NewBudgetClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.ListBudgetsRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleBudgetClient_DeleteBudget() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.DeleteBudgetRequest{ // TODO: Fill request struct fields. diff --git a/billing/budgets/apiv1/doc.go b/billing/budgets/apiv1/doc.go index 6858f47ba8f6..2137b7395a21 100644 --- a/billing/budgets/apiv1/doc.go +++ b/billing/budgets/apiv1/doc.go @@ -30,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package budgets // import "cloud.google.com/go/billing/budgets/apiv1" import ( @@ -50,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/billing/budgets/apiv1beta1/budget_client.go b/billing/budgets/apiv1beta1/budget_client.go index 17e01134d2c2..3583d60e3b69 100644 --- a/billing/budgets/apiv1beta1/budget_client.go +++ b/billing/budgets/apiv1beta1/budget_client.go @@ -46,7 +46,7 @@ type BudgetCallOptions struct { DeleteBudget []gax.CallOption } -func defaultBudgetClientOptions() []option.ClientOption { +func defaultBudgetGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("billingbudgets.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("billingbudgets.mtls.googleapis.com:443"), @@ -112,33 +112,121 @@ func defaultBudgetCallOptions() *BudgetCallOptions { } } +// internalBudgetClient is an interface that defines the methods availaible from Cloud Billing Budget API. +type internalBudgetClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateBudget(context.Context, *budgetspb.CreateBudgetRequest, ...gax.CallOption) (*budgetspb.Budget, error) + UpdateBudget(context.Context, *budgetspb.UpdateBudgetRequest, ...gax.CallOption) (*budgetspb.Budget, error) + GetBudget(context.Context, *budgetspb.GetBudgetRequest, ...gax.CallOption) (*budgetspb.Budget, error) + ListBudgets(context.Context, *budgetspb.ListBudgetsRequest, ...gax.CallOption) *BudgetIterator + DeleteBudget(context.Context, *budgetspb.DeleteBudgetRequest, ...gax.CallOption) error +} + // BudgetClient is a client for interacting with Cloud Billing Budget API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// BudgetService stores Cloud Billing budgets, which define a +// budget plan and rules to execute as we track spend against that plan. type BudgetClient struct { + // The internal transport-dependent client. + internalClient internalBudgetClient + + // The call options for this service. + CallOptions *BudgetCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *BudgetClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *BudgetClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *BudgetClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateBudget creates a new budget. See +// Quotas and limits (at https://cloud.google.com/billing/quotas) +// for more information on the limits of the number of budgets you can create. +func (c *BudgetClient) CreateBudget(ctx context.Context, req *budgetspb.CreateBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { + return c.internalClient.CreateBudget(ctx, req, opts...) +} + +// UpdateBudget updates a budget and returns the updated budget. +// +// WARNING: There are some fields exposed on the Google Cloud Console that +// aren’t available on this API. Budget fields that are not exposed in +// this API will not be changed by this method. +func (c *BudgetClient) UpdateBudget(ctx context.Context, req *budgetspb.UpdateBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { + return c.internalClient.UpdateBudget(ctx, req, opts...) +} + +// GetBudget returns a budget. +// +// WARNING: There are some fields exposed on the Google Cloud Console that +// aren’t available on this API. When reading from the API, you will not +// see these fields in the return value, though they may have been set +// in the Cloud Console. +func (c *BudgetClient) GetBudget(ctx context.Context, req *budgetspb.GetBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { + return c.internalClient.GetBudget(ctx, req, opts...) +} + +// ListBudgets returns a list of budgets for a billing account. +// +// WARNING: There are some fields exposed on the Google Cloud Console that +// aren’t available on this API. When reading from the API, you will not +// see these fields in the return value, though they may have been set +// in the Cloud Console. +func (c *BudgetClient) ListBudgets(ctx context.Context, req *budgetspb.ListBudgetsRequest, opts ...gax.CallOption) *BudgetIterator { + return c.internalClient.ListBudgets(ctx, req, opts...) +} + +// DeleteBudget deletes a budget. Returns successfully if already deleted. +func (c *BudgetClient) DeleteBudget(ctx context.Context, req *budgetspb.DeleteBudgetRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteBudget(ctx, req, opts...) +} + +// budgetGRPCClient is a client for interacting with Cloud Billing Budget API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type budgetGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing BudgetClient + CallOptions **BudgetCallOptions + // The gRPC API client. budgetClient budgetspb.BudgetServiceClient - // The call options for this service. - CallOptions *BudgetCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewBudgetClient creates a new budget service client. +// NewBudgetClient creates a new budget service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // BudgetService stores Cloud Billing budgets, which define a // budget plan and rules to execute as we track spend against that plan. func NewBudgetClient(ctx context.Context, opts ...option.ClientOption) (*BudgetClient, error) { - clientOpts := defaultBudgetClientOptions() - + clientOpts := defaultBudgetGRPCClientOptions() if newBudgetClientHook != nil { hookOpts, err := newBudgetClientHook(ctx, clientHookParams{}) if err != nil { @@ -156,44 +244,44 @@ func NewBudgetClient(ctx context.Context, opts ...option.ClientOption) (*BudgetC if err != nil { return nil, err } - c := &BudgetClient{ + client := BudgetClient{CallOptions: defaultBudgetCallOptions()} + + c := &budgetGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultBudgetCallOptions(), - - budgetClient: budgetspb.NewBudgetServiceClient(connPool), + budgetClient: budgetspb.NewBudgetServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *BudgetClient) Connection() *grpc.ClientConn { +func (c *budgetGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *BudgetClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *BudgetClient) setGoogleClientInfo(keyval ...string) { +func (c *budgetGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateBudget creates a new budget. See -// Quotas and limits (at https://cloud.google.com/billing/quotas) -// for more information on the limits of the number of budgets you can create. -func (c *BudgetClient) CreateBudget(ctx context.Context, req *budgetspb.CreateBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *budgetGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *budgetGRPCClient) CreateBudget(ctx context.Context, req *budgetspb.CreateBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -201,7 +289,7 @@ func (c *BudgetClient) CreateBudget(ctx context.Context, req *budgetspb.CreateBu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateBudget[0:len(c.CallOptions.CreateBudget):len(c.CallOptions.CreateBudget)], opts...) + opts = append((*c.CallOptions).CreateBudget[0:len((*c.CallOptions).CreateBudget):len((*c.CallOptions).CreateBudget)], opts...) var resp *budgetspb.Budget err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -214,12 +302,7 @@ func (c *BudgetClient) CreateBudget(ctx context.Context, req *budgetspb.CreateBu return resp, nil } -// UpdateBudget updates a budget and returns the updated budget. -// -// WARNING: There are some fields exposed on the Google Cloud Console that -// aren’t available on this API. Budget fields that are not exposed in -// this API will not be changed by this method. -func (c *BudgetClient) UpdateBudget(ctx context.Context, req *budgetspb.UpdateBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { +func (c *budgetGRPCClient) UpdateBudget(ctx context.Context, req *budgetspb.UpdateBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -227,7 +310,7 @@ func (c *BudgetClient) UpdateBudget(ctx context.Context, req *budgetspb.UpdateBu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "budget.name", url.QueryEscape(req.GetBudget().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateBudget[0:len(c.CallOptions.UpdateBudget):len(c.CallOptions.UpdateBudget)], opts...) + opts = append((*c.CallOptions).UpdateBudget[0:len((*c.CallOptions).UpdateBudget):len((*c.CallOptions).UpdateBudget)], opts...) var resp *budgetspb.Budget err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -240,13 +323,7 @@ func (c *BudgetClient) UpdateBudget(ctx context.Context, req *budgetspb.UpdateBu return resp, nil } -// GetBudget returns a budget. -// -// WARNING: There are some fields exposed on the Google Cloud Console that -// aren’t available on this API. When reading from the API, you will not -// see these fields in the return value, though they may have been set -// in the Cloud Console. -func (c *BudgetClient) GetBudget(ctx context.Context, req *budgetspb.GetBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { +func (c *budgetGRPCClient) GetBudget(ctx context.Context, req *budgetspb.GetBudgetRequest, opts ...gax.CallOption) (*budgetspb.Budget, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -254,7 +331,7 @@ func (c *BudgetClient) GetBudget(ctx context.Context, req *budgetspb.GetBudgetRe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetBudget[0:len(c.CallOptions.GetBudget):len(c.CallOptions.GetBudget)], opts...) + opts = append((*c.CallOptions).GetBudget[0:len((*c.CallOptions).GetBudget):len((*c.CallOptions).GetBudget)], opts...) var resp *budgetspb.Budget err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -267,16 +344,10 @@ func (c *BudgetClient) GetBudget(ctx context.Context, req *budgetspb.GetBudgetRe return resp, nil } -// ListBudgets returns a list of budgets for a billing account. -// -// WARNING: There are some fields exposed on the Google Cloud Console that -// aren’t available on this API. When reading from the API, you will not -// see these fields in the return value, though they may have been set -// in the Cloud Console. -func (c *BudgetClient) ListBudgets(ctx context.Context, req *budgetspb.ListBudgetsRequest, opts ...gax.CallOption) *BudgetIterator { +func (c *budgetGRPCClient) ListBudgets(ctx context.Context, req *budgetspb.ListBudgetsRequest, opts ...gax.CallOption) *BudgetIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListBudgets[0:len(c.CallOptions.ListBudgets):len(c.CallOptions.ListBudgets)], opts...) + opts = append((*c.CallOptions).ListBudgets[0:len((*c.CallOptions).ListBudgets):len((*c.CallOptions).ListBudgets)], opts...) it := &BudgetIterator{} req = proto.Clone(req).(*budgetspb.ListBudgetsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*budgetspb.Budget, string, error) { @@ -313,8 +384,7 @@ func (c *BudgetClient) ListBudgets(ctx context.Context, req *budgetspb.ListBudge return it } -// DeleteBudget deletes a budget. Returns successfully if already deleted. -func (c *BudgetClient) DeleteBudget(ctx context.Context, req *budgetspb.DeleteBudgetRequest, opts ...gax.CallOption) error { +func (c *budgetGRPCClient) DeleteBudget(ctx context.Context, req *budgetspb.DeleteBudgetRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -322,7 +392,7 @@ func (c *BudgetClient) DeleteBudget(ctx context.Context, req *budgetspb.DeleteBu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteBudget[0:len(c.CallOptions.DeleteBudget):len(c.CallOptions.DeleteBudget)], opts...) + opts = append((*c.CallOptions).DeleteBudget[0:len((*c.CallOptions).DeleteBudget):len((*c.CallOptions).DeleteBudget)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.budgetClient.DeleteBudget(ctx, req, settings.GRPC...) diff --git a/billing/budgets/apiv1beta1/budget_client_example_test.go b/billing/budgets/apiv1beta1/budget_client_example_test.go index cefb2b55b4fc..53d3f68cab5d 100644 --- a/billing/budgets/apiv1beta1/budget_client_example_test.go +++ b/billing/budgets/apiv1beta1/budget_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewBudgetClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleBudgetClient_CreateBudget() { - // import budgetspb "google.golang.org/genproto/googleapis/cloud/billing/budgets/v1beta1" - ctx := context.Background() c, err := budgets.NewBudgetClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.CreateBudgetRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleBudgetClient_CreateBudget() { } func ExampleBudgetClient_UpdateBudget() { - // import budgetspb "google.golang.org/genproto/googleapis/cloud/billing/budgets/v1beta1" - ctx := context.Background() c, err := budgets.NewBudgetClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.UpdateBudgetRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleBudgetClient_UpdateBudget() { } func ExampleBudgetClient_GetBudget() { - // import budgetspb "google.golang.org/genproto/googleapis/cloud/billing/budgets/v1beta1" - ctx := context.Background() c, err := budgets.NewBudgetClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.GetBudgetRequest{ // TODO: Fill request struct fields. @@ -95,14 +94,12 @@ func ExampleBudgetClient_GetBudget() { } func ExampleBudgetClient_ListBudgets() { - // import budgetspb "google.golang.org/genproto/googleapis/cloud/billing/budgets/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := budgets.NewBudgetClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.ListBudgetsRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleBudgetClient_DeleteBudget() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.DeleteBudgetRequest{ // TODO: Fill request struct fields. diff --git a/billing/budgets/apiv1beta1/doc.go b/billing/budgets/apiv1beta1/doc.go index 817daef87a1d..606c78055f84 100644 --- a/billing/budgets/apiv1beta1/doc.go +++ b/billing/budgets/apiv1beta1/doc.go @@ -21,6 +21,8 @@ // budget plan and the rules to execute as spend is tracked against that // plan. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -30,7 +32,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package budgets // import "cloud.google.com/go/billing/budgets/apiv1beta1" import ( @@ -50,7 +52,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/binaryauthorization/apiv1beta1/binauthz_management_service_v1_beta1_client.go b/binaryauthorization/apiv1beta1/binauthz_management_service_v1_beta1_client.go index 664156e31efc..8e24b481705a 100644 --- a/binaryauthorization/apiv1beta1/binauthz_management_service_v1_beta1_client.go +++ b/binaryauthorization/apiv1beta1/binauthz_management_service_v1_beta1_client.go @@ -48,7 +48,7 @@ type BinauthzManagementServiceV1Beta1CallOptions struct { DeleteAttestor []gax.CallOption } -func defaultBinauthzManagementServiceV1Beta1ClientOptions() []option.ClientOption { +func defaultBinauthzManagementServiceV1Beta1GRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("binaryauthorization.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("binaryauthorization.mtls.googleapis.com:443"), @@ -138,27 +138,149 @@ func defaultBinauthzManagementServiceV1Beta1CallOptions() *BinauthzManagementSer } } +// internalBinauthzManagementServiceV1Beta1Client is an interface that defines the methods availaible from Binary Authorization API. +type internalBinauthzManagementServiceV1Beta1Client interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + GetPolicy(context.Context, *binaryauthorizationpb.GetPolicyRequest, ...gax.CallOption) (*binaryauthorizationpb.Policy, error) + UpdatePolicy(context.Context, *binaryauthorizationpb.UpdatePolicyRequest, ...gax.CallOption) (*binaryauthorizationpb.Policy, error) + CreateAttestor(context.Context, *binaryauthorizationpb.CreateAttestorRequest, ...gax.CallOption) (*binaryauthorizationpb.Attestor, error) + GetAttestor(context.Context, *binaryauthorizationpb.GetAttestorRequest, ...gax.CallOption) (*binaryauthorizationpb.Attestor, error) + UpdateAttestor(context.Context, *binaryauthorizationpb.UpdateAttestorRequest, ...gax.CallOption) (*binaryauthorizationpb.Attestor, error) + ListAttestors(context.Context, *binaryauthorizationpb.ListAttestorsRequest, ...gax.CallOption) *AttestorIterator + DeleteAttestor(context.Context, *binaryauthorizationpb.DeleteAttestorRequest, ...gax.CallOption) error +} + // BinauthzManagementServiceV1Beta1Client is a client for interacting with Binary Authorization API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Google Cloud Management Service for Binary Authorization admission policies +// and attestation authorities. +// +// This API implements a REST model with the following objects: +// +// Policy +// +// Attestor type BinauthzManagementServiceV1Beta1Client struct { + // The internal transport-dependent client. + internalClient internalBinauthzManagementServiceV1Beta1Client + + // The call options for this service. + CallOptions *BinauthzManagementServiceV1Beta1CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *BinauthzManagementServiceV1Beta1Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *BinauthzManagementServiceV1Beta1Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *BinauthzManagementServiceV1Beta1Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// GetPolicy a policy specifies the +// attestors that must +// attest to a container image, before the project is allowed to deploy that +// image. There is at most one policy per project. All image admission +// requests are permitted if a project has no policy. +// +// Gets the policy for this +// project. Returns a default +// policy if the project +// does not have one. +func (c *BinauthzManagementServiceV1Beta1Client) GetPolicy(ctx context.Context, req *binaryauthorizationpb.GetPolicyRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Policy, error) { + return c.internalClient.GetPolicy(ctx, req, opts...) +} + +// UpdatePolicy creates or updates a project’s +// policy, and returns a +// copy of the new policy. +// A policy is always updated as a whole, to avoid race conditions with +// concurrent policy enforcement (or management!) requests. Returns NOT_FOUND +// if the project does not exist, INVALID_ARGUMENT if the request is +// malformed. +func (c *BinauthzManagementServiceV1Beta1Client) UpdatePolicy(ctx context.Context, req *binaryauthorizationpb.UpdatePolicyRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Policy, error) { + return c.internalClient.UpdatePolicy(ctx, req, opts...) +} + +// CreateAttestor creates an attestor, +// and returns a copy of the new +// attestor. Returns +// NOT_FOUND if the project does not exist, INVALID_ARGUMENT if the request is +// malformed, ALREADY_EXISTS if the +// attestor already +// exists. +func (c *BinauthzManagementServiceV1Beta1Client) CreateAttestor(ctx context.Context, req *binaryauthorizationpb.CreateAttestorRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Attestor, error) { + return c.internalClient.CreateAttestor(ctx, req, opts...) +} + +// GetAttestor gets an attestor. +// Returns NOT_FOUND if the +// attestor does not +// exist. +func (c *BinauthzManagementServiceV1Beta1Client) GetAttestor(ctx context.Context, req *binaryauthorizationpb.GetAttestorRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Attestor, error) { + return c.internalClient.GetAttestor(ctx, req, opts...) +} + +// UpdateAttestor updates an attestor. +// Returns NOT_FOUND if the +// attestor does not +// exist. +func (c *BinauthzManagementServiceV1Beta1Client) UpdateAttestor(ctx context.Context, req *binaryauthorizationpb.UpdateAttestorRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Attestor, error) { + return c.internalClient.UpdateAttestor(ctx, req, opts...) +} + +// ListAttestors lists attestors. +// Returns INVALID_ARGUMENT if the project does not exist. +func (c *BinauthzManagementServiceV1Beta1Client) ListAttestors(ctx context.Context, req *binaryauthorizationpb.ListAttestorsRequest, opts ...gax.CallOption) *AttestorIterator { + return c.internalClient.ListAttestors(ctx, req, opts...) +} + +// DeleteAttestor deletes an attestor. +// Returns NOT_FOUND if the +// attestor does not +// exist. +func (c *BinauthzManagementServiceV1Beta1Client) DeleteAttestor(ctx context.Context, req *binaryauthorizationpb.DeleteAttestorRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteAttestor(ctx, req, opts...) +} + +// binauthzManagementServiceV1Beta1GRPCClient is a client for interacting with Binary Authorization API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type binauthzManagementServiceV1Beta1GRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing BinauthzManagementServiceV1Beta1Client + CallOptions **BinauthzManagementServiceV1Beta1CallOptions + // The gRPC API client. binauthzManagementServiceV1Beta1Client binaryauthorizationpb.BinauthzManagementServiceV1Beta1Client - // The call options for this service. - CallOptions *BinauthzManagementServiceV1Beta1CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewBinauthzManagementServiceV1Beta1Client creates a new binauthz management service v1 beta1 client. +// NewBinauthzManagementServiceV1Beta1Client creates a new binauthz management service v1 beta1 client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Google Cloud Management Service for Binary Authorization admission policies // and attestation authorities. @@ -169,8 +291,7 @@ type BinauthzManagementServiceV1Beta1Client struct { // // Attestor func NewBinauthzManagementServiceV1Beta1Client(ctx context.Context, opts ...option.ClientOption) (*BinauthzManagementServiceV1Beta1Client, error) { - clientOpts := defaultBinauthzManagementServiceV1Beta1ClientOptions() - + clientOpts := defaultBinauthzManagementServiceV1Beta1GRPCClientOptions() if newBinauthzManagementServiceV1Beta1ClientHook != nil { hookOpts, err := newBinauthzManagementServiceV1Beta1ClientHook(ctx, clientHookParams{}) if err != nil { @@ -188,51 +309,44 @@ func NewBinauthzManagementServiceV1Beta1Client(ctx context.Context, opts ...opti if err != nil { return nil, err } - c := &BinauthzManagementServiceV1Beta1Client{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultBinauthzManagementServiceV1Beta1CallOptions(), + client := BinauthzManagementServiceV1Beta1Client{CallOptions: defaultBinauthzManagementServiceV1Beta1CallOptions()} + c := &binauthzManagementServiceV1Beta1GRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, binauthzManagementServiceV1Beta1Client: binaryauthorizationpb.NewBinauthzManagementServiceV1Beta1Client(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *BinauthzManagementServiceV1Beta1Client) Connection() *grpc.ClientConn { +func (c *binauthzManagementServiceV1Beta1GRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *BinauthzManagementServiceV1Beta1Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *BinauthzManagementServiceV1Beta1Client) setGoogleClientInfo(keyval ...string) { +func (c *binauthzManagementServiceV1Beta1GRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// GetPolicy a policy specifies the -// attestors that must -// attest to a container image, before the project is allowed to deploy that -// image. There is at most one policy per project. All image admission -// requests are permitted if a project has no policy. -// -// Gets the policy for this -// project. Returns a default -// policy if the project -// does not have one. -func (c *BinauthzManagementServiceV1Beta1Client) GetPolicy(ctx context.Context, req *binaryauthorizationpb.GetPolicyRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Policy, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *binauthzManagementServiceV1Beta1GRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *binauthzManagementServiceV1Beta1GRPCClient) GetPolicy(ctx context.Context, req *binaryauthorizationpb.GetPolicyRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -240,7 +354,7 @@ func (c *BinauthzManagementServiceV1Beta1Client) GetPolicy(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetPolicy[0:len(c.CallOptions.GetPolicy):len(c.CallOptions.GetPolicy)], opts...) + opts = append((*c.CallOptions).GetPolicy[0:len((*c.CallOptions).GetPolicy):len((*c.CallOptions).GetPolicy)], opts...) var resp *binaryauthorizationpb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -253,14 +367,7 @@ func (c *BinauthzManagementServiceV1Beta1Client) GetPolicy(ctx context.Context, return resp, nil } -// UpdatePolicy creates or updates a project’s -// policy, and returns a -// copy of the new policy. -// A policy is always updated as a whole, to avoid race conditions with -// concurrent policy enforcement (or management!) requests. Returns NOT_FOUND -// if the project does not exist, INVALID_ARGUMENT if the request is -// malformed. -func (c *BinauthzManagementServiceV1Beta1Client) UpdatePolicy(ctx context.Context, req *binaryauthorizationpb.UpdatePolicyRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Policy, error) { +func (c *binauthzManagementServiceV1Beta1GRPCClient) UpdatePolicy(ctx context.Context, req *binaryauthorizationpb.UpdatePolicyRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -268,7 +375,7 @@ func (c *BinauthzManagementServiceV1Beta1Client) UpdatePolicy(ctx context.Contex } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "policy.name", url.QueryEscape(req.GetPolicy().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdatePolicy[0:len(c.CallOptions.UpdatePolicy):len(c.CallOptions.UpdatePolicy)], opts...) + opts = append((*c.CallOptions).UpdatePolicy[0:len((*c.CallOptions).UpdatePolicy):len((*c.CallOptions).UpdatePolicy)], opts...) var resp *binaryauthorizationpb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -281,14 +388,7 @@ func (c *BinauthzManagementServiceV1Beta1Client) UpdatePolicy(ctx context.Contex return resp, nil } -// CreateAttestor creates an attestor, -// and returns a copy of the new -// attestor. Returns -// NOT_FOUND if the project does not exist, INVALID_ARGUMENT if the request is -// malformed, ALREADY_EXISTS if the -// attestor already -// exists. -func (c *BinauthzManagementServiceV1Beta1Client) CreateAttestor(ctx context.Context, req *binaryauthorizationpb.CreateAttestorRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Attestor, error) { +func (c *binauthzManagementServiceV1Beta1GRPCClient) CreateAttestor(ctx context.Context, req *binaryauthorizationpb.CreateAttestorRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Attestor, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -296,7 +396,7 @@ func (c *BinauthzManagementServiceV1Beta1Client) CreateAttestor(ctx context.Cont } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateAttestor[0:len(c.CallOptions.CreateAttestor):len(c.CallOptions.CreateAttestor)], opts...) + opts = append((*c.CallOptions).CreateAttestor[0:len((*c.CallOptions).CreateAttestor):len((*c.CallOptions).CreateAttestor)], opts...) var resp *binaryauthorizationpb.Attestor err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -309,11 +409,7 @@ func (c *BinauthzManagementServiceV1Beta1Client) CreateAttestor(ctx context.Cont return resp, nil } -// GetAttestor gets an attestor. -// Returns NOT_FOUND if the -// attestor does not -// exist. -func (c *BinauthzManagementServiceV1Beta1Client) GetAttestor(ctx context.Context, req *binaryauthorizationpb.GetAttestorRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Attestor, error) { +func (c *binauthzManagementServiceV1Beta1GRPCClient) GetAttestor(ctx context.Context, req *binaryauthorizationpb.GetAttestorRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Attestor, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -321,7 +417,7 @@ func (c *BinauthzManagementServiceV1Beta1Client) GetAttestor(ctx context.Context } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetAttestor[0:len(c.CallOptions.GetAttestor):len(c.CallOptions.GetAttestor)], opts...) + opts = append((*c.CallOptions).GetAttestor[0:len((*c.CallOptions).GetAttestor):len((*c.CallOptions).GetAttestor)], opts...) var resp *binaryauthorizationpb.Attestor err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -334,11 +430,7 @@ func (c *BinauthzManagementServiceV1Beta1Client) GetAttestor(ctx context.Context return resp, nil } -// UpdateAttestor updates an attestor. -// Returns NOT_FOUND if the -// attestor does not -// exist. -func (c *BinauthzManagementServiceV1Beta1Client) UpdateAttestor(ctx context.Context, req *binaryauthorizationpb.UpdateAttestorRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Attestor, error) { +func (c *binauthzManagementServiceV1Beta1GRPCClient) UpdateAttestor(ctx context.Context, req *binaryauthorizationpb.UpdateAttestorRequest, opts ...gax.CallOption) (*binaryauthorizationpb.Attestor, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -346,7 +438,7 @@ func (c *BinauthzManagementServiceV1Beta1Client) UpdateAttestor(ctx context.Cont } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "attestor.name", url.QueryEscape(req.GetAttestor().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateAttestor[0:len(c.CallOptions.UpdateAttestor):len(c.CallOptions.UpdateAttestor)], opts...) + opts = append((*c.CallOptions).UpdateAttestor[0:len((*c.CallOptions).UpdateAttestor):len((*c.CallOptions).UpdateAttestor)], opts...) var resp *binaryauthorizationpb.Attestor err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -359,12 +451,10 @@ func (c *BinauthzManagementServiceV1Beta1Client) UpdateAttestor(ctx context.Cont return resp, nil } -// ListAttestors lists attestors. -// Returns INVALID_ARGUMENT if the project does not exist. -func (c *BinauthzManagementServiceV1Beta1Client) ListAttestors(ctx context.Context, req *binaryauthorizationpb.ListAttestorsRequest, opts ...gax.CallOption) *AttestorIterator { +func (c *binauthzManagementServiceV1Beta1GRPCClient) ListAttestors(ctx context.Context, req *binaryauthorizationpb.ListAttestorsRequest, opts ...gax.CallOption) *AttestorIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAttestors[0:len(c.CallOptions.ListAttestors):len(c.CallOptions.ListAttestors)], opts...) + opts = append((*c.CallOptions).ListAttestors[0:len((*c.CallOptions).ListAttestors):len((*c.CallOptions).ListAttestors)], opts...) it := &AttestorIterator{} req = proto.Clone(req).(*binaryauthorizationpb.ListAttestorsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*binaryauthorizationpb.Attestor, string, error) { @@ -401,11 +491,7 @@ func (c *BinauthzManagementServiceV1Beta1Client) ListAttestors(ctx context.Conte return it } -// DeleteAttestor deletes an attestor. -// Returns NOT_FOUND if the -// attestor does not -// exist. -func (c *BinauthzManagementServiceV1Beta1Client) DeleteAttestor(ctx context.Context, req *binaryauthorizationpb.DeleteAttestorRequest, opts ...gax.CallOption) error { +func (c *binauthzManagementServiceV1Beta1GRPCClient) DeleteAttestor(ctx context.Context, req *binaryauthorizationpb.DeleteAttestorRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -413,7 +499,7 @@ func (c *BinauthzManagementServiceV1Beta1Client) DeleteAttestor(ctx context.Cont } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteAttestor[0:len(c.CallOptions.DeleteAttestor):len(c.CallOptions.DeleteAttestor)], opts...) + opts = append((*c.CallOptions).DeleteAttestor[0:len((*c.CallOptions).DeleteAttestor):len((*c.CallOptions).DeleteAttestor)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.binauthzManagementServiceV1Beta1Client.DeleteAttestor(ctx, req, settings.GRPC...) diff --git a/binaryauthorization/apiv1beta1/binauthz_management_service_v1_beta1_client_example_test.go b/binaryauthorization/apiv1beta1/binauthz_management_service_v1_beta1_client_example_test.go index a691917b4a9a..1c33a69324b6 100644 --- a/binaryauthorization/apiv1beta1/binauthz_management_service_v1_beta1_client_example_test.go +++ b/binaryauthorization/apiv1beta1/binauthz_management_service_v1_beta1_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewBinauthzManagementServiceV1Beta1Client() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleBinauthzManagementServiceV1Beta1Client_GetPolicy() { - // import binaryauthorizationpb "google.golang.org/genproto/googleapis/cloud/binaryauthorization/v1beta1" - ctx := context.Background() c, err := binaryauthorization.NewBinauthzManagementServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &binaryauthorizationpb.GetPolicyRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleBinauthzManagementServiceV1Beta1Client_GetPolicy() { } func ExampleBinauthzManagementServiceV1Beta1Client_UpdatePolicy() { - // import binaryauthorizationpb "google.golang.org/genproto/googleapis/cloud/binaryauthorization/v1beta1" - ctx := context.Background() c, err := binaryauthorization.NewBinauthzManagementServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &binaryauthorizationpb.UpdatePolicyRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleBinauthzManagementServiceV1Beta1Client_UpdatePolicy() { } func ExampleBinauthzManagementServiceV1Beta1Client_CreateAttestor() { - // import binaryauthorizationpb "google.golang.org/genproto/googleapis/cloud/binaryauthorization/v1beta1" - ctx := context.Background() c, err := binaryauthorization.NewBinauthzManagementServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &binaryauthorizationpb.CreateAttestorRequest{ // TODO: Fill request struct fields. @@ -95,13 +94,12 @@ func ExampleBinauthzManagementServiceV1Beta1Client_CreateAttestor() { } func ExampleBinauthzManagementServiceV1Beta1Client_GetAttestor() { - // import binaryauthorizationpb "google.golang.org/genproto/googleapis/cloud/binaryauthorization/v1beta1" - ctx := context.Background() c, err := binaryauthorization.NewBinauthzManagementServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &binaryauthorizationpb.GetAttestorRequest{ // TODO: Fill request struct fields. @@ -115,13 +113,12 @@ func ExampleBinauthzManagementServiceV1Beta1Client_GetAttestor() { } func ExampleBinauthzManagementServiceV1Beta1Client_UpdateAttestor() { - // import binaryauthorizationpb "google.golang.org/genproto/googleapis/cloud/binaryauthorization/v1beta1" - ctx := context.Background() c, err := binaryauthorization.NewBinauthzManagementServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &binaryauthorizationpb.UpdateAttestorRequest{ // TODO: Fill request struct fields. @@ -135,14 +132,12 @@ func ExampleBinauthzManagementServiceV1Beta1Client_UpdateAttestor() { } func ExampleBinauthzManagementServiceV1Beta1Client_ListAttestors() { - // import binaryauthorizationpb "google.golang.org/genproto/googleapis/cloud/binaryauthorization/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := binaryauthorization.NewBinauthzManagementServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &binaryauthorizationpb.ListAttestorsRequest{ // TODO: Fill request struct fields. @@ -167,6 +162,7 @@ func ExampleBinauthzManagementServiceV1Beta1Client_DeleteAttestor() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &binaryauthorizationpb.DeleteAttestorRequest{ // TODO: Fill request struct fields. diff --git a/binaryauthorization/apiv1beta1/doc.go b/binaryauthorization/apiv1beta1/doc.go index eeb723f7f0dd..acc1fb13b356 100644 --- a/binaryauthorization/apiv1beta1/doc.go +++ b/binaryauthorization/apiv1beta1/doc.go @@ -20,6 +20,8 @@ // The management interface for Binary Authorization, a system providing // policy control for images deployed to Kubernetes Engine clusters. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package binaryauthorization // import "cloud.google.com/go/binaryauthorization/apiv1beta1" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/channel/apiv1/cloud_channel_client.go b/channel/apiv1/cloud_channel_client.go index 4f9426625cb1..e56346990304 100644 --- a/channel/apiv1/cloud_channel_client.go +++ b/channel/apiv1/cloud_channel_client.go @@ -77,7 +77,7 @@ type CloudChannelCallOptions struct { ListSubscribers []gax.CallOption } -func defaultCloudChannelClientOptions() []option.ClientOption { +func defaultCloudChannelGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudchannel.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudchannel.mtls.googleapis.com:443"), @@ -347,32 +347,59 @@ func defaultCloudChannelCallOptions() *CloudChannelCallOptions { } } -// CloudChannelClient is a client for interacting with Cloud Channel API. -// -// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. -type CloudChannelClient struct { - // Connection pool of gRPC connections to the service. - connPool gtransport.ConnPool - - // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE - disableDeadlines bool - - // The gRPC API client. - cloudChannelClient channelpb.CloudChannelServiceClient - - // LROClient is used internally to handle longrunning operations. - // It is exposed so that its CallOptions can be modified if required. - // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CloudChannelCallOptions - - // The x-goog-* metadata to be sent with each request. - xGoogMetadata metadata.MD +// internalCloudChannelClient is an interface that defines the methods availaible from Cloud Channel API. +type internalCloudChannelClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListCustomers(context.Context, *channelpb.ListCustomersRequest, ...gax.CallOption) *CustomerIterator + GetCustomer(context.Context, *channelpb.GetCustomerRequest, ...gax.CallOption) (*channelpb.Customer, error) + CheckCloudIdentityAccountsExist(context.Context, *channelpb.CheckCloudIdentityAccountsExistRequest, ...gax.CallOption) (*channelpb.CheckCloudIdentityAccountsExistResponse, error) + CreateCustomer(context.Context, *channelpb.CreateCustomerRequest, ...gax.CallOption) (*channelpb.Customer, error) + UpdateCustomer(context.Context, *channelpb.UpdateCustomerRequest, ...gax.CallOption) (*channelpb.Customer, error) + DeleteCustomer(context.Context, *channelpb.DeleteCustomerRequest, ...gax.CallOption) error + ProvisionCloudIdentity(context.Context, *channelpb.ProvisionCloudIdentityRequest, ...gax.CallOption) (*ProvisionCloudIdentityOperation, error) + ProvisionCloudIdentityOperation(name string) *ProvisionCloudIdentityOperation + ListEntitlements(context.Context, *channelpb.ListEntitlementsRequest, ...gax.CallOption) *EntitlementIterator + ListTransferableSkus(context.Context, *channelpb.ListTransferableSkusRequest, ...gax.CallOption) *TransferableSkuIterator + ListTransferableOffers(context.Context, *channelpb.ListTransferableOffersRequest, ...gax.CallOption) *TransferableOfferIterator + GetEntitlement(context.Context, *channelpb.GetEntitlementRequest, ...gax.CallOption) (*channelpb.Entitlement, error) + CreateEntitlement(context.Context, *channelpb.CreateEntitlementRequest, ...gax.CallOption) (*CreateEntitlementOperation, error) + CreateEntitlementOperation(name string) *CreateEntitlementOperation + ChangeParameters(context.Context, *channelpb.ChangeParametersRequest, ...gax.CallOption) (*ChangeParametersOperation, error) + ChangeParametersOperation(name string) *ChangeParametersOperation + ChangeRenewalSettings(context.Context, *channelpb.ChangeRenewalSettingsRequest, ...gax.CallOption) (*ChangeRenewalSettingsOperation, error) + ChangeRenewalSettingsOperation(name string) *ChangeRenewalSettingsOperation + ChangeOffer(context.Context, *channelpb.ChangeOfferRequest, ...gax.CallOption) (*ChangeOfferOperation, error) + ChangeOfferOperation(name string) *ChangeOfferOperation + StartPaidService(context.Context, *channelpb.StartPaidServiceRequest, ...gax.CallOption) (*StartPaidServiceOperation, error) + StartPaidServiceOperation(name string) *StartPaidServiceOperation + SuspendEntitlement(context.Context, *channelpb.SuspendEntitlementRequest, ...gax.CallOption) (*SuspendEntitlementOperation, error) + SuspendEntitlementOperation(name string) *SuspendEntitlementOperation + CancelEntitlement(context.Context, *channelpb.CancelEntitlementRequest, ...gax.CallOption) (*CancelEntitlementOperation, error) + CancelEntitlementOperation(name string) *CancelEntitlementOperation + ActivateEntitlement(context.Context, *channelpb.ActivateEntitlementRequest, ...gax.CallOption) (*ActivateEntitlementOperation, error) + ActivateEntitlementOperation(name string) *ActivateEntitlementOperation + TransferEntitlements(context.Context, *channelpb.TransferEntitlementsRequest, ...gax.CallOption) (*TransferEntitlementsOperation, error) + TransferEntitlementsOperation(name string) *TransferEntitlementsOperation + TransferEntitlementsToGoogle(context.Context, *channelpb.TransferEntitlementsToGoogleRequest, ...gax.CallOption) (*TransferEntitlementsToGoogleOperation, error) + TransferEntitlementsToGoogleOperation(name string) *TransferEntitlementsToGoogleOperation + ListChannelPartnerLinks(context.Context, *channelpb.ListChannelPartnerLinksRequest, ...gax.CallOption) *ChannelPartnerLinkIterator + GetChannelPartnerLink(context.Context, *channelpb.GetChannelPartnerLinkRequest, ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) + CreateChannelPartnerLink(context.Context, *channelpb.CreateChannelPartnerLinkRequest, ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) + UpdateChannelPartnerLink(context.Context, *channelpb.UpdateChannelPartnerLinkRequest, ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) + ListProducts(context.Context, *channelpb.ListProductsRequest, ...gax.CallOption) *ProductIterator + ListSkus(context.Context, *channelpb.ListSkusRequest, ...gax.CallOption) *SkuIterator + ListOffers(context.Context, *channelpb.ListOffersRequest, ...gax.CallOption) *OfferIterator + ListPurchasableSkus(context.Context, *channelpb.ListPurchasableSkusRequest, ...gax.CallOption) *PurchasableSkuIterator + ListPurchasableOffers(context.Context, *channelpb.ListPurchasableOffersRequest, ...gax.CallOption) *PurchasableOfferIterator + RegisterSubscriber(context.Context, *channelpb.RegisterSubscriberRequest, ...gax.CallOption) (*channelpb.RegisterSubscriberResponse, error) + UnregisterSubscriber(context.Context, *channelpb.UnregisterSubscriberRequest, ...gax.CallOption) (*channelpb.UnregisterSubscriberResponse, error) + ListSubscribers(context.Context, *channelpb.ListSubscribersRequest, ...gax.CallOption) *StringIterator } -// NewCloudChannelClient creates a new cloud channel service client. +// CloudChannelClient is a client for interacting with Cloud Channel API. +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. // // CloudChannelService lets Google cloud resellers and distributors manage // their customers, channel partners, entitlements, and reports. @@ -397,68 +424,39 @@ type CloudChannelClient struct { // // ChannelPartnerLinks: An entity that identifies links between // distributors and their indirect resellers in a channel. -func NewCloudChannelClient(ctx context.Context, opts ...option.ClientOption) (*CloudChannelClient, error) { - clientOpts := defaultCloudChannelClientOptions() - - if newCloudChannelClientHook != nil { - hookOpts, err := newCloudChannelClientHook(ctx, clientHookParams{}) - if err != nil { - return nil, err - } - clientOpts = append(clientOpts, hookOpts...) - } - - disableDeadlines, err := checkDisableDeadlines() - if err != nil { - return nil, err - } - - connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...) - if err != nil { - return nil, err - } - c := &CloudChannelClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultCloudChannelCallOptions(), +type CloudChannelClient struct { + // The internal transport-dependent client. + internalClient internalCloudChannelClient - cloudChannelClient: channelpb.NewCloudChannelServiceClient(connPool), - } - c.setGoogleClientInfo() + // The call options for this service. + CallOptions *CloudChannelCallOptions - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) - if err != nil { - // This error "should not happen", since we are just reusing old connection pool - // and never actually need to dial. - // If this does happen, we could leak connp. However, we cannot close conn: - // If the user invoked the constructor with option.WithGRPCConn, - // we would close a connection that's still in use. - // TODO: investigate error conditions. - return nil, err - } - return c, nil + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient } -// Connection returns a connection to the API service. -// -// Deprecated. -func (c *CloudChannelClient) Connection() *grpc.ClientConn { - return c.connPool.Conn() -} +// Wrapper methods routed to the internal client. // Close closes the connection to the API service. The user should invoke this when // the client is no longer required. func (c *CloudChannelClient) Close() error { - return c.connPool.Close() + return c.internalClient.Close() } // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CloudChannelClient) setGoogleClientInfo(keyval ...string) { - kv := append([]string{"gl-go", versionGo()}, keyval...) - kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) - c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +func (c *CloudChannelClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CloudChannelClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() } // ListCustomers list Customers. @@ -473,43 +471,7 @@ func (c *CloudChannelClient) setGoogleClientInfo(keyval ...string) { // Return value: // List of Customers, or an empty list if there are no customers. func (c *CloudChannelClient) ListCustomers(ctx context.Context, req *channelpb.ListCustomersRequest, opts ...gax.CallOption) *CustomerIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCustomers[0:len(c.CallOptions.ListCustomers):len(c.CallOptions.ListCustomers)], opts...) - it := &CustomerIterator{} - req = proto.Clone(req).(*channelpb.ListCustomersRequest) - it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Customer, string, error) { - var resp *channelpb.ListCustomersResponse - req.PageToken = pageToken - if pageSize > math.MaxInt32 { - req.PageSize = math.MaxInt32 - } else { - req.PageSize = int32(pageSize) - } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ListCustomers(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, "", err - } - - it.Response = resp - return resp.GetCustomers(), resp.GetNextPageToken(), nil - } - fetch := func(pageSize int, pageToken string) (string, error) { - items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) - if err != nil { - return "", err - } - it.items = append(it.items, items...) - return nextPageToken, nil - } - it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) - it.pageInfo.MaxSize = int(req.GetPageSize()) - it.pageInfo.Token = req.GetPageToken() - return it + return c.internalClient.ListCustomers(ctx, req, opts...) } // GetCustomer returns a requested Customer resource. @@ -527,24 +489,7 @@ func (c *CloudChannelClient) ListCustomers(ctx context.Context, req *channelpb.L // Return value: // The Customer resource. func (c *CloudChannelClient) GetCustomer(ctx context.Context, req *channelpb.GetCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCustomer[0:len(c.CallOptions.GetCustomer):len(c.CallOptions.GetCustomer)], opts...) - var resp *channelpb.Customer - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.GetCustomer(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil + return c.internalClient.GetCustomer(ctx, req, opts...) } // CheckCloudIdentityAccountsExist confirms the existence of Cloud Identity accounts based on the domain and @@ -566,24 +511,7 @@ func (c *CloudChannelClient) GetCustomer(ctx context.Context, req *channelpb.Get // Note: in the v1alpha1 version of the API, a NOT_FOUND error returns if // no CloudIdentityCustomerAccount resources match the domain. func (c *CloudChannelClient) CheckCloudIdentityAccountsExist(ctx context.Context, req *channelpb.CheckCloudIdentityAccountsExistRequest, opts ...gax.CallOption) (*channelpb.CheckCloudIdentityAccountsExistResponse, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CheckCloudIdentityAccountsExist[0:len(c.CallOptions.CheckCloudIdentityAccountsExist):len(c.CallOptions.CheckCloudIdentityAccountsExist)], opts...) - var resp *channelpb.CheckCloudIdentityAccountsExistResponse - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.CheckCloudIdentityAccountsExist(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil + return c.internalClient.CheckCloudIdentityAccountsExist(ctx, req, opts...) } // CreateCustomer creates a new Customer resource under the reseller or distributor @@ -603,24 +531,7 @@ func (c *CloudChannelClient) CheckCloudIdentityAccountsExist(ctx context.Context // Return value: // The newly created Customer resource. func (c *CloudChannelClient) CreateCustomer(ctx context.Context, req *channelpb.CreateCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCustomer[0:len(c.CallOptions.CreateCustomer):len(c.CallOptions.CreateCustomer)], opts...) - var resp *channelpb.Customer - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.CreateCustomer(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil + return c.internalClient.CreateCustomer(ctx, req, opts...) } // UpdateCustomer updates an existing Customer resource for the reseller or @@ -638,24 +549,7 @@ func (c *CloudChannelClient) CreateCustomer(ctx context.Context, req *channelpb. // Return value: // The updated Customer resource. func (c *CloudChannelClient) UpdateCustomer(ctx context.Context, req *channelpb.UpdateCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer.name", url.QueryEscape(req.GetCustomer().GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCustomer[0:len(c.CallOptions.UpdateCustomer):len(c.CallOptions.UpdateCustomer)], opts...) - var resp *channelpb.Customer - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.UpdateCustomer(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil + return c.internalClient.UpdateCustomer(ctx, req, opts...) } // DeleteCustomer deletes the given Customer permanently and irreversibly. @@ -671,20 +565,7 @@ func (c *CloudChannelClient) UpdateCustomer(ctx context.Context, req *channelpb. // // NOT_FOUND: No Customer resource found for the name in the request. func (c *CloudChannelClient) DeleteCustomer(ctx context.Context, req *channelpb.DeleteCustomerRequest, opts ...gax.CallOption) error { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteCustomer[0:len(c.CallOptions.DeleteCustomer):len(c.CallOptions.DeleteCustomer)], opts...) - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - _, err = c.cloudChannelClient.DeleteCustomer(ctx, req, settings.GRPC...) - return err - }, opts...) - return err + return c.internalClient.DeleteCustomer(ctx, req, opts...) } // ProvisionCloudIdentity creates a Cloud Identity for the given customer using the customer’s @@ -714,26 +595,13 @@ func (c *CloudChannelClient) DeleteCustomer(ctx context.Context, req *channelpb. // CloudChannelOperationsService. The Operation metadata contains an // instance of OperationMetadata. func (c *CloudChannelClient) ProvisionCloudIdentity(ctx context.Context, req *channelpb.ProvisionCloudIdentityRequest, opts ...gax.CallOption) (*ProvisionCloudIdentityOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer", url.QueryEscape(req.GetCustomer()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ProvisionCloudIdentity[0:len(c.CallOptions.ProvisionCloudIdentity):len(c.CallOptions.ProvisionCloudIdentity)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ProvisionCloudIdentity(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return &ProvisionCloudIdentityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), - }, nil + return c.internalClient.ProvisionCloudIdentity(ctx, req, opts...) +} + +// ProvisionCloudIdentityOperation returns a new ProvisionCloudIdentityOperation from a given name. +// The name must be that of a previously created ProvisionCloudIdentityOperation, possibly from a different process. +func (c *CloudChannelClient) ProvisionCloudIdentityOperation(name string) *ProvisionCloudIdentityOperation { + return c.internalClient.ProvisionCloudIdentityOperation(name) } // ListEntitlements lists Entitlements belonging to a customer. @@ -747,43 +615,7 @@ func (c *CloudChannelClient) ProvisionCloudIdentity(ctx context.Context, req *ch // Return value: // A list of the customer’s Entitlements. func (c *CloudChannelClient) ListEntitlements(ctx context.Context, req *channelpb.ListEntitlementsRequest, opts ...gax.CallOption) *EntitlementIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListEntitlements[0:len(c.CallOptions.ListEntitlements):len(c.CallOptions.ListEntitlements)], opts...) - it := &EntitlementIterator{} - req = proto.Clone(req).(*channelpb.ListEntitlementsRequest) - it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Entitlement, string, error) { - var resp *channelpb.ListEntitlementsResponse - req.PageToken = pageToken - if pageSize > math.MaxInt32 { - req.PageSize = math.MaxInt32 - } else { - req.PageSize = int32(pageSize) - } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ListEntitlements(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, "", err - } - - it.Response = resp - return resp.GetEntitlements(), resp.GetNextPageToken(), nil - } - fetch := func(pageSize int, pageToken string) (string, error) { - items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) - if err != nil { - return "", err - } - it.items = append(it.items, items...) - return nextPageToken, nil - } - it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) - it.pageInfo.MaxSize = int(req.GetPageSize()) - it.pageInfo.Token = req.GetPageToken() - return it + return c.internalClient.ListEntitlements(ctx, req, opts...) } // ListTransferableSkus list TransferableSkus of a customer based on the Cloud Identity ID or @@ -809,43 +641,7 @@ func (c *CloudChannelClient) ListEntitlements(ctx context.Context, req *channelp // Return value: // A list of the customer’s TransferableSku. func (c *CloudChannelClient) ListTransferableSkus(ctx context.Context, req *channelpb.ListTransferableSkusRequest, opts ...gax.CallOption) *TransferableSkuIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTransferableSkus[0:len(c.CallOptions.ListTransferableSkus):len(c.CallOptions.ListTransferableSkus)], opts...) - it := &TransferableSkuIterator{} - req = proto.Clone(req).(*channelpb.ListTransferableSkusRequest) - it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.TransferableSku, string, error) { - var resp *channelpb.ListTransferableSkusResponse - req.PageToken = pageToken - if pageSize > math.MaxInt32 { - req.PageSize = math.MaxInt32 - } else { - req.PageSize = int32(pageSize) - } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ListTransferableSkus(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, "", err - } - - it.Response = resp - return resp.GetTransferableSkus(), resp.GetNextPageToken(), nil - } - fetch := func(pageSize int, pageToken string) (string, error) { - items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) - if err != nil { - return "", err - } - it.items = append(it.items, items...) - return nextPageToken, nil - } - it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) - it.pageInfo.MaxSize = int(req.GetPageSize()) - it.pageInfo.Token = req.GetPageToken() - return it + return c.internalClient.ListTransferableSkus(ctx, req, opts...) } // ListTransferableOffers list TransferableOffers of a customer based on Cloud Identity ID or @@ -871,43 +667,7 @@ func (c *CloudChannelClient) ListTransferableSkus(ctx context.Context, req *chan // Return value: // List of TransferableOffer for the given customer and SKU. func (c *CloudChannelClient) ListTransferableOffers(ctx context.Context, req *channelpb.ListTransferableOffersRequest, opts ...gax.CallOption) *TransferableOfferIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTransferableOffers[0:len(c.CallOptions.ListTransferableOffers):len(c.CallOptions.ListTransferableOffers)], opts...) - it := &TransferableOfferIterator{} - req = proto.Clone(req).(*channelpb.ListTransferableOffersRequest) - it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.TransferableOffer, string, error) { - var resp *channelpb.ListTransferableOffersResponse - req.PageToken = pageToken - if pageSize > math.MaxInt32 { - req.PageSize = math.MaxInt32 - } else { - req.PageSize = int32(pageSize) - } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ListTransferableOffers(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, "", err - } - - it.Response = resp - return resp.GetTransferableOffers(), resp.GetNextPageToken(), nil - } - fetch := func(pageSize int, pageToken string) (string, error) { - items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) - if err != nil { - return "", err - } - it.items = append(it.items, items...) - return nextPageToken, nil - } - it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) - it.pageInfo.MaxSize = int(req.GetPageSize()) - it.pageInfo.Token = req.GetPageToken() - return it + return c.internalClient.ListTransferableOffers(ctx, req, opts...) } // GetEntitlement returns a requested Entitlement resource. @@ -923,24 +683,7 @@ func (c *CloudChannelClient) ListTransferableOffers(ctx context.Context, req *ch // Return value: // The requested Entitlement resource. func (c *CloudChannelClient) GetEntitlement(ctx context.Context, req *channelpb.GetEntitlementRequest, opts ...gax.CallOption) (*channelpb.Entitlement, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEntitlement[0:len(c.CallOptions.GetEntitlement):len(c.CallOptions.GetEntitlement)], opts...) - var resp *channelpb.Entitlement - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.GetEntitlement(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil + return c.internalClient.GetEntitlement(ctx, req, opts...) } // CreateEntitlement creates an entitlement for a customer. @@ -996,26 +739,13 @@ func (c *CloudChannelClient) GetEntitlement(ctx context.Context, req *channelpb. // CloudChannelOperationsService. The Operation metadata will contain an // instance of OperationMetadata. func (c *CloudChannelClient) CreateEntitlement(ctx context.Context, req *channelpb.CreateEntitlementRequest, opts ...gax.CallOption) (*CreateEntitlementOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateEntitlement[0:len(c.CallOptions.CreateEntitlement):len(c.CallOptions.CreateEntitlement)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.CreateEntitlement(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return &CreateEntitlementOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), - }, nil + return c.internalClient.CreateEntitlement(ctx, req, opts...) +} + +// CreateEntitlementOperation returns a new CreateEntitlementOperation from a given name. +// The name must be that of a previously created CreateEntitlementOperation, possibly from a different process. +func (c *CloudChannelClient) CreateEntitlementOperation(name string) *CreateEntitlementOperation { + return c.internalClient.CreateEntitlementOperation(name) } // ChangeParameters change parameters of the entitlement. @@ -1046,26 +776,13 @@ func (c *CloudChannelClient) CreateEntitlement(ctx context.Context, req *channel // CloudChannelOperationsService. The Operation metadata will contain an // instance of OperationMetadata. func (c *CloudChannelClient) ChangeParameters(ctx context.Context, req *channelpb.ChangeParametersRequest, opts ...gax.CallOption) (*ChangeParametersOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ChangeParameters[0:len(c.CallOptions.ChangeParameters):len(c.CallOptions.ChangeParameters)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ChangeParameters(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return &ChangeParametersOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), - }, nil + return c.internalClient.ChangeParameters(ctx, req, opts...) +} + +// ChangeParametersOperation returns a new ChangeParametersOperation from a given name. +// The name must be that of a previously created ChangeParametersOperation, possibly from a different process. +func (c *CloudChannelClient) ChangeParametersOperation(name string) *ChangeParametersOperation { + return c.internalClient.ChangeParametersOperation(name) } // ChangeRenewalSettings updates the renewal settings for an existing customer entitlement. @@ -1097,26 +814,13 @@ func (c *CloudChannelClient) ChangeParameters(ctx context.Context, req *channelp // CloudChannelOperationsService. The Operation metadata will contain an // instance of OperationMetadata. func (c *CloudChannelClient) ChangeRenewalSettings(ctx context.Context, req *channelpb.ChangeRenewalSettingsRequest, opts ...gax.CallOption) (*ChangeRenewalSettingsOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ChangeRenewalSettings[0:len(c.CallOptions.ChangeRenewalSettings):len(c.CallOptions.ChangeRenewalSettings)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ChangeRenewalSettings(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return &ChangeRenewalSettingsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), - }, nil + return c.internalClient.ChangeRenewalSettings(ctx, req, opts...) +} + +// ChangeRenewalSettingsOperation returns a new ChangeRenewalSettingsOperation from a given name. +// The name must be that of a previously created ChangeRenewalSettingsOperation, possibly from a different process. +func (c *CloudChannelClient) ChangeRenewalSettingsOperation(name string) *ChangeRenewalSettingsOperation { + return c.internalClient.ChangeRenewalSettingsOperation(name) } // ChangeOffer updates the Offer for an existing customer entitlement. @@ -1145,26 +849,13 @@ func (c *CloudChannelClient) ChangeRenewalSettings(ctx context.Context, req *cha // CloudChannelOperationsService. The Operation metadata will contain an // instance of OperationMetadata. func (c *CloudChannelClient) ChangeOffer(ctx context.Context, req *channelpb.ChangeOfferRequest, opts ...gax.CallOption) (*ChangeOfferOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ChangeOffer[0:len(c.CallOptions.ChangeOffer):len(c.CallOptions.ChangeOffer)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ChangeOffer(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return &ChangeOfferOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), - }, nil + return c.internalClient.ChangeOffer(ctx, req, opts...) +} + +// ChangeOfferOperation returns a new ChangeOfferOperation from a given name. +// The name must be that of a previously created ChangeOfferOperation, possibly from a different process. +func (c *CloudChannelClient) ChangeOfferOperation(name string) *ChangeOfferOperation { + return c.internalClient.ChangeOfferOperation(name) } // StartPaidService starts paid service for a trial entitlement. @@ -1197,26 +888,13 @@ func (c *CloudChannelClient) ChangeOffer(ctx context.Context, req *channelpb.Cha // CloudChannelOperationsService. The Operation metadata will contain an // instance of OperationMetadata. func (c *CloudChannelClient) StartPaidService(ctx context.Context, req *channelpb.StartPaidServiceRequest, opts ...gax.CallOption) (*StartPaidServiceOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.StartPaidService[0:len(c.CallOptions.StartPaidService):len(c.CallOptions.StartPaidService)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.StartPaidService(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return &StartPaidServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), - }, nil + return c.internalClient.StartPaidService(ctx, req, opts...) +} + +// StartPaidServiceOperation returns a new StartPaidServiceOperation from a given name. +// The name must be that of a previously created StartPaidServiceOperation, possibly from a different process. +func (c *CloudChannelClient) StartPaidServiceOperation(name string) *StartPaidServiceOperation { + return c.internalClient.StartPaidServiceOperation(name) } // SuspendEntitlement suspends a previously fulfilled entitlement. @@ -1246,26 +924,13 @@ func (c *CloudChannelClient) StartPaidService(ctx context.Context, req *channelp // CloudChannelOperationsService. The Operation metadata will contain an // instance of OperationMetadata. func (c *CloudChannelClient) SuspendEntitlement(ctx context.Context, req *channelpb.SuspendEntitlementRequest, opts ...gax.CallOption) (*SuspendEntitlementOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SuspendEntitlement[0:len(c.CallOptions.SuspendEntitlement):len(c.CallOptions.SuspendEntitlement)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.SuspendEntitlement(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return &SuspendEntitlementOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), - }, nil + return c.internalClient.SuspendEntitlement(ctx, req, opts...) +} + +// SuspendEntitlementOperation returns a new SuspendEntitlementOperation from a given name. +// The name must be that of a previously created SuspendEntitlementOperation, possibly from a different process. +func (c *CloudChannelClient) SuspendEntitlementOperation(name string) *SuspendEntitlementOperation { + return c.internalClient.SuspendEntitlementOperation(name) } // CancelEntitlement cancels a previously fulfilled entitlement. @@ -1301,26 +966,13 @@ func (c *CloudChannelClient) SuspendEntitlement(ctx context.Context, req *channe // google.protobuf.Empty on success. The Operation metadata will contain an // instance of OperationMetadata. func (c *CloudChannelClient) CancelEntitlement(ctx context.Context, req *channelpb.CancelEntitlementRequest, opts ...gax.CallOption) (*CancelEntitlementOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CancelEntitlement[0:len(c.CallOptions.CancelEntitlement):len(c.CallOptions.CancelEntitlement)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.CancelEntitlement(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return &CancelEntitlementOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), - }, nil + return c.internalClient.CancelEntitlement(ctx, req, opts...) +} + +// CancelEntitlementOperation returns a new CancelEntitlementOperation from a given name. +// The name must be that of a previously created CancelEntitlementOperation, possibly from a different process. +func (c *CloudChannelClient) CancelEntitlementOperation(name string) *CancelEntitlementOperation { + return c.internalClient.CancelEntitlementOperation(name) } // ActivateEntitlement activates a previously suspended entitlement. Entitlements suspended for @@ -1357,26 +1009,13 @@ func (c *CloudChannelClient) CancelEntitlement(ctx context.Context, req *channel // CloudChannelOperationsService. The Operation metadata will contain an // instance of OperationMetadata. func (c *CloudChannelClient) ActivateEntitlement(ctx context.Context, req *channelpb.ActivateEntitlementRequest, opts ...gax.CallOption) (*ActivateEntitlementOperation, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ActivateEntitlement[0:len(c.CallOptions.ActivateEntitlement):len(c.CallOptions.ActivateEntitlement)], opts...) - var resp *longrunningpb.Operation - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.cloudChannelClient.ActivateEntitlement(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return &ActivateEntitlementOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), - }, nil + return c.internalClient.ActivateEntitlement(ctx, req, opts...) +} + +// ActivateEntitlementOperation returns a new ActivateEntitlementOperation from a given name. +// The name must be that of a previously created ActivateEntitlementOperation, possibly from a different process. +func (c *CloudChannelClient) ActivateEntitlementOperation(name string) *ActivateEntitlementOperation { + return c.internalClient.ActivateEntitlementOperation(name) } // TransferEntitlements transfers customer entitlements to new reseller. @@ -1421,6 +1060,906 @@ func (c *CloudChannelClient) ActivateEntitlement(ctx context.Context, req *chann // CloudChannelOperationsService. The Operation metadata will contain an // instance of OperationMetadata. func (c *CloudChannelClient) TransferEntitlements(ctx context.Context, req *channelpb.TransferEntitlementsRequest, opts ...gax.CallOption) (*TransferEntitlementsOperation, error) { + return c.internalClient.TransferEntitlements(ctx, req, opts...) +} + +// TransferEntitlementsOperation returns a new TransferEntitlementsOperation from a given name. +// The name must be that of a previously created TransferEntitlementsOperation, possibly from a different process. +func (c *CloudChannelClient) TransferEntitlementsOperation(name string) *TransferEntitlementsOperation { + return c.internalClient.TransferEntitlementsOperation(name) +} + +// TransferEntitlementsToGoogle transfers customer entitlements from their current reseller to Google. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: The customer or offer resource was not found. +// +// ALREADY_EXISTS: The SKU was already transferred for the customer. +// +// CONDITION_NOT_MET or FAILED_PRECONDITION: +// +// The SKU requires domain verification to transfer, but the domain is +// not verified. +// +// An Add-On SKU (example, Vault or Drive) is missing the +// pre-requisite SKU (example, G Suite Basic). +// +// (Developer accounts only) Reseller and resold domain must meet the +// following naming requirements: +// +// Domain names must start with goog-test. +// +// Domain names must include the reseller domain. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The ID of a long-running operation. +// +// To get the results of the operation, call the GetOperation method of +// CloudChannelOperationsService. The response will contain +// google.protobuf.Empty on success. The Operation metadata will contain an +// instance of OperationMetadata. +func (c *CloudChannelClient) TransferEntitlementsToGoogle(ctx context.Context, req *channelpb.TransferEntitlementsToGoogleRequest, opts ...gax.CallOption) (*TransferEntitlementsToGoogleOperation, error) { + return c.internalClient.TransferEntitlementsToGoogle(ctx, req, opts...) +} + +// TransferEntitlementsToGoogleOperation returns a new TransferEntitlementsToGoogleOperation from a given name. +// The name must be that of a previously created TransferEntitlementsToGoogleOperation, possibly from a different process. +func (c *CloudChannelClient) TransferEntitlementsToGoogleOperation(name string) *TransferEntitlementsToGoogleOperation { + return c.internalClient.TransferEntitlementsToGoogleOperation(name) +} + +// ListChannelPartnerLinks list ChannelPartnerLinks belonging to a distributor. +// You must be a distributor to call this method. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// Return value: +// The list of the distributor account’s ChannelPartnerLink resources. +func (c *CloudChannelClient) ListChannelPartnerLinks(ctx context.Context, req *channelpb.ListChannelPartnerLinksRequest, opts ...gax.CallOption) *ChannelPartnerLinkIterator { + return c.internalClient.ListChannelPartnerLinks(ctx, req, opts...) +} + +// GetChannelPartnerLink returns a requested ChannelPartnerLink resource. +// You must be a distributor to call this method. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: ChannelPartnerLink resource not found because of an +// invalid channel partner link name. +// +// Return value: +// The ChannelPartnerLink resource. +func (c *CloudChannelClient) GetChannelPartnerLink(ctx context.Context, req *channelpb.GetChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { + return c.internalClient.GetChannelPartnerLink(ctx, req, opts...) +} + +// CreateChannelPartnerLink initiates a channel partner link between a distributor and a reseller, or +// between resellers in an n-tier reseller channel. +// Invited partners need to follow the invite_link_uri provided in the +// response to accept. After accepting the invitation, a link is set up +// between the two parties. +// You must be a distributor to call this method. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// ALREADY_EXISTS: The ChannelPartnerLink sent in the request already +// exists. +// +// NOT_FOUND: No Cloud Identity customer exists for provided domain. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The new ChannelPartnerLink resource. +func (c *CloudChannelClient) CreateChannelPartnerLink(ctx context.Context, req *channelpb.CreateChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { + return c.internalClient.CreateChannelPartnerLink(ctx, req, opts...) +} + +// UpdateChannelPartnerLink updates a channel partner link. Distributors call this method to change a +// link’s status. For example, to suspend a partner link. +// You must be a distributor to call this method. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request is different +// from the reseller account in the API request. +// +// INVALID_ARGUMENT: +// +// Required request parameters are missing or invalid. +// +// Link state cannot change from invited to active or suspended. +// +// Cannot send reseller_cloud_identity_id, invite_url, or name in update +// mask. +// +// NOT_FOUND: ChannelPartnerLink resource not found. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The updated ChannelPartnerLink resource. +func (c *CloudChannelClient) UpdateChannelPartnerLink(ctx context.Context, req *channelpb.UpdateChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { + return c.internalClient.UpdateChannelPartnerLink(ctx, req, opts...) +} + +// ListProducts lists the Products the reseller is authorized to sell. +// +// Possible error codes: +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +func (c *CloudChannelClient) ListProducts(ctx context.Context, req *channelpb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator { + return c.internalClient.ListProducts(ctx, req, opts...) +} + +// ListSkus lists the SKUs for a product the reseller is authorized to sell. +// +// Possible error codes: +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +func (c *CloudChannelClient) ListSkus(ctx context.Context, req *channelpb.ListSkusRequest, opts ...gax.CallOption) *SkuIterator { + return c.internalClient.ListSkus(ctx, req, opts...) +} + +// ListOffers lists the Offers the reseller can sell. +// +// Possible error codes: +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +func (c *CloudChannelClient) ListOffers(ctx context.Context, req *channelpb.ListOffersRequest, opts ...gax.CallOption) *OfferIterator { + return c.internalClient.ListOffers(ctx, req, opts...) +} + +// ListPurchasableSkus lists the following: +// +// SKUs that you can purchase for a customer +// +// SKUs that you can upgrade or downgrade for an entitlement. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +func (c *CloudChannelClient) ListPurchasableSkus(ctx context.Context, req *channelpb.ListPurchasableSkusRequest, opts ...gax.CallOption) *PurchasableSkuIterator { + return c.internalClient.ListPurchasableSkus(ctx, req, opts...) +} + +// ListPurchasableOffers lists the following: +// +// Offers that you can purchase for a customer. +// +// Offers that you can change for an entitlement. +// +// Possible error codes: +// +// PERMISSION_DENIED: The customer doesn’t belong to the reseller +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +func (c *CloudChannelClient) ListPurchasableOffers(ctx context.Context, req *channelpb.ListPurchasableOffersRequest, opts ...gax.CallOption) *PurchasableOfferIterator { + return c.internalClient.ListPurchasableOffers(ctx, req, opts...) +} + +// RegisterSubscriber registers a service account with subscriber privileges on the Cloud Pub/Sub +// topic for this Channel Services account. After you create a +// subscriber, you get the events through SubscriberEvent +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request and the +// provided reseller account are different, or the impersonated user +// is not a super admin. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The topic name with the registered service email address. +func (c *CloudChannelClient) RegisterSubscriber(ctx context.Context, req *channelpb.RegisterSubscriberRequest, opts ...gax.CallOption) (*channelpb.RegisterSubscriberResponse, error) { + return c.internalClient.RegisterSubscriber(ctx, req, opts...) +} + +// UnregisterSubscriber unregisters a service account with subscriber privileges on the Cloud +// Pub/Sub topic created for this Channel Services account. If there are no +// service accounts left with subscriber privileges, this deletes the topic. +// You can call ListSubscribers to check for these accounts. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request and the +// provided reseller account are different, or the impersonated user +// is not a super admin. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: The topic resource doesn’t exist. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// The topic name that unregistered the service email address. +// Returns a success response if the service email address wasn’t registered +// with the topic. +func (c *CloudChannelClient) UnregisterSubscriber(ctx context.Context, req *channelpb.UnregisterSubscriberRequest, opts ...gax.CallOption) (*channelpb.UnregisterSubscriberResponse, error) { + return c.internalClient.UnregisterSubscriber(ctx, req, opts...) +} + +// ListSubscribers lists service accounts with subscriber privileges on the Cloud Pub/Sub +// topic created for this Channel Services account. +// +// Possible error codes: +// +// PERMISSION_DENIED: The reseller account making the request and the +// provided reseller account are different, or the impersonated user +// is not a super admin. +// +// INVALID_ARGUMENT: Required request parameters are missing or invalid. +// +// NOT_FOUND: The topic resource doesn’t exist. +// +// INTERNAL: Any non-user error related to a technical issue in the +// backend. Contact Cloud Channel support. +// +// UNKNOWN: Any non-user error related to a technical issue in the backend. +// Contact Cloud Channel support. +// +// Return value: +// A list of service email addresses. +func (c *CloudChannelClient) ListSubscribers(ctx context.Context, req *channelpb.ListSubscribersRequest, opts ...gax.CallOption) *StringIterator { + return c.internalClient.ListSubscribers(ctx, req, opts...) +} + +// cloudChannelGRPCClient is a client for interacting with Cloud Channel API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudChannelGRPCClient struct { + // Connection pool of gRPC connections to the service. + connPool gtransport.ConnPool + + // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE + disableDeadlines bool + + // Points back to the CallOptions field of the containing CloudChannelClient + CallOptions **CloudChannelCallOptions + + // The gRPC API client. + cloudChannelClient channelpb.CloudChannelServiceClient + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient **lroauto.OperationsClient + + // The x-goog-* metadata to be sent with each request. + xGoogMetadata metadata.MD +} + +// NewCloudChannelClient creates a new cloud channel service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. +// +// CloudChannelService lets Google cloud resellers and distributors manage +// their customers, channel partners, entitlements, and reports. +// +// Using this service: +// +// Resellers and distributors can manage a customer entity. +// +// Distributors can register an authorized reseller in their channel and +// provide them with delegated admin access. +// +// Resellers and distributors can manage customer entitlements. +// +// CloudChannelService exposes the following resources: +// +// Customers: An entity—usually an enterprise—managed by a reseller or +// distributor. +// +// Entitlements: An entity that provides a customer with the means to use +// a service. Entitlements are created or updated as a result of a successful +// fulfillment. +// +// ChannelPartnerLinks: An entity that identifies links between +// distributors and their indirect resellers in a channel. +func NewCloudChannelClient(ctx context.Context, opts ...option.ClientOption) (*CloudChannelClient, error) { + clientOpts := defaultCloudChannelGRPCClientOptions() + if newCloudChannelClientHook != nil { + hookOpts, err := newCloudChannelClientHook(ctx, clientHookParams{}) + if err != nil { + return nil, err + } + clientOpts = append(clientOpts, hookOpts...) + } + + disableDeadlines, err := checkDisableDeadlines() + if err != nil { + return nil, err + } + + connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...) + if err != nil { + return nil, err + } + client := CloudChannelClient{CallOptions: defaultCloudChannelCallOptions()} + + c := &cloudChannelGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, + cloudChannelClient: channelpb.NewCloudChannelServiceClient(connPool), + CallOptions: &client.CallOptions, + } + c.setGoogleClientInfo() + + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + if err != nil { + // This error "should not happen", since we are just reusing old connection pool + // and never actually need to dial. + // If this does happen, we could leak connp. However, we cannot close conn: + // If the user invoked the constructor with option.WithGRPCConn, + // we would close a connection that's still in use. + // TODO: investigate error conditions. + return nil, err + } + c.LROClient = &client.LROClient + return &client, nil +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *cloudChannelGRPCClient) Connection() *grpc.ClientConn { + return c.connPool.Conn() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *cloudChannelGRPCClient) setGoogleClientInfo(keyval ...string) { + kv := append([]string{"gl-go", versionGo()}, keyval...) + kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) + c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) +} + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudChannelGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *cloudChannelGRPCClient) ListCustomers(ctx context.Context, req *channelpb.ListCustomersRequest, opts ...gax.CallOption) *CustomerIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListCustomers[0:len((*c.CallOptions).ListCustomers):len((*c.CallOptions).ListCustomers)], opts...) + it := &CustomerIterator{} + req = proto.Clone(req).(*channelpb.ListCustomersRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Customer, string, error) { + var resp *channelpb.ListCustomersResponse + req.PageToken = pageToken + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ListCustomers(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetCustomers(), resp.GetNextPageToken(), nil + } + fetch := func(pageSize int, pageToken string) (string, error) { + items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) + if err != nil { + return "", err + } + it.items = append(it.items, items...) + return nextPageToken, nil + } + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + return it +} + +func (c *cloudChannelGRPCClient) GetCustomer(ctx context.Context, req *channelpb.GetCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetCustomer[0:len((*c.CallOptions).GetCustomer):len((*c.CallOptions).GetCustomer)], opts...) + var resp *channelpb.Customer + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.GetCustomer(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *cloudChannelGRPCClient) CheckCloudIdentityAccountsExist(ctx context.Context, req *channelpb.CheckCloudIdentityAccountsExistRequest, opts ...gax.CallOption) (*channelpb.CheckCloudIdentityAccountsExistResponse, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CheckCloudIdentityAccountsExist[0:len((*c.CallOptions).CheckCloudIdentityAccountsExist):len((*c.CallOptions).CheckCloudIdentityAccountsExist)], opts...) + var resp *channelpb.CheckCloudIdentityAccountsExistResponse + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.CheckCloudIdentityAccountsExist(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *cloudChannelGRPCClient) CreateCustomer(ctx context.Context, req *channelpb.CreateCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CreateCustomer[0:len((*c.CallOptions).CreateCustomer):len((*c.CallOptions).CreateCustomer)], opts...) + var resp *channelpb.Customer + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.CreateCustomer(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *cloudChannelGRPCClient) UpdateCustomer(ctx context.Context, req *channelpb.UpdateCustomerRequest, opts ...gax.CallOption) (*channelpb.Customer, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer.name", url.QueryEscape(req.GetCustomer().GetName()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).UpdateCustomer[0:len((*c.CallOptions).UpdateCustomer):len((*c.CallOptions).UpdateCustomer)], opts...) + var resp *channelpb.Customer + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.UpdateCustomer(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *cloudChannelGRPCClient) DeleteCustomer(ctx context.Context, req *channelpb.DeleteCustomerRequest, opts ...gax.CallOption) error { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).DeleteCustomer[0:len((*c.CallOptions).DeleteCustomer):len((*c.CallOptions).DeleteCustomer)], opts...) + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + _, err = c.cloudChannelClient.DeleteCustomer(ctx, req, settings.GRPC...) + return err + }, opts...) + return err +} + +func (c *cloudChannelGRPCClient) ProvisionCloudIdentity(ctx context.Context, req *channelpb.ProvisionCloudIdentityRequest, opts ...gax.CallOption) (*ProvisionCloudIdentityOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer", url.QueryEscape(req.GetCustomer()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ProvisionCloudIdentity[0:len((*c.CallOptions).ProvisionCloudIdentity):len((*c.CallOptions).ProvisionCloudIdentity)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ProvisionCloudIdentity(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &ProvisionCloudIdentityOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) ListEntitlements(ctx context.Context, req *channelpb.ListEntitlementsRequest, opts ...gax.CallOption) *EntitlementIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListEntitlements[0:len((*c.CallOptions).ListEntitlements):len((*c.CallOptions).ListEntitlements)], opts...) + it := &EntitlementIterator{} + req = proto.Clone(req).(*channelpb.ListEntitlementsRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Entitlement, string, error) { + var resp *channelpb.ListEntitlementsResponse + req.PageToken = pageToken + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ListEntitlements(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetEntitlements(), resp.GetNextPageToken(), nil + } + fetch := func(pageSize int, pageToken string) (string, error) { + items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) + if err != nil { + return "", err + } + it.items = append(it.items, items...) + return nextPageToken, nil + } + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + return it +} + +func (c *cloudChannelGRPCClient) ListTransferableSkus(ctx context.Context, req *channelpb.ListTransferableSkusRequest, opts ...gax.CallOption) *TransferableSkuIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListTransferableSkus[0:len((*c.CallOptions).ListTransferableSkus):len((*c.CallOptions).ListTransferableSkus)], opts...) + it := &TransferableSkuIterator{} + req = proto.Clone(req).(*channelpb.ListTransferableSkusRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.TransferableSku, string, error) { + var resp *channelpb.ListTransferableSkusResponse + req.PageToken = pageToken + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ListTransferableSkus(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetTransferableSkus(), resp.GetNextPageToken(), nil + } + fetch := func(pageSize int, pageToken string) (string, error) { + items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) + if err != nil { + return "", err + } + it.items = append(it.items, items...) + return nextPageToken, nil + } + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + return it +} + +func (c *cloudChannelGRPCClient) ListTransferableOffers(ctx context.Context, req *channelpb.ListTransferableOffersRequest, opts ...gax.CallOption) *TransferableOfferIterator { + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ListTransferableOffers[0:len((*c.CallOptions).ListTransferableOffers):len((*c.CallOptions).ListTransferableOffers)], opts...) + it := &TransferableOfferIterator{} + req = proto.Clone(req).(*channelpb.ListTransferableOffersRequest) + it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.TransferableOffer, string, error) { + var resp *channelpb.ListTransferableOffersResponse + req.PageToken = pageToken + if pageSize > math.MaxInt32 { + req.PageSize = math.MaxInt32 + } else { + req.PageSize = int32(pageSize) + } + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ListTransferableOffers(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, "", err + } + + it.Response = resp + return resp.GetTransferableOffers(), resp.GetNextPageToken(), nil + } + fetch := func(pageSize int, pageToken string) (string, error) { + items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) + if err != nil { + return "", err + } + it.items = append(it.items, items...) + return nextPageToken, nil + } + it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) + it.pageInfo.MaxSize = int(req.GetPageSize()) + it.pageInfo.Token = req.GetPageToken() + return it +} + +func (c *cloudChannelGRPCClient) GetEntitlement(ctx context.Context, req *channelpb.GetEntitlementRequest, opts ...gax.CallOption) (*channelpb.Entitlement, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).GetEntitlement[0:len((*c.CallOptions).GetEntitlement):len((*c.CallOptions).GetEntitlement)], opts...) + var resp *channelpb.Entitlement + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.GetEntitlement(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *cloudChannelGRPCClient) CreateEntitlement(ctx context.Context, req *channelpb.CreateEntitlementRequest, opts ...gax.CallOption) (*CreateEntitlementOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CreateEntitlement[0:len((*c.CallOptions).CreateEntitlement):len((*c.CallOptions).CreateEntitlement)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.CreateEntitlement(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &CreateEntitlementOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) ChangeParameters(ctx context.Context, req *channelpb.ChangeParametersRequest, opts ...gax.CallOption) (*ChangeParametersOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ChangeParameters[0:len((*c.CallOptions).ChangeParameters):len((*c.CallOptions).ChangeParameters)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ChangeParameters(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &ChangeParametersOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) ChangeRenewalSettings(ctx context.Context, req *channelpb.ChangeRenewalSettingsRequest, opts ...gax.CallOption) (*ChangeRenewalSettingsOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ChangeRenewalSettings[0:len((*c.CallOptions).ChangeRenewalSettings):len((*c.CallOptions).ChangeRenewalSettings)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ChangeRenewalSettings(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &ChangeRenewalSettingsOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) ChangeOffer(ctx context.Context, req *channelpb.ChangeOfferRequest, opts ...gax.CallOption) (*ChangeOfferOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ChangeOffer[0:len((*c.CallOptions).ChangeOffer):len((*c.CallOptions).ChangeOffer)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ChangeOffer(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &ChangeOfferOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) StartPaidService(ctx context.Context, req *channelpb.StartPaidServiceRequest, opts ...gax.CallOption) (*StartPaidServiceOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).StartPaidService[0:len((*c.CallOptions).StartPaidService):len((*c.CallOptions).StartPaidService)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.StartPaidService(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &StartPaidServiceOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) SuspendEntitlement(ctx context.Context, req *channelpb.SuspendEntitlementRequest, opts ...gax.CallOption) (*SuspendEntitlementOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).SuspendEntitlement[0:len((*c.CallOptions).SuspendEntitlement):len((*c.CallOptions).SuspendEntitlement)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.SuspendEntitlement(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &SuspendEntitlementOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) CancelEntitlement(ctx context.Context, req *channelpb.CancelEntitlementRequest, opts ...gax.CallOption) (*CancelEntitlementOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).CancelEntitlement[0:len((*c.CallOptions).CancelEntitlement):len((*c.CallOptions).CancelEntitlement)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.CancelEntitlement(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &CancelEntitlementOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) ActivateEntitlement(ctx context.Context, req *channelpb.ActivateEntitlementRequest, opts ...gax.CallOption) (*ActivateEntitlementOperation, error) { + if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { + cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) + defer cancel() + ctx = cctx + } + md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) + ctx = insertMetadata(ctx, c.xGoogMetadata, md) + opts = append((*c.CallOptions).ActivateEntitlement[0:len((*c.CallOptions).ActivateEntitlement):len((*c.CallOptions).ActivateEntitlement)], opts...) + var resp *longrunningpb.Operation + err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { + var err error + resp, err = c.cloudChannelClient.ActivateEntitlement(ctx, req, settings.GRPC...) + return err + }, opts...) + if err != nil { + return nil, err + } + return &ActivateEntitlementOperation{ + lro: longrunning.InternalNewOperation(*c.LROClient, resp), + }, nil +} + +func (c *cloudChannelGRPCClient) TransferEntitlements(ctx context.Context, req *channelpb.TransferEntitlementsRequest, opts ...gax.CallOption) (*TransferEntitlementsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1428,7 +1967,7 @@ func (c *CloudChannelClient) TransferEntitlements(ctx context.Context, req *chan } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TransferEntitlements[0:len(c.CallOptions.TransferEntitlements):len(c.CallOptions.TransferEntitlements)], opts...) + opts = append((*c.CallOptions).TransferEntitlements[0:len((*c.CallOptions).TransferEntitlements):len((*c.CallOptions).TransferEntitlements)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1439,51 +1978,11 @@ func (c *CloudChannelClient) TransferEntitlements(ctx context.Context, req *chan return nil, err } return &TransferEntitlementsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// TransferEntitlementsToGoogle transfers customer entitlements from their current reseller to Google. -// -// Possible error codes: -// -// PERMISSION_DENIED: The customer doesn’t belong to the reseller. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// NOT_FOUND: The customer or offer resource was not found. -// -// ALREADY_EXISTS: The SKU was already transferred for the customer. -// -// CONDITION_NOT_MET or FAILED_PRECONDITION: -// -// The SKU requires domain verification to transfer, but the domain is -// not verified. -// -// An Add-On SKU (example, Vault or Drive) is missing the -// pre-requisite SKU (example, G Suite Basic). -// -// (Developer accounts only) Reseller and resold domain must meet the -// following naming requirements: -// -// Domain names must start with goog-test. -// -// Domain names must include the reseller domain. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. -// -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. -// -// Return value: -// The ID of a long-running operation. -// -// To get the results of the operation, call the GetOperation method of -// CloudChannelOperationsService. The response will contain -// google.protobuf.Empty on success. The Operation metadata will contain an -// instance of OperationMetadata. -func (c *CloudChannelClient) TransferEntitlementsToGoogle(ctx context.Context, req *channelpb.TransferEntitlementsToGoogleRequest, opts ...gax.CallOption) (*TransferEntitlementsToGoogleOperation, error) { +func (c *cloudChannelGRPCClient) TransferEntitlementsToGoogle(ctx context.Context, req *channelpb.TransferEntitlementsToGoogleRequest, opts ...gax.CallOption) (*TransferEntitlementsToGoogleOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1491,7 +1990,7 @@ func (c *CloudChannelClient) TransferEntitlementsToGoogle(ctx context.Context, r } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TransferEntitlementsToGoogle[0:len(c.CallOptions.TransferEntitlementsToGoogle):len(c.CallOptions.TransferEntitlementsToGoogle)], opts...) + opts = append((*c.CallOptions).TransferEntitlementsToGoogle[0:len((*c.CallOptions).TransferEntitlementsToGoogle):len((*c.CallOptions).TransferEntitlementsToGoogle)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1502,26 +2001,14 @@ func (c *CloudChannelClient) TransferEntitlementsToGoogle(ctx context.Context, r return nil, err } return &TransferEntitlementsToGoogleOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListChannelPartnerLinks list ChannelPartnerLinks belonging to a distributor. -// You must be a distributor to call this method. -// -// Possible error codes: -// -// PERMISSION_DENIED: The reseller account making the request is different -// from the reseller account in the API request. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// Return value: -// The list of the distributor account’s ChannelPartnerLink resources. -func (c *CloudChannelClient) ListChannelPartnerLinks(ctx context.Context, req *channelpb.ListChannelPartnerLinksRequest, opts ...gax.CallOption) *ChannelPartnerLinkIterator { +func (c *cloudChannelGRPCClient) ListChannelPartnerLinks(ctx context.Context, req *channelpb.ListChannelPartnerLinksRequest, opts ...gax.CallOption) *ChannelPartnerLinkIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListChannelPartnerLinks[0:len(c.CallOptions.ListChannelPartnerLinks):len(c.CallOptions.ListChannelPartnerLinks)], opts...) + opts = append((*c.CallOptions).ListChannelPartnerLinks[0:len((*c.CallOptions).ListChannelPartnerLinks):len((*c.CallOptions).ListChannelPartnerLinks)], opts...) it := &ChannelPartnerLinkIterator{} req = proto.Clone(req).(*channelpb.ListChannelPartnerLinksRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.ChannelPartnerLink, string, error) { @@ -1558,22 +2045,7 @@ func (c *CloudChannelClient) ListChannelPartnerLinks(ctx context.Context, req *c return it } -// GetChannelPartnerLink returns a requested ChannelPartnerLink resource. -// You must be a distributor to call this method. -// -// Possible error codes: -// -// PERMISSION_DENIED: The reseller account making the request is different -// from the reseller account in the API request. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// NOT_FOUND: ChannelPartnerLink resource not found because of an -// invalid channel partner link name. -// -// Return value: -// The ChannelPartnerLink resource. -func (c *CloudChannelClient) GetChannelPartnerLink(ctx context.Context, req *channelpb.GetChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { +func (c *cloudChannelGRPCClient) GetChannelPartnerLink(ctx context.Context, req *channelpb.GetChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1581,7 +2053,7 @@ func (c *CloudChannelClient) GetChannelPartnerLink(ctx context.Context, req *cha } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetChannelPartnerLink[0:len(c.CallOptions.GetChannelPartnerLink):len(c.CallOptions.GetChannelPartnerLink)], opts...) + opts = append((*c.CallOptions).GetChannelPartnerLink[0:len((*c.CallOptions).GetChannelPartnerLink):len((*c.CallOptions).GetChannelPartnerLink)], opts...) var resp *channelpb.ChannelPartnerLink err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1594,34 +2066,7 @@ func (c *CloudChannelClient) GetChannelPartnerLink(ctx context.Context, req *cha return resp, nil } -// CreateChannelPartnerLink initiates a channel partner link between a distributor and a reseller, or -// between resellers in an n-tier reseller channel. -// Invited partners need to follow the invite_link_uri provided in the -// response to accept. After accepting the invitation, a link is set up -// between the two parties. -// You must be a distributor to call this method. -// -// Possible error codes: -// -// PERMISSION_DENIED: The reseller account making the request is different -// from the reseller account in the API request. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// ALREADY_EXISTS: The ChannelPartnerLink sent in the request already -// exists. -// -// NOT_FOUND: No Cloud Identity customer exists for provided domain. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. -// -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. -// -// Return value: -// The new ChannelPartnerLink resource. -func (c *CloudChannelClient) CreateChannelPartnerLink(ctx context.Context, req *channelpb.CreateChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { +func (c *cloudChannelGRPCClient) CreateChannelPartnerLink(ctx context.Context, req *channelpb.CreateChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1629,7 +2074,7 @@ func (c *CloudChannelClient) CreateChannelPartnerLink(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateChannelPartnerLink[0:len(c.CallOptions.CreateChannelPartnerLink):len(c.CallOptions.CreateChannelPartnerLink)], opts...) + opts = append((*c.CallOptions).CreateChannelPartnerLink[0:len((*c.CallOptions).CreateChannelPartnerLink):len((*c.CallOptions).CreateChannelPartnerLink)], opts...) var resp *channelpb.ChannelPartnerLink err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1642,35 +2087,7 @@ func (c *CloudChannelClient) CreateChannelPartnerLink(ctx context.Context, req * return resp, nil } -// UpdateChannelPartnerLink updates a channel partner link. Distributors call this method to change a -// link’s status. For example, to suspend a partner link. -// You must be a distributor to call this method. -// -// Possible error codes: -// -// PERMISSION_DENIED: The reseller account making the request is different -// from the reseller account in the API request. -// -// INVALID_ARGUMENT: -// -// Required request parameters are missing or invalid. -// -// Link state cannot change from invited to active or suspended. -// -// Cannot send reseller_cloud_identity_id, invite_url, or name in update -// mask. -// -// NOT_FOUND: ChannelPartnerLink resource not found. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. -// -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. -// -// Return value: -// The updated ChannelPartnerLink resource. -func (c *CloudChannelClient) UpdateChannelPartnerLink(ctx context.Context, req *channelpb.UpdateChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { +func (c *cloudChannelGRPCClient) UpdateChannelPartnerLink(ctx context.Context, req *channelpb.UpdateChannelPartnerLinkRequest, opts ...gax.CallOption) (*channelpb.ChannelPartnerLink, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1678,7 +2095,7 @@ func (c *CloudChannelClient) UpdateChannelPartnerLink(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateChannelPartnerLink[0:len(c.CallOptions.UpdateChannelPartnerLink):len(c.CallOptions.UpdateChannelPartnerLink)], opts...) + opts = append((*c.CallOptions).UpdateChannelPartnerLink[0:len((*c.CallOptions).UpdateChannelPartnerLink):len((*c.CallOptions).UpdateChannelPartnerLink)], opts...) var resp *channelpb.ChannelPartnerLink err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1691,14 +2108,9 @@ func (c *CloudChannelClient) UpdateChannelPartnerLink(ctx context.Context, req * return resp, nil } -// ListProducts lists the Products the reseller is authorized to sell. -// -// Possible error codes: -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -func (c *CloudChannelClient) ListProducts(ctx context.Context, req *channelpb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator { +func (c *cloudChannelGRPCClient) ListProducts(ctx context.Context, req *channelpb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListProducts[0:len(c.CallOptions.ListProducts):len(c.CallOptions.ListProducts)], opts...) + opts = append((*c.CallOptions).ListProducts[0:len((*c.CallOptions).ListProducts):len((*c.CallOptions).ListProducts)], opts...) it := &ProductIterator{} req = proto.Clone(req).(*channelpb.ListProductsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Product, string, error) { @@ -1735,15 +2147,10 @@ func (c *CloudChannelClient) ListProducts(ctx context.Context, req *channelpb.Li return it } -// ListSkus lists the SKUs for a product the reseller is authorized to sell. -// -// Possible error codes: -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -func (c *CloudChannelClient) ListSkus(ctx context.Context, req *channelpb.ListSkusRequest, opts ...gax.CallOption) *SkuIterator { +func (c *cloudChannelGRPCClient) ListSkus(ctx context.Context, req *channelpb.ListSkusRequest, opts ...gax.CallOption) *SkuIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSkus[0:len(c.CallOptions.ListSkus):len(c.CallOptions.ListSkus)], opts...) + opts = append((*c.CallOptions).ListSkus[0:len((*c.CallOptions).ListSkus):len((*c.CallOptions).ListSkus)], opts...) it := &SkuIterator{} req = proto.Clone(req).(*channelpb.ListSkusRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Sku, string, error) { @@ -1780,15 +2187,10 @@ func (c *CloudChannelClient) ListSkus(ctx context.Context, req *channelpb.ListSk return it } -// ListOffers lists the Offers the reseller can sell. -// -// Possible error codes: -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -func (c *CloudChannelClient) ListOffers(ctx context.Context, req *channelpb.ListOffersRequest, opts ...gax.CallOption) *OfferIterator { +func (c *cloudChannelGRPCClient) ListOffers(ctx context.Context, req *channelpb.ListOffersRequest, opts ...gax.CallOption) *OfferIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListOffers[0:len(c.CallOptions.ListOffers):len(c.CallOptions.ListOffers)], opts...) + opts = append((*c.CallOptions).ListOffers[0:len((*c.CallOptions).ListOffers):len((*c.CallOptions).ListOffers)], opts...) it := &OfferIterator{} req = proto.Clone(req).(*channelpb.ListOffersRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Offer, string, error) { @@ -1825,21 +2227,10 @@ func (c *CloudChannelClient) ListOffers(ctx context.Context, req *channelpb.List return it } -// ListPurchasableSkus lists the following: -// -// SKUs that you can purchase for a customer -// -// SKUs that you can upgrade or downgrade for an entitlement. -// -// Possible error codes: -// -// PERMISSION_DENIED: The customer doesn’t belong to the reseller. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -func (c *CloudChannelClient) ListPurchasableSkus(ctx context.Context, req *channelpb.ListPurchasableSkusRequest, opts ...gax.CallOption) *PurchasableSkuIterator { +func (c *cloudChannelGRPCClient) ListPurchasableSkus(ctx context.Context, req *channelpb.ListPurchasableSkusRequest, opts ...gax.CallOption) *PurchasableSkuIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer", url.QueryEscape(req.GetCustomer()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListPurchasableSkus[0:len(c.CallOptions.ListPurchasableSkus):len(c.CallOptions.ListPurchasableSkus)], opts...) + opts = append((*c.CallOptions).ListPurchasableSkus[0:len((*c.CallOptions).ListPurchasableSkus):len((*c.CallOptions).ListPurchasableSkus)], opts...) it := &PurchasableSkuIterator{} req = proto.Clone(req).(*channelpb.ListPurchasableSkusRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.PurchasableSku, string, error) { @@ -1876,21 +2267,10 @@ func (c *CloudChannelClient) ListPurchasableSkus(ctx context.Context, req *chann return it } -// ListPurchasableOffers lists the following: -// -// Offers that you can purchase for a customer. -// -// Offers that you can change for an entitlement. -// -// Possible error codes: -// -// PERMISSION_DENIED: The customer doesn’t belong to the reseller -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -func (c *CloudChannelClient) ListPurchasableOffers(ctx context.Context, req *channelpb.ListPurchasableOffersRequest, opts ...gax.CallOption) *PurchasableOfferIterator { +func (c *cloudChannelGRPCClient) ListPurchasableOffers(ctx context.Context, req *channelpb.ListPurchasableOffersRequest, opts ...gax.CallOption) *PurchasableOfferIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "customer", url.QueryEscape(req.GetCustomer()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListPurchasableOffers[0:len(c.CallOptions.ListPurchasableOffers):len(c.CallOptions.ListPurchasableOffers)], opts...) + opts = append((*c.CallOptions).ListPurchasableOffers[0:len((*c.CallOptions).ListPurchasableOffers):len((*c.CallOptions).ListPurchasableOffers)], opts...) it := &PurchasableOfferIterator{} req = proto.Clone(req).(*channelpb.ListPurchasableOffersRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.PurchasableOffer, string, error) { @@ -1927,27 +2307,7 @@ func (c *CloudChannelClient) ListPurchasableOffers(ctx context.Context, req *cha return it } -// RegisterSubscriber registers a service account with subscriber privileges on the Cloud Pub/Sub -// topic for this Channel Services account. After you create a -// subscriber, you get the events through SubscriberEvent -// -// Possible error codes: -// -// PERMISSION_DENIED: The reseller account making the request and the -// provided reseller account are different, or the impersonated user -// is not a super admin. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. -// -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. -// -// Return value: -// The topic name with the registered service email address. -func (c *CloudChannelClient) RegisterSubscriber(ctx context.Context, req *channelpb.RegisterSubscriberRequest, opts ...gax.CallOption) (*channelpb.RegisterSubscriberResponse, error) { +func (c *cloudChannelGRPCClient) RegisterSubscriber(ctx context.Context, req *channelpb.RegisterSubscriberRequest, opts ...gax.CallOption) (*channelpb.RegisterSubscriberResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1955,7 +2315,7 @@ func (c *CloudChannelClient) RegisterSubscriber(ctx context.Context, req *channe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "account", url.QueryEscape(req.GetAccount()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RegisterSubscriber[0:len(c.CallOptions.RegisterSubscriber):len(c.CallOptions.RegisterSubscriber)], opts...) + opts = append((*c.CallOptions).RegisterSubscriber[0:len((*c.CallOptions).RegisterSubscriber):len((*c.CallOptions).RegisterSubscriber)], opts...) var resp *channelpb.RegisterSubscriberResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1968,32 +2328,7 @@ func (c *CloudChannelClient) RegisterSubscriber(ctx context.Context, req *channe return resp, nil } -// UnregisterSubscriber unregisters a service account with subscriber privileges on the Cloud -// Pub/Sub topic created for this Channel Services account. If there are no -// service accounts left with subscriber privileges, this deletes the topic. -// You can call ListSubscribers to check for these accounts. -// -// Possible error codes: -// -// PERMISSION_DENIED: The reseller account making the request and the -// provided reseller account are different, or the impersonated user -// is not a super admin. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// NOT_FOUND: The topic resource doesn’t exist. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. -// -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. -// -// Return value: -// The topic name that unregistered the service email address. -// Returns a success response if the service email address wasn’t registered -// with the topic. -func (c *CloudChannelClient) UnregisterSubscriber(ctx context.Context, req *channelpb.UnregisterSubscriberRequest, opts ...gax.CallOption) (*channelpb.UnregisterSubscriberResponse, error) { +func (c *cloudChannelGRPCClient) UnregisterSubscriber(ctx context.Context, req *channelpb.UnregisterSubscriberRequest, opts ...gax.CallOption) (*channelpb.UnregisterSubscriberResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -2001,7 +2336,7 @@ func (c *CloudChannelClient) UnregisterSubscriber(ctx context.Context, req *chan } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "account", url.QueryEscape(req.GetAccount()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UnregisterSubscriber[0:len(c.CallOptions.UnregisterSubscriber):len(c.CallOptions.UnregisterSubscriber)], opts...) + opts = append((*c.CallOptions).UnregisterSubscriber[0:len((*c.CallOptions).UnregisterSubscriber):len((*c.CallOptions).UnregisterSubscriber)], opts...) var resp *channelpb.UnregisterSubscriberResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -2014,31 +2349,10 @@ func (c *CloudChannelClient) UnregisterSubscriber(ctx context.Context, req *chan return resp, nil } -// ListSubscribers lists service accounts with subscriber privileges on the Cloud Pub/Sub -// topic created for this Channel Services account. -// -// Possible error codes: -// -// PERMISSION_DENIED: The reseller account making the request and the -// provided reseller account are different, or the impersonated user -// is not a super admin. -// -// INVALID_ARGUMENT: Required request parameters are missing or invalid. -// -// NOT_FOUND: The topic resource doesn’t exist. -// -// INTERNAL: Any non-user error related to a technical issue in the -// backend. Contact Cloud Channel support. -// -// UNKNOWN: Any non-user error related to a technical issue in the backend. -// Contact Cloud Channel support. -// -// Return value: -// A list of service email addresses. -func (c *CloudChannelClient) ListSubscribers(ctx context.Context, req *channelpb.ListSubscribersRequest, opts ...gax.CallOption) *StringIterator { +func (c *cloudChannelGRPCClient) ListSubscribers(ctx context.Context, req *channelpb.ListSubscribersRequest, opts ...gax.CallOption) *StringIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "account", url.QueryEscape(req.GetAccount()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSubscribers[0:len(c.CallOptions.ListSubscribers):len(c.CallOptions.ListSubscribers)], opts...) + opts = append((*c.CallOptions).ListSubscribers[0:len((*c.CallOptions).ListSubscribers):len((*c.CallOptions).ListSubscribers)], opts...) it := &StringIterator{} req = proto.Clone(req).(*channelpb.ListSubscribersRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]string, string, error) { @@ -2082,9 +2396,9 @@ type ActivateEntitlementOperation struct { // ActivateEntitlementOperation returns a new ActivateEntitlementOperation from a given name. // The name must be that of a previously created ActivateEntitlementOperation, possibly from a different process. -func (c *CloudChannelClient) ActivateEntitlementOperation(name string) *ActivateEntitlementOperation { +func (c *cloudChannelGRPCClient) ActivateEntitlementOperation(name string) *ActivateEntitlementOperation { return &ActivateEntitlementOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -2151,9 +2465,9 @@ type CancelEntitlementOperation struct { // CancelEntitlementOperation returns a new CancelEntitlementOperation from a given name. // The name must be that of a previously created CancelEntitlementOperation, possibly from a different process. -func (c *CloudChannelClient) CancelEntitlementOperation(name string) *CancelEntitlementOperation { +func (c *cloudChannelGRPCClient) CancelEntitlementOperation(name string) *CancelEntitlementOperation { return &CancelEntitlementOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -2209,9 +2523,9 @@ type ChangeOfferOperation struct { // ChangeOfferOperation returns a new ChangeOfferOperation from a given name. // The name must be that of a previously created ChangeOfferOperation, possibly from a different process. -func (c *CloudChannelClient) ChangeOfferOperation(name string) *ChangeOfferOperation { +func (c *cloudChannelGRPCClient) ChangeOfferOperation(name string) *ChangeOfferOperation { return &ChangeOfferOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -2278,9 +2592,9 @@ type ChangeParametersOperation struct { // ChangeParametersOperation returns a new ChangeParametersOperation from a given name. // The name must be that of a previously created ChangeParametersOperation, possibly from a different process. -func (c *CloudChannelClient) ChangeParametersOperation(name string) *ChangeParametersOperation { +func (c *cloudChannelGRPCClient) ChangeParametersOperation(name string) *ChangeParametersOperation { return &ChangeParametersOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -2347,9 +2661,9 @@ type ChangeRenewalSettingsOperation struct { // ChangeRenewalSettingsOperation returns a new ChangeRenewalSettingsOperation from a given name. // The name must be that of a previously created ChangeRenewalSettingsOperation, possibly from a different process. -func (c *CloudChannelClient) ChangeRenewalSettingsOperation(name string) *ChangeRenewalSettingsOperation { +func (c *cloudChannelGRPCClient) ChangeRenewalSettingsOperation(name string) *ChangeRenewalSettingsOperation { return &ChangeRenewalSettingsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -2416,9 +2730,9 @@ type CreateEntitlementOperation struct { // CreateEntitlementOperation returns a new CreateEntitlementOperation from a given name. // The name must be that of a previously created CreateEntitlementOperation, possibly from a different process. -func (c *CloudChannelClient) CreateEntitlementOperation(name string) *CreateEntitlementOperation { +func (c *cloudChannelGRPCClient) CreateEntitlementOperation(name string) *CreateEntitlementOperation { return &CreateEntitlementOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -2485,9 +2799,9 @@ type ProvisionCloudIdentityOperation struct { // ProvisionCloudIdentityOperation returns a new ProvisionCloudIdentityOperation from a given name. // The name must be that of a previously created ProvisionCloudIdentityOperation, possibly from a different process. -func (c *CloudChannelClient) ProvisionCloudIdentityOperation(name string) *ProvisionCloudIdentityOperation { +func (c *cloudChannelGRPCClient) ProvisionCloudIdentityOperation(name string) *ProvisionCloudIdentityOperation { return &ProvisionCloudIdentityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -2554,9 +2868,9 @@ type StartPaidServiceOperation struct { // StartPaidServiceOperation returns a new StartPaidServiceOperation from a given name. // The name must be that of a previously created StartPaidServiceOperation, possibly from a different process. -func (c *CloudChannelClient) StartPaidServiceOperation(name string) *StartPaidServiceOperation { +func (c *cloudChannelGRPCClient) StartPaidServiceOperation(name string) *StartPaidServiceOperation { return &StartPaidServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -2623,9 +2937,9 @@ type SuspendEntitlementOperation struct { // SuspendEntitlementOperation returns a new SuspendEntitlementOperation from a given name. // The name must be that of a previously created SuspendEntitlementOperation, possibly from a different process. -func (c *CloudChannelClient) SuspendEntitlementOperation(name string) *SuspendEntitlementOperation { +func (c *cloudChannelGRPCClient) SuspendEntitlementOperation(name string) *SuspendEntitlementOperation { return &SuspendEntitlementOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -2692,9 +3006,9 @@ type TransferEntitlementsOperation struct { // TransferEntitlementsOperation returns a new TransferEntitlementsOperation from a given name. // The name must be that of a previously created TransferEntitlementsOperation, possibly from a different process. -func (c *CloudChannelClient) TransferEntitlementsOperation(name string) *TransferEntitlementsOperation { +func (c *cloudChannelGRPCClient) TransferEntitlementsOperation(name string) *TransferEntitlementsOperation { return &TransferEntitlementsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -2761,9 +3075,9 @@ type TransferEntitlementsToGoogleOperation struct { // TransferEntitlementsToGoogleOperation returns a new TransferEntitlementsToGoogleOperation from a given name. // The name must be that of a previously created TransferEntitlementsToGoogleOperation, possibly from a different process. -func (c *CloudChannelClient) TransferEntitlementsToGoogleOperation(name string) *TransferEntitlementsToGoogleOperation { +func (c *cloudChannelGRPCClient) TransferEntitlementsToGoogleOperation(name string) *TransferEntitlementsToGoogleOperation { return &TransferEntitlementsToGoogleOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/channel/apiv1/cloud_channel_client_example_test.go b/channel/apiv1/cloud_channel_client_example_test.go index 3d9feeac95fe..e7d11b60c9f2 100644 --- a/channel/apiv1/cloud_channel_client_example_test.go +++ b/channel/apiv1/cloud_channel_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewCloudChannelClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCloudChannelClient_ListCustomers() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListCustomersRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleCloudChannelClient_ListCustomers() { } func ExampleCloudChannelClient_GetCustomer() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.GetCustomerRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleCloudChannelClient_GetCustomer() { } func ExampleCloudChannelClient_CheckCloudIdentityAccountsExist() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.CheckCloudIdentityAccountsExistRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleCloudChannelClient_CheckCloudIdentityAccountsExist() { } func ExampleCloudChannelClient_CreateCustomer() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.CreateCustomerRequest{ // TODO: Fill request struct fields. @@ -122,13 +119,12 @@ func ExampleCloudChannelClient_CreateCustomer() { } func ExampleCloudChannelClient_UpdateCustomer() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.UpdateCustomerRequest{ // TODO: Fill request struct fields. @@ -147,6 +143,7 @@ func ExampleCloudChannelClient_DeleteCustomer() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.DeleteCustomerRequest{ // TODO: Fill request struct fields. @@ -158,13 +155,12 @@ func ExampleCloudChannelClient_DeleteCustomer() { } func ExampleCloudChannelClient_ProvisionCloudIdentity() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ProvisionCloudIdentityRequest{ // TODO: Fill request struct fields. @@ -183,14 +179,12 @@ func ExampleCloudChannelClient_ProvisionCloudIdentity() { } func ExampleCloudChannelClient_ListEntitlements() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListEntitlementsRequest{ // TODO: Fill request struct fields. @@ -210,14 +204,12 @@ func ExampleCloudChannelClient_ListEntitlements() { } func ExampleCloudChannelClient_ListTransferableSkus() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListTransferableSkusRequest{ // TODO: Fill request struct fields. @@ -237,14 +229,12 @@ func ExampleCloudChannelClient_ListTransferableSkus() { } func ExampleCloudChannelClient_ListTransferableOffers() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListTransferableOffersRequest{ // TODO: Fill request struct fields. @@ -264,13 +254,12 @@ func ExampleCloudChannelClient_ListTransferableOffers() { } func ExampleCloudChannelClient_GetEntitlement() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.GetEntitlementRequest{ // TODO: Fill request struct fields. @@ -284,13 +273,12 @@ func ExampleCloudChannelClient_GetEntitlement() { } func ExampleCloudChannelClient_CreateEntitlement() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.CreateEntitlementRequest{ // TODO: Fill request struct fields. @@ -309,13 +297,12 @@ func ExampleCloudChannelClient_CreateEntitlement() { } func ExampleCloudChannelClient_ChangeParameters() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ChangeParametersRequest{ // TODO: Fill request struct fields. @@ -334,13 +321,12 @@ func ExampleCloudChannelClient_ChangeParameters() { } func ExampleCloudChannelClient_ChangeRenewalSettings() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ChangeRenewalSettingsRequest{ // TODO: Fill request struct fields. @@ -359,13 +345,12 @@ func ExampleCloudChannelClient_ChangeRenewalSettings() { } func ExampleCloudChannelClient_ChangeOffer() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ChangeOfferRequest{ // TODO: Fill request struct fields. @@ -384,13 +369,12 @@ func ExampleCloudChannelClient_ChangeOffer() { } func ExampleCloudChannelClient_StartPaidService() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.StartPaidServiceRequest{ // TODO: Fill request struct fields. @@ -409,13 +393,12 @@ func ExampleCloudChannelClient_StartPaidService() { } func ExampleCloudChannelClient_SuspendEntitlement() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.SuspendEntitlementRequest{ // TODO: Fill request struct fields. @@ -434,13 +417,12 @@ func ExampleCloudChannelClient_SuspendEntitlement() { } func ExampleCloudChannelClient_CancelEntitlement() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.CancelEntitlementRequest{ // TODO: Fill request struct fields. @@ -457,13 +439,12 @@ func ExampleCloudChannelClient_CancelEntitlement() { } func ExampleCloudChannelClient_ActivateEntitlement() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ActivateEntitlementRequest{ // TODO: Fill request struct fields. @@ -482,13 +463,12 @@ func ExampleCloudChannelClient_ActivateEntitlement() { } func ExampleCloudChannelClient_TransferEntitlements() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.TransferEntitlementsRequest{ // TODO: Fill request struct fields. @@ -507,13 +487,12 @@ func ExampleCloudChannelClient_TransferEntitlements() { } func ExampleCloudChannelClient_TransferEntitlementsToGoogle() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.TransferEntitlementsToGoogleRequest{ // TODO: Fill request struct fields. @@ -530,14 +509,12 @@ func ExampleCloudChannelClient_TransferEntitlementsToGoogle() { } func ExampleCloudChannelClient_ListChannelPartnerLinks() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListChannelPartnerLinksRequest{ // TODO: Fill request struct fields. @@ -557,13 +534,12 @@ func ExampleCloudChannelClient_ListChannelPartnerLinks() { } func ExampleCloudChannelClient_GetChannelPartnerLink() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.GetChannelPartnerLinkRequest{ // TODO: Fill request struct fields. @@ -577,13 +553,12 @@ func ExampleCloudChannelClient_GetChannelPartnerLink() { } func ExampleCloudChannelClient_CreateChannelPartnerLink() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.CreateChannelPartnerLinkRequest{ // TODO: Fill request struct fields. @@ -597,13 +572,12 @@ func ExampleCloudChannelClient_CreateChannelPartnerLink() { } func ExampleCloudChannelClient_UpdateChannelPartnerLink() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.UpdateChannelPartnerLinkRequest{ // TODO: Fill request struct fields. @@ -617,14 +591,12 @@ func ExampleCloudChannelClient_UpdateChannelPartnerLink() { } func ExampleCloudChannelClient_ListProducts() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListProductsRequest{ // TODO: Fill request struct fields. @@ -644,14 +616,12 @@ func ExampleCloudChannelClient_ListProducts() { } func ExampleCloudChannelClient_ListSkus() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListSkusRequest{ // TODO: Fill request struct fields. @@ -671,14 +641,12 @@ func ExampleCloudChannelClient_ListSkus() { } func ExampleCloudChannelClient_ListOffers() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListOffersRequest{ // TODO: Fill request struct fields. @@ -698,14 +666,12 @@ func ExampleCloudChannelClient_ListOffers() { } func ExampleCloudChannelClient_ListPurchasableSkus() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListPurchasableSkusRequest{ // TODO: Fill request struct fields. @@ -725,14 +691,12 @@ func ExampleCloudChannelClient_ListPurchasableSkus() { } func ExampleCloudChannelClient_ListPurchasableOffers() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListPurchasableOffersRequest{ // TODO: Fill request struct fields. @@ -752,13 +716,12 @@ func ExampleCloudChannelClient_ListPurchasableOffers() { } func ExampleCloudChannelClient_RegisterSubscriber() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.RegisterSubscriberRequest{ // TODO: Fill request struct fields. @@ -772,13 +735,12 @@ func ExampleCloudChannelClient_RegisterSubscriber() { } func ExampleCloudChannelClient_UnregisterSubscriber() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.UnregisterSubscriberRequest{ // TODO: Fill request struct fields. @@ -792,14 +754,12 @@ func ExampleCloudChannelClient_UnregisterSubscriber() { } func ExampleCloudChannelClient_ListSubscribers() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListSubscribersRequest{ // TODO: Fill request struct fields. diff --git a/channel/apiv1/doc.go b/channel/apiv1/doc.go index 92534a5d9610..6dec129f57ef 100644 --- a/channel/apiv1/doc.go +++ b/channel/apiv1/doc.go @@ -26,7 +26,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package channel // import "cloud.google.com/go/channel/apiv1" import ( @@ -46,7 +46,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/cloudbuild/apiv1/v2/cloud_build_client.go b/cloudbuild/apiv1/v2/cloud_build_client.go index 16657ffd5c17..69790e76391b 100644 --- a/cloudbuild/apiv1/v2/cloud_build_client.go +++ b/cloudbuild/apiv1/v2/cloud_build_client.go @@ -61,7 +61,7 @@ type CallOptions struct { ListWorkerPools []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudbuild.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudbuild.mtls.googleapis.com:443"), @@ -172,32 +172,268 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Build API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateBuild(context.Context, *cloudbuildpb.CreateBuildRequest, ...gax.CallOption) (*CreateBuildOperation, error) + CreateBuildOperation(name string) *CreateBuildOperation + GetBuild(context.Context, *cloudbuildpb.GetBuildRequest, ...gax.CallOption) (*cloudbuildpb.Build, error) + ListBuilds(context.Context, *cloudbuildpb.ListBuildsRequest, ...gax.CallOption) *BuildIterator + CancelBuild(context.Context, *cloudbuildpb.CancelBuildRequest, ...gax.CallOption) (*cloudbuildpb.Build, error) + RetryBuild(context.Context, *cloudbuildpb.RetryBuildRequest, ...gax.CallOption) (*RetryBuildOperation, error) + RetryBuildOperation(name string) *RetryBuildOperation + CreateBuildTrigger(context.Context, *cloudbuildpb.CreateBuildTriggerRequest, ...gax.CallOption) (*cloudbuildpb.BuildTrigger, error) + GetBuildTrigger(context.Context, *cloudbuildpb.GetBuildTriggerRequest, ...gax.CallOption) (*cloudbuildpb.BuildTrigger, error) + ListBuildTriggers(context.Context, *cloudbuildpb.ListBuildTriggersRequest, ...gax.CallOption) *BuildTriggerIterator + DeleteBuildTrigger(context.Context, *cloudbuildpb.DeleteBuildTriggerRequest, ...gax.CallOption) error + UpdateBuildTrigger(context.Context, *cloudbuildpb.UpdateBuildTriggerRequest, ...gax.CallOption) (*cloudbuildpb.BuildTrigger, error) + RunBuildTrigger(context.Context, *cloudbuildpb.RunBuildTriggerRequest, ...gax.CallOption) (*RunBuildTriggerOperation, error) + RunBuildTriggerOperation(name string) *RunBuildTriggerOperation + ReceiveTriggerWebhook(context.Context, *cloudbuildpb.ReceiveTriggerWebhookRequest, ...gax.CallOption) (*cloudbuildpb.ReceiveTriggerWebhookResponse, error) + CreateWorkerPool(context.Context, *cloudbuildpb.CreateWorkerPoolRequest, ...gax.CallOption) (*cloudbuildpb.WorkerPool, error) + GetWorkerPool(context.Context, *cloudbuildpb.GetWorkerPoolRequest, ...gax.CallOption) (*cloudbuildpb.WorkerPool, error) + DeleteWorkerPool(context.Context, *cloudbuildpb.DeleteWorkerPoolRequest, ...gax.CallOption) error + UpdateWorkerPool(context.Context, *cloudbuildpb.UpdateWorkerPoolRequest, ...gax.CallOption) (*cloudbuildpb.WorkerPool, error) + ListWorkerPools(context.Context, *cloudbuildpb.ListWorkerPoolsRequest, ...gax.CallOption) (*cloudbuildpb.ListWorkerPoolsResponse, error) +} + // Client is a client for interacting with Cloud Build API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Creates and manages builds on Google Cloud Platform. +// +// The main concept used by this API is a Build, which describes the location +// of the source to build, how to build the source, and where to store the +// built artifacts, if any. +// +// A user can list previously-requested builds or get builds by their ID to +// determine the status of the build. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateBuild starts a build with the specified configuration. +// +// This method returns a long-running Operation, which includes the build +// ID. Pass the build ID to GetBuild to determine the build status (such as +// SUCCESS or FAILURE). +func (c *Client) CreateBuild(ctx context.Context, req *cloudbuildpb.CreateBuildRequest, opts ...gax.CallOption) (*CreateBuildOperation, error) { + return c.internalClient.CreateBuild(ctx, req, opts...) +} + +// CreateBuildOperation returns a new CreateBuildOperation from a given name. +// The name must be that of a previously created CreateBuildOperation, possibly from a different process. +func (c *Client) CreateBuildOperation(name string) *CreateBuildOperation { + return c.internalClient.CreateBuildOperation(name) +} + +// GetBuild returns information about a previously requested build. +// +// The Build that is returned includes its status (such as SUCCESS, +// FAILURE, or WORKING), and timing information. +func (c *Client) GetBuild(ctx context.Context, req *cloudbuildpb.GetBuildRequest, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { + return c.internalClient.GetBuild(ctx, req, opts...) +} + +// ListBuilds lists previously requested builds. +// +// Previously requested builds may still be in-progress, or may have finished +// successfully or unsuccessfully. +func (c *Client) ListBuilds(ctx context.Context, req *cloudbuildpb.ListBuildsRequest, opts ...gax.CallOption) *BuildIterator { + return c.internalClient.ListBuilds(ctx, req, opts...) +} + +// CancelBuild cancels a build in progress. +func (c *Client) CancelBuild(ctx context.Context, req *cloudbuildpb.CancelBuildRequest, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { + return c.internalClient.CancelBuild(ctx, req, opts...) +} + +// RetryBuild creates a new build based on the specified build. +// +// This method creates a new build using the original build request, which may +// or may not result in an identical build. +// +// For triggered builds: +// +// Triggered builds resolve to a precise revision; therefore a retry of a +// triggered build will result in a build that uses the same revision. +// +// For non-triggered builds that specify RepoSource: +// +// If the original build built from the tip of a branch, the retried build +// will build from the tip of that branch, which may not be the same revision +// as the original build. +// +// If the original build specified a commit sha or revision ID, the retried +// build will use the identical source. +// +// For builds that specify StorageSource: +// +// If the original build pulled source from Google Cloud Storage without +// specifying the generation of the object, the new build will use the current +// object, which may be different from the original build source. +// +// If the original build pulled source from Cloud Storage and specified the +// generation of the object, the new build will attempt to use the same +// object, which may or may not be available depending on the bucket’s +// lifecycle management settings. +func (c *Client) RetryBuild(ctx context.Context, req *cloudbuildpb.RetryBuildRequest, opts ...gax.CallOption) (*RetryBuildOperation, error) { + return c.internalClient.RetryBuild(ctx, req, opts...) +} + +// RetryBuildOperation returns a new RetryBuildOperation from a given name. +// The name must be that of a previously created RetryBuildOperation, possibly from a different process. +func (c *Client) RetryBuildOperation(name string) *RetryBuildOperation { + return c.internalClient.RetryBuildOperation(name) +} + +// CreateBuildTrigger creates a new BuildTrigger. +// +// This API is experimental. +func (c *Client) CreateBuildTrigger(ctx context.Context, req *cloudbuildpb.CreateBuildTriggerRequest, opts ...gax.CallOption) (*cloudbuildpb.BuildTrigger, error) { + return c.internalClient.CreateBuildTrigger(ctx, req, opts...) +} + +// GetBuildTrigger returns information about a BuildTrigger. +// +// This API is experimental. +func (c *Client) GetBuildTrigger(ctx context.Context, req *cloudbuildpb.GetBuildTriggerRequest, opts ...gax.CallOption) (*cloudbuildpb.BuildTrigger, error) { + return c.internalClient.GetBuildTrigger(ctx, req, opts...) +} + +// ListBuildTriggers lists existing BuildTriggers. +// +// This API is experimental. +func (c *Client) ListBuildTriggers(ctx context.Context, req *cloudbuildpb.ListBuildTriggersRequest, opts ...gax.CallOption) *BuildTriggerIterator { + return c.internalClient.ListBuildTriggers(ctx, req, opts...) +} + +// DeleteBuildTrigger deletes a BuildTrigger by its project ID and trigger ID. +// +// This API is experimental. +func (c *Client) DeleteBuildTrigger(ctx context.Context, req *cloudbuildpb.DeleteBuildTriggerRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteBuildTrigger(ctx, req, opts...) +} + +// UpdateBuildTrigger updates a BuildTrigger by its project ID and trigger ID. +// +// This API is experimental. +func (c *Client) UpdateBuildTrigger(ctx context.Context, req *cloudbuildpb.UpdateBuildTriggerRequest, opts ...gax.CallOption) (*cloudbuildpb.BuildTrigger, error) { + return c.internalClient.UpdateBuildTrigger(ctx, req, opts...) +} + +// RunBuildTrigger runs a BuildTrigger at a particular source revision. +func (c *Client) RunBuildTrigger(ctx context.Context, req *cloudbuildpb.RunBuildTriggerRequest, opts ...gax.CallOption) (*RunBuildTriggerOperation, error) { + return c.internalClient.RunBuildTrigger(ctx, req, opts...) +} + +// RunBuildTriggerOperation returns a new RunBuildTriggerOperation from a given name. +// The name must be that of a previously created RunBuildTriggerOperation, possibly from a different process. +func (c *Client) RunBuildTriggerOperation(name string) *RunBuildTriggerOperation { + return c.internalClient.RunBuildTriggerOperation(name) +} + +// ReceiveTriggerWebhook receiveTriggerWebhook [Experimental] is called when the API receives a +// webhook request targeted at a specific trigger. +func (c *Client) ReceiveTriggerWebhook(ctx context.Context, req *cloudbuildpb.ReceiveTriggerWebhookRequest, opts ...gax.CallOption) (*cloudbuildpb.ReceiveTriggerWebhookResponse, error) { + return c.internalClient.ReceiveTriggerWebhook(ctx, req, opts...) +} + +// CreateWorkerPool creates a WorkerPool to run the builds, and returns the new worker pool. +// +// This API is experimental. +func (c *Client) CreateWorkerPool(ctx context.Context, req *cloudbuildpb.CreateWorkerPoolRequest, opts ...gax.CallOption) (*cloudbuildpb.WorkerPool, error) { + return c.internalClient.CreateWorkerPool(ctx, req, opts...) +} + +// GetWorkerPool returns information about a WorkerPool. +// +// This API is experimental. +func (c *Client) GetWorkerPool(ctx context.Context, req *cloudbuildpb.GetWorkerPoolRequest, opts ...gax.CallOption) (*cloudbuildpb.WorkerPool, error) { + return c.internalClient.GetWorkerPool(ctx, req, opts...) +} + +// DeleteWorkerPool deletes a WorkerPool by its project ID and WorkerPool name. +// +// This API is experimental. +func (c *Client) DeleteWorkerPool(ctx context.Context, req *cloudbuildpb.DeleteWorkerPoolRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteWorkerPool(ctx, req, opts...) +} + +// UpdateWorkerPool update a WorkerPool. +// +// This API is experimental. +func (c *Client) UpdateWorkerPool(ctx context.Context, req *cloudbuildpb.UpdateWorkerPoolRequest, opts ...gax.CallOption) (*cloudbuildpb.WorkerPool, error) { + return c.internalClient.UpdateWorkerPool(ctx, req, opts...) +} + +// ListWorkerPools list project’s WorkerPools. +// +// This API is experimental. +func (c *Client) ListWorkerPools(ctx context.Context, req *cloudbuildpb.ListWorkerPoolsRequest, opts ...gax.CallOption) (*cloudbuildpb.ListWorkerPoolsResponse, error) { + return c.internalClient.ListWorkerPools(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud Build API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client cloudbuildpb.CloudBuildClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new cloud build client. +// NewClient creates a new cloud build client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Creates and manages builds on Google Cloud Platform. // @@ -208,8 +444,7 @@ type Client struct { // A user can list previously-requested builds or get builds by their ID to // determine the status of the build. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -227,16 +462,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: cloudbuildpb.NewCloudBuildClient(connPool), + client: cloudbuildpb.NewCloudBuildClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -246,37 +484,33 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateBuild starts a build with the specified configuration. -// -// This method returns a long-running Operation, which includes the build -// ID. Pass the build ID to GetBuild to determine the build status (such as -// SUCCESS or FAILURE). -func (c *Client) CreateBuild(ctx context.Context, req *cloudbuildpb.CreateBuildRequest, opts ...gax.CallOption) (*CreateBuildOperation, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateBuild(ctx context.Context, req *cloudbuildpb.CreateBuildRequest, opts ...gax.CallOption) (*CreateBuildOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -284,7 +518,7 @@ func (c *Client) CreateBuild(ctx context.Context, req *cloudbuildpb.CreateBuildR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateBuild[0:len(c.CallOptions.CreateBuild):len(c.CallOptions.CreateBuild)], opts...) + opts = append((*c.CallOptions).CreateBuild[0:len((*c.CallOptions).CreateBuild):len((*c.CallOptions).CreateBuild)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -295,15 +529,11 @@ func (c *Client) CreateBuild(ctx context.Context, req *cloudbuildpb.CreateBuildR return nil, err } return &CreateBuildOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetBuild returns information about a previously requested build. -// -// The Build that is returned includes its status (such as SUCCESS, -// FAILURE, or WORKING), and timing information. -func (c *Client) GetBuild(ctx context.Context, req *cloudbuildpb.GetBuildRequest, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { +func (c *gRPCClient) GetBuild(ctx context.Context, req *cloudbuildpb.GetBuildRequest, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -311,7 +541,7 @@ func (c *Client) GetBuild(ctx context.Context, req *cloudbuildpb.GetBuildRequest } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "id", url.QueryEscape(req.GetId()), "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetBuild[0:len(c.CallOptions.GetBuild):len(c.CallOptions.GetBuild)], opts...) + opts = append((*c.CallOptions).GetBuild[0:len((*c.CallOptions).GetBuild):len((*c.CallOptions).GetBuild)], opts...) var resp *cloudbuildpb.Build err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -324,14 +554,10 @@ func (c *Client) GetBuild(ctx context.Context, req *cloudbuildpb.GetBuildRequest return resp, nil } -// ListBuilds lists previously requested builds. -// -// Previously requested builds may still be in-progress, or may have finished -// successfully or unsuccessfully. -func (c *Client) ListBuilds(ctx context.Context, req *cloudbuildpb.ListBuildsRequest, opts ...gax.CallOption) *BuildIterator { +func (c *gRPCClient) ListBuilds(ctx context.Context, req *cloudbuildpb.ListBuildsRequest, opts ...gax.CallOption) *BuildIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListBuilds[0:len(c.CallOptions.ListBuilds):len(c.CallOptions.ListBuilds)], opts...) + opts = append((*c.CallOptions).ListBuilds[0:len((*c.CallOptions).ListBuilds):len((*c.CallOptions).ListBuilds)], opts...) it := &BuildIterator{} req = proto.Clone(req).(*cloudbuildpb.ListBuildsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cloudbuildpb.Build, string, error) { @@ -368,8 +594,7 @@ func (c *Client) ListBuilds(ctx context.Context, req *cloudbuildpb.ListBuildsReq return it } -// CancelBuild cancels a build in progress. -func (c *Client) CancelBuild(ctx context.Context, req *cloudbuildpb.CancelBuildRequest, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { +func (c *gRPCClient) CancelBuild(ctx context.Context, req *cloudbuildpb.CancelBuildRequest, opts ...gax.CallOption) (*cloudbuildpb.Build, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -377,7 +602,7 @@ func (c *Client) CancelBuild(ctx context.Context, req *cloudbuildpb.CancelBuildR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "id", url.QueryEscape(req.GetId()), "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CancelBuild[0:len(c.CallOptions.CancelBuild):len(c.CallOptions.CancelBuild)], opts...) + opts = append((*c.CallOptions).CancelBuild[0:len((*c.CallOptions).CancelBuild):len((*c.CallOptions).CancelBuild)], opts...) var resp *cloudbuildpb.Build err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -390,36 +615,7 @@ func (c *Client) CancelBuild(ctx context.Context, req *cloudbuildpb.CancelBuildR return resp, nil } -// RetryBuild creates a new build based on the specified build. -// -// This method creates a new build using the original build request, which may -// or may not result in an identical build. -// -// For triggered builds: -// -// Triggered builds resolve to a precise revision; therefore a retry of a -// triggered build will result in a build that uses the same revision. -// -// For non-triggered builds that specify RepoSource: -// -// If the original build built from the tip of a branch, the retried build -// will build from the tip of that branch, which may not be the same revision -// as the original build. -// -// If the original build specified a commit sha or revision ID, the retried -// build will use the identical source. -// -// For builds that specify StorageSource: -// -// If the original build pulled source from Google Cloud Storage without -// specifying the generation of the object, the new build will use the current -// object, which may be different from the original build source. -// -// If the original build pulled source from Cloud Storage and specified the -// generation of the object, the new build will attempt to use the same -// object, which may or may not be available depending on the bucket’s -// lifecycle management settings. -func (c *Client) RetryBuild(ctx context.Context, req *cloudbuildpb.RetryBuildRequest, opts ...gax.CallOption) (*RetryBuildOperation, error) { +func (c *gRPCClient) RetryBuild(ctx context.Context, req *cloudbuildpb.RetryBuildRequest, opts ...gax.CallOption) (*RetryBuildOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -427,7 +623,7 @@ func (c *Client) RetryBuild(ctx context.Context, req *cloudbuildpb.RetryBuildReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "id", url.QueryEscape(req.GetId()), "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RetryBuild[0:len(c.CallOptions.RetryBuild):len(c.CallOptions.RetryBuild)], opts...) + opts = append((*c.CallOptions).RetryBuild[0:len((*c.CallOptions).RetryBuild):len((*c.CallOptions).RetryBuild)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -438,14 +634,11 @@ func (c *Client) RetryBuild(ctx context.Context, req *cloudbuildpb.RetryBuildReq return nil, err } return &RetryBuildOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// CreateBuildTrigger creates a new BuildTrigger. -// -// This API is experimental. -func (c *Client) CreateBuildTrigger(ctx context.Context, req *cloudbuildpb.CreateBuildTriggerRequest, opts ...gax.CallOption) (*cloudbuildpb.BuildTrigger, error) { +func (c *gRPCClient) CreateBuildTrigger(ctx context.Context, req *cloudbuildpb.CreateBuildTriggerRequest, opts ...gax.CallOption) (*cloudbuildpb.BuildTrigger, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -453,7 +646,7 @@ func (c *Client) CreateBuildTrigger(ctx context.Context, req *cloudbuildpb.Creat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateBuildTrigger[0:len(c.CallOptions.CreateBuildTrigger):len(c.CallOptions.CreateBuildTrigger)], opts...) + opts = append((*c.CallOptions).CreateBuildTrigger[0:len((*c.CallOptions).CreateBuildTrigger):len((*c.CallOptions).CreateBuildTrigger)], opts...) var resp *cloudbuildpb.BuildTrigger err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -466,10 +659,7 @@ func (c *Client) CreateBuildTrigger(ctx context.Context, req *cloudbuildpb.Creat return resp, nil } -// GetBuildTrigger returns information about a BuildTrigger. -// -// This API is experimental. -func (c *Client) GetBuildTrigger(ctx context.Context, req *cloudbuildpb.GetBuildTriggerRequest, opts ...gax.CallOption) (*cloudbuildpb.BuildTrigger, error) { +func (c *gRPCClient) GetBuildTrigger(ctx context.Context, req *cloudbuildpb.GetBuildTriggerRequest, opts ...gax.CallOption) (*cloudbuildpb.BuildTrigger, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -477,7 +667,7 @@ func (c *Client) GetBuildTrigger(ctx context.Context, req *cloudbuildpb.GetBuild } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "trigger_id", url.QueryEscape(req.GetTriggerId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetBuildTrigger[0:len(c.CallOptions.GetBuildTrigger):len(c.CallOptions.GetBuildTrigger)], opts...) + opts = append((*c.CallOptions).GetBuildTrigger[0:len((*c.CallOptions).GetBuildTrigger):len((*c.CallOptions).GetBuildTrigger)], opts...) var resp *cloudbuildpb.BuildTrigger err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -490,13 +680,10 @@ func (c *Client) GetBuildTrigger(ctx context.Context, req *cloudbuildpb.GetBuild return resp, nil } -// ListBuildTriggers lists existing BuildTriggers. -// -// This API is experimental. -func (c *Client) ListBuildTriggers(ctx context.Context, req *cloudbuildpb.ListBuildTriggersRequest, opts ...gax.CallOption) *BuildTriggerIterator { +func (c *gRPCClient) ListBuildTriggers(ctx context.Context, req *cloudbuildpb.ListBuildTriggersRequest, opts ...gax.CallOption) *BuildTriggerIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListBuildTriggers[0:len(c.CallOptions.ListBuildTriggers):len(c.CallOptions.ListBuildTriggers)], opts...) + opts = append((*c.CallOptions).ListBuildTriggers[0:len((*c.CallOptions).ListBuildTriggers):len((*c.CallOptions).ListBuildTriggers)], opts...) it := &BuildTriggerIterator{} req = proto.Clone(req).(*cloudbuildpb.ListBuildTriggersRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cloudbuildpb.BuildTrigger, string, error) { @@ -533,10 +720,7 @@ func (c *Client) ListBuildTriggers(ctx context.Context, req *cloudbuildpb.ListBu return it } -// DeleteBuildTrigger deletes a BuildTrigger by its project ID and trigger ID. -// -// This API is experimental. -func (c *Client) DeleteBuildTrigger(ctx context.Context, req *cloudbuildpb.DeleteBuildTriggerRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteBuildTrigger(ctx context.Context, req *cloudbuildpb.DeleteBuildTriggerRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -544,7 +728,7 @@ func (c *Client) DeleteBuildTrigger(ctx context.Context, req *cloudbuildpb.Delet } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "trigger_id", url.QueryEscape(req.GetTriggerId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteBuildTrigger[0:len(c.CallOptions.DeleteBuildTrigger):len(c.CallOptions.DeleteBuildTrigger)], opts...) + opts = append((*c.CallOptions).DeleteBuildTrigger[0:len((*c.CallOptions).DeleteBuildTrigger):len((*c.CallOptions).DeleteBuildTrigger)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteBuildTrigger(ctx, req, settings.GRPC...) @@ -553,10 +737,7 @@ func (c *Client) DeleteBuildTrigger(ctx context.Context, req *cloudbuildpb.Delet return err } -// UpdateBuildTrigger updates a BuildTrigger by its project ID and trigger ID. -// -// This API is experimental. -func (c *Client) UpdateBuildTrigger(ctx context.Context, req *cloudbuildpb.UpdateBuildTriggerRequest, opts ...gax.CallOption) (*cloudbuildpb.BuildTrigger, error) { +func (c *gRPCClient) UpdateBuildTrigger(ctx context.Context, req *cloudbuildpb.UpdateBuildTriggerRequest, opts ...gax.CallOption) (*cloudbuildpb.BuildTrigger, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -564,7 +745,7 @@ func (c *Client) UpdateBuildTrigger(ctx context.Context, req *cloudbuildpb.Updat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "trigger_id", url.QueryEscape(req.GetTriggerId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateBuildTrigger[0:len(c.CallOptions.UpdateBuildTrigger):len(c.CallOptions.UpdateBuildTrigger)], opts...) + opts = append((*c.CallOptions).UpdateBuildTrigger[0:len((*c.CallOptions).UpdateBuildTrigger):len((*c.CallOptions).UpdateBuildTrigger)], opts...) var resp *cloudbuildpb.BuildTrigger err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -577,8 +758,7 @@ func (c *Client) UpdateBuildTrigger(ctx context.Context, req *cloudbuildpb.Updat return resp, nil } -// RunBuildTrigger runs a BuildTrigger at a particular source revision. -func (c *Client) RunBuildTrigger(ctx context.Context, req *cloudbuildpb.RunBuildTriggerRequest, opts ...gax.CallOption) (*RunBuildTriggerOperation, error) { +func (c *gRPCClient) RunBuildTrigger(ctx context.Context, req *cloudbuildpb.RunBuildTriggerRequest, opts ...gax.CallOption) (*RunBuildTriggerOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -586,7 +766,7 @@ func (c *Client) RunBuildTrigger(ctx context.Context, req *cloudbuildpb.RunBuild } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "trigger_id", url.QueryEscape(req.GetTriggerId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RunBuildTrigger[0:len(c.CallOptions.RunBuildTrigger):len(c.CallOptions.RunBuildTrigger)], opts...) + opts = append((*c.CallOptions).RunBuildTrigger[0:len((*c.CallOptions).RunBuildTrigger):len((*c.CallOptions).RunBuildTrigger)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -597,16 +777,14 @@ func (c *Client) RunBuildTrigger(ctx context.Context, req *cloudbuildpb.RunBuild return nil, err } return &RunBuildTriggerOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ReceiveTriggerWebhook receiveTriggerWebhook [Experimental] is called when the API receives a -// webhook request targeted at a specific trigger. -func (c *Client) ReceiveTriggerWebhook(ctx context.Context, req *cloudbuildpb.ReceiveTriggerWebhookRequest, opts ...gax.CallOption) (*cloudbuildpb.ReceiveTriggerWebhookResponse, error) { +func (c *gRPCClient) ReceiveTriggerWebhook(ctx context.Context, req *cloudbuildpb.ReceiveTriggerWebhookRequest, opts ...gax.CallOption) (*cloudbuildpb.ReceiveTriggerWebhookResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "trigger", url.QueryEscape(req.GetTrigger()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ReceiveTriggerWebhook[0:len(c.CallOptions.ReceiveTriggerWebhook):len(c.CallOptions.ReceiveTriggerWebhook)], opts...) + opts = append((*c.CallOptions).ReceiveTriggerWebhook[0:len((*c.CallOptions).ReceiveTriggerWebhook):len((*c.CallOptions).ReceiveTriggerWebhook)], opts...) var resp *cloudbuildpb.ReceiveTriggerWebhookResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -619,17 +797,14 @@ func (c *Client) ReceiveTriggerWebhook(ctx context.Context, req *cloudbuildpb.Re return resp, nil } -// CreateWorkerPool creates a WorkerPool to run the builds, and returns the new worker pool. -// -// This API is experimental. -func (c *Client) CreateWorkerPool(ctx context.Context, req *cloudbuildpb.CreateWorkerPoolRequest, opts ...gax.CallOption) (*cloudbuildpb.WorkerPool, error) { +func (c *gRPCClient) CreateWorkerPool(ctx context.Context, req *cloudbuildpb.CreateWorkerPoolRequest, opts ...gax.CallOption) (*cloudbuildpb.WorkerPool, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.CreateWorkerPool[0:len(c.CallOptions.CreateWorkerPool):len(c.CallOptions.CreateWorkerPool)], opts...) + opts = append((*c.CallOptions).CreateWorkerPool[0:len((*c.CallOptions).CreateWorkerPool):len((*c.CallOptions).CreateWorkerPool)], opts...) var resp *cloudbuildpb.WorkerPool err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -642,17 +817,14 @@ func (c *Client) CreateWorkerPool(ctx context.Context, req *cloudbuildpb.CreateW return resp, nil } -// GetWorkerPool returns information about a WorkerPool. -// -// This API is experimental. -func (c *Client) GetWorkerPool(ctx context.Context, req *cloudbuildpb.GetWorkerPoolRequest, opts ...gax.CallOption) (*cloudbuildpb.WorkerPool, error) { +func (c *gRPCClient) GetWorkerPool(ctx context.Context, req *cloudbuildpb.GetWorkerPoolRequest, opts ...gax.CallOption) (*cloudbuildpb.WorkerPool, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.GetWorkerPool[0:len(c.CallOptions.GetWorkerPool):len(c.CallOptions.GetWorkerPool)], opts...) + opts = append((*c.CallOptions).GetWorkerPool[0:len((*c.CallOptions).GetWorkerPool):len((*c.CallOptions).GetWorkerPool)], opts...) var resp *cloudbuildpb.WorkerPool err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -665,17 +837,14 @@ func (c *Client) GetWorkerPool(ctx context.Context, req *cloudbuildpb.GetWorkerP return resp, nil } -// DeleteWorkerPool deletes a WorkerPool by its project ID and WorkerPool name. -// -// This API is experimental. -func (c *Client) DeleteWorkerPool(ctx context.Context, req *cloudbuildpb.DeleteWorkerPoolRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteWorkerPool(ctx context.Context, req *cloudbuildpb.DeleteWorkerPoolRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.DeleteWorkerPool[0:len(c.CallOptions.DeleteWorkerPool):len(c.CallOptions.DeleteWorkerPool)], opts...) + opts = append((*c.CallOptions).DeleteWorkerPool[0:len((*c.CallOptions).DeleteWorkerPool):len((*c.CallOptions).DeleteWorkerPool)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteWorkerPool(ctx, req, settings.GRPC...) @@ -684,17 +853,14 @@ func (c *Client) DeleteWorkerPool(ctx context.Context, req *cloudbuildpb.DeleteW return err } -// UpdateWorkerPool update a WorkerPool. -// -// This API is experimental. -func (c *Client) UpdateWorkerPool(ctx context.Context, req *cloudbuildpb.UpdateWorkerPoolRequest, opts ...gax.CallOption) (*cloudbuildpb.WorkerPool, error) { +func (c *gRPCClient) UpdateWorkerPool(ctx context.Context, req *cloudbuildpb.UpdateWorkerPoolRequest, opts ...gax.CallOption) (*cloudbuildpb.WorkerPool, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.UpdateWorkerPool[0:len(c.CallOptions.UpdateWorkerPool):len(c.CallOptions.UpdateWorkerPool)], opts...) + opts = append((*c.CallOptions).UpdateWorkerPool[0:len((*c.CallOptions).UpdateWorkerPool):len((*c.CallOptions).UpdateWorkerPool)], opts...) var resp *cloudbuildpb.WorkerPool err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -707,17 +873,14 @@ func (c *Client) UpdateWorkerPool(ctx context.Context, req *cloudbuildpb.UpdateW return resp, nil } -// ListWorkerPools list project’s WorkerPools. -// -// This API is experimental. -func (c *Client) ListWorkerPools(ctx context.Context, req *cloudbuildpb.ListWorkerPoolsRequest, opts ...gax.CallOption) (*cloudbuildpb.ListWorkerPoolsResponse, error) { +func (c *gRPCClient) ListWorkerPools(ctx context.Context, req *cloudbuildpb.ListWorkerPoolsRequest, opts ...gax.CallOption) (*cloudbuildpb.ListWorkerPoolsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListWorkerPools[0:len(c.CallOptions.ListWorkerPools):len(c.CallOptions.ListWorkerPools)], opts...) + opts = append((*c.CallOptions).ListWorkerPools[0:len((*c.CallOptions).ListWorkerPools):len((*c.CallOptions).ListWorkerPools)], opts...) var resp *cloudbuildpb.ListWorkerPoolsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -737,9 +900,9 @@ type CreateBuildOperation struct { // CreateBuildOperation returns a new CreateBuildOperation from a given name. // The name must be that of a previously created CreateBuildOperation, possibly from a different process. -func (c *Client) CreateBuildOperation(name string) *CreateBuildOperation { +func (c *gRPCClient) CreateBuildOperation(name string) *CreateBuildOperation { return &CreateBuildOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -806,9 +969,9 @@ type RetryBuildOperation struct { // RetryBuildOperation returns a new RetryBuildOperation from a given name. // The name must be that of a previously created RetryBuildOperation, possibly from a different process. -func (c *Client) RetryBuildOperation(name string) *RetryBuildOperation { +func (c *gRPCClient) RetryBuildOperation(name string) *RetryBuildOperation { return &RetryBuildOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -875,9 +1038,9 @@ type RunBuildTriggerOperation struct { // RunBuildTriggerOperation returns a new RunBuildTriggerOperation from a given name. // The name must be that of a previously created RunBuildTriggerOperation, possibly from a different process. -func (c *Client) RunBuildTriggerOperation(name string) *RunBuildTriggerOperation { +func (c *gRPCClient) RunBuildTriggerOperation(name string) *RunBuildTriggerOperation { return &RunBuildTriggerOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/cloudbuild/apiv1/v2/cloud_build_client_example_test.go b/cloudbuild/apiv1/v2/cloud_build_client_example_test.go index a880aeb7e115..28506ce04c00 100644 --- a/cloudbuild/apiv1/v2/cloud_build_client_example_test.go +++ b/cloudbuild/apiv1/v2/cloud_build_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateBuild() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.CreateBuildRequest{ // TODO: Fill request struct fields. @@ -60,13 +61,12 @@ func ExampleClient_CreateBuild() { } func ExampleClient_GetBuild() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.GetBuildRequest{ // TODO: Fill request struct fields. @@ -80,14 +80,12 @@ func ExampleClient_GetBuild() { } func ExampleClient_ListBuilds() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.ListBuildsRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleClient_ListBuilds() { } func ExampleClient_CancelBuild() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.CancelBuildRequest{ // TODO: Fill request struct fields. @@ -127,13 +124,12 @@ func ExampleClient_CancelBuild() { } func ExampleClient_RetryBuild() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.RetryBuildRequest{ // TODO: Fill request struct fields. @@ -152,13 +148,12 @@ func ExampleClient_RetryBuild() { } func ExampleClient_CreateBuildTrigger() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.CreateBuildTriggerRequest{ // TODO: Fill request struct fields. @@ -172,13 +167,12 @@ func ExampleClient_CreateBuildTrigger() { } func ExampleClient_GetBuildTrigger() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.GetBuildTriggerRequest{ // TODO: Fill request struct fields. @@ -192,14 +186,12 @@ func ExampleClient_GetBuildTrigger() { } func ExampleClient_ListBuildTriggers() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.ListBuildTriggersRequest{ // TODO: Fill request struct fields. @@ -224,6 +216,7 @@ func ExampleClient_DeleteBuildTrigger() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.DeleteBuildTriggerRequest{ // TODO: Fill request struct fields. @@ -235,13 +228,12 @@ func ExampleClient_DeleteBuildTrigger() { } func ExampleClient_UpdateBuildTrigger() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.UpdateBuildTriggerRequest{ // TODO: Fill request struct fields. @@ -255,13 +247,12 @@ func ExampleClient_UpdateBuildTrigger() { } func ExampleClient_RunBuildTrigger() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.RunBuildTriggerRequest{ // TODO: Fill request struct fields. @@ -280,13 +271,12 @@ func ExampleClient_RunBuildTrigger() { } func ExampleClient_ReceiveTriggerWebhook() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.ReceiveTriggerWebhookRequest{ // TODO: Fill request struct fields. @@ -300,13 +290,12 @@ func ExampleClient_ReceiveTriggerWebhook() { } func ExampleClient_CreateWorkerPool() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.CreateWorkerPoolRequest{ // TODO: Fill request struct fields. @@ -320,13 +309,12 @@ func ExampleClient_CreateWorkerPool() { } func ExampleClient_GetWorkerPool() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.GetWorkerPoolRequest{ // TODO: Fill request struct fields. @@ -345,6 +333,7 @@ func ExampleClient_DeleteWorkerPool() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.DeleteWorkerPoolRequest{ // TODO: Fill request struct fields. @@ -356,13 +345,12 @@ func ExampleClient_DeleteWorkerPool() { } func ExampleClient_UpdateWorkerPool() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.UpdateWorkerPoolRequest{ // TODO: Fill request struct fields. @@ -376,13 +364,12 @@ func ExampleClient_UpdateWorkerPool() { } func ExampleClient_ListWorkerPools() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.ListWorkerPoolsRequest{ // TODO: Fill request struct fields. diff --git a/cloudbuild/apiv1/v2/doc.go b/cloudbuild/apiv1/v2/doc.go index 5f1118c91710..5a163b8573e8 100644 --- a/cloudbuild/apiv1/v2/doc.go +++ b/cloudbuild/apiv1/v2/doc.go @@ -28,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package cloudbuild // import "cloud.google.com/go/cloudbuild/apiv1/v2" import ( @@ -48,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/clouddms/apiv1/data_migration_client.go b/clouddms/apiv1/data_migration_client.go index b1938f0edb2d..82b2e7643d62 100644 --- a/clouddms/apiv1/data_migration_client.go +++ b/clouddms/apiv1/data_migration_client.go @@ -60,7 +60,7 @@ type DataMigrationCallOptions struct { DeleteConnectionProfile []gax.CallOption } -func defaultDataMigrationClientOptions() []option.ClientOption { +func defaultDataMigrationGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("datamigration.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("datamigration.mtls.googleapis.com:443"), @@ -94,37 +94,277 @@ func defaultDataMigrationCallOptions() *DataMigrationCallOptions { } } +// internalDataMigrationClient is an interface that defines the methods availaible from Database Migration API. +type internalDataMigrationClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListMigrationJobs(context.Context, *clouddmspb.ListMigrationJobsRequest, ...gax.CallOption) *MigrationJobIterator + GetMigrationJob(context.Context, *clouddmspb.GetMigrationJobRequest, ...gax.CallOption) (*clouddmspb.MigrationJob, error) + CreateMigrationJob(context.Context, *clouddmspb.CreateMigrationJobRequest, ...gax.CallOption) (*CreateMigrationJobOperation, error) + CreateMigrationJobOperation(name string) *CreateMigrationJobOperation + UpdateMigrationJob(context.Context, *clouddmspb.UpdateMigrationJobRequest, ...gax.CallOption) (*UpdateMigrationJobOperation, error) + UpdateMigrationJobOperation(name string) *UpdateMigrationJobOperation + DeleteMigrationJob(context.Context, *clouddmspb.DeleteMigrationJobRequest, ...gax.CallOption) (*DeleteMigrationJobOperation, error) + DeleteMigrationJobOperation(name string) *DeleteMigrationJobOperation + StartMigrationJob(context.Context, *clouddmspb.StartMigrationJobRequest, ...gax.CallOption) (*StartMigrationJobOperation, error) + StartMigrationJobOperation(name string) *StartMigrationJobOperation + StopMigrationJob(context.Context, *clouddmspb.StopMigrationJobRequest, ...gax.CallOption) (*StopMigrationJobOperation, error) + StopMigrationJobOperation(name string) *StopMigrationJobOperation + ResumeMigrationJob(context.Context, *clouddmspb.ResumeMigrationJobRequest, ...gax.CallOption) (*ResumeMigrationJobOperation, error) + ResumeMigrationJobOperation(name string) *ResumeMigrationJobOperation + PromoteMigrationJob(context.Context, *clouddmspb.PromoteMigrationJobRequest, ...gax.CallOption) (*PromoteMigrationJobOperation, error) + PromoteMigrationJobOperation(name string) *PromoteMigrationJobOperation + VerifyMigrationJob(context.Context, *clouddmspb.VerifyMigrationJobRequest, ...gax.CallOption) (*VerifyMigrationJobOperation, error) + VerifyMigrationJobOperation(name string) *VerifyMigrationJobOperation + RestartMigrationJob(context.Context, *clouddmspb.RestartMigrationJobRequest, ...gax.CallOption) (*RestartMigrationJobOperation, error) + RestartMigrationJobOperation(name string) *RestartMigrationJobOperation + GenerateSshScript(context.Context, *clouddmspb.GenerateSshScriptRequest, ...gax.CallOption) (*clouddmspb.SshScript, error) + ListConnectionProfiles(context.Context, *clouddmspb.ListConnectionProfilesRequest, ...gax.CallOption) *ConnectionProfileIterator + GetConnectionProfile(context.Context, *clouddmspb.GetConnectionProfileRequest, ...gax.CallOption) (*clouddmspb.ConnectionProfile, error) + CreateConnectionProfile(context.Context, *clouddmspb.CreateConnectionProfileRequest, ...gax.CallOption) (*CreateConnectionProfileOperation, error) + CreateConnectionProfileOperation(name string) *CreateConnectionProfileOperation + UpdateConnectionProfile(context.Context, *clouddmspb.UpdateConnectionProfileRequest, ...gax.CallOption) (*UpdateConnectionProfileOperation, error) + UpdateConnectionProfileOperation(name string) *UpdateConnectionProfileOperation + DeleteConnectionProfile(context.Context, *clouddmspb.DeleteConnectionProfileRequest, ...gax.CallOption) (*DeleteConnectionProfileOperation, error) + DeleteConnectionProfileOperation(name string) *DeleteConnectionProfileOperation +} + // DataMigrationClient is a client for interacting with Database Migration API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Database Migration service type DataMigrationClient struct { + // The internal transport-dependent client. + internalClient internalDataMigrationClient + + // The call options for this service. + CallOptions *DataMigrationCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *DataMigrationClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *DataMigrationClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *DataMigrationClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListMigrationJobs lists migration jobs in a given project and location. +func (c *DataMigrationClient) ListMigrationJobs(ctx context.Context, req *clouddmspb.ListMigrationJobsRequest, opts ...gax.CallOption) *MigrationJobIterator { + return c.internalClient.ListMigrationJobs(ctx, req, opts...) +} + +// GetMigrationJob gets details of a single migration job. +func (c *DataMigrationClient) GetMigrationJob(ctx context.Context, req *clouddmspb.GetMigrationJobRequest, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { + return c.internalClient.GetMigrationJob(ctx, req, opts...) +} + +// CreateMigrationJob creates a new migration job in a given project and location. +func (c *DataMigrationClient) CreateMigrationJob(ctx context.Context, req *clouddmspb.CreateMigrationJobRequest, opts ...gax.CallOption) (*CreateMigrationJobOperation, error) { + return c.internalClient.CreateMigrationJob(ctx, req, opts...) +} + +// CreateMigrationJobOperation returns a new CreateMigrationJobOperation from a given name. +// The name must be that of a previously created CreateMigrationJobOperation, possibly from a different process. +func (c *DataMigrationClient) CreateMigrationJobOperation(name string) *CreateMigrationJobOperation { + return c.internalClient.CreateMigrationJobOperation(name) +} + +// UpdateMigrationJob updates the parameters of a single migration job. +func (c *DataMigrationClient) UpdateMigrationJob(ctx context.Context, req *clouddmspb.UpdateMigrationJobRequest, opts ...gax.CallOption) (*UpdateMigrationJobOperation, error) { + return c.internalClient.UpdateMigrationJob(ctx, req, opts...) +} + +// UpdateMigrationJobOperation returns a new UpdateMigrationJobOperation from a given name. +// The name must be that of a previously created UpdateMigrationJobOperation, possibly from a different process. +func (c *DataMigrationClient) UpdateMigrationJobOperation(name string) *UpdateMigrationJobOperation { + return c.internalClient.UpdateMigrationJobOperation(name) +} + +// DeleteMigrationJob deletes a single migration job. +func (c *DataMigrationClient) DeleteMigrationJob(ctx context.Context, req *clouddmspb.DeleteMigrationJobRequest, opts ...gax.CallOption) (*DeleteMigrationJobOperation, error) { + return c.internalClient.DeleteMigrationJob(ctx, req, opts...) +} + +// DeleteMigrationJobOperation returns a new DeleteMigrationJobOperation from a given name. +// The name must be that of a previously created DeleteMigrationJobOperation, possibly from a different process. +func (c *DataMigrationClient) DeleteMigrationJobOperation(name string) *DeleteMigrationJobOperation { + return c.internalClient.DeleteMigrationJobOperation(name) +} + +// StartMigrationJob start an already created migration job. +func (c *DataMigrationClient) StartMigrationJob(ctx context.Context, req *clouddmspb.StartMigrationJobRequest, opts ...gax.CallOption) (*StartMigrationJobOperation, error) { + return c.internalClient.StartMigrationJob(ctx, req, opts...) +} + +// StartMigrationJobOperation returns a new StartMigrationJobOperation from a given name. +// The name must be that of a previously created StartMigrationJobOperation, possibly from a different process. +func (c *DataMigrationClient) StartMigrationJobOperation(name string) *StartMigrationJobOperation { + return c.internalClient.StartMigrationJobOperation(name) +} + +// StopMigrationJob stops a running migration job. +func (c *DataMigrationClient) StopMigrationJob(ctx context.Context, req *clouddmspb.StopMigrationJobRequest, opts ...gax.CallOption) (*StopMigrationJobOperation, error) { + return c.internalClient.StopMigrationJob(ctx, req, opts...) +} + +// StopMigrationJobOperation returns a new StopMigrationJobOperation from a given name. +// The name must be that of a previously created StopMigrationJobOperation, possibly from a different process. +func (c *DataMigrationClient) StopMigrationJobOperation(name string) *StopMigrationJobOperation { + return c.internalClient.StopMigrationJobOperation(name) +} + +// ResumeMigrationJob resume a migration job that is currently stopped and is resumable (was +// stopped during CDC phase). +func (c *DataMigrationClient) ResumeMigrationJob(ctx context.Context, req *clouddmspb.ResumeMigrationJobRequest, opts ...gax.CallOption) (*ResumeMigrationJobOperation, error) { + return c.internalClient.ResumeMigrationJob(ctx, req, opts...) +} + +// ResumeMigrationJobOperation returns a new ResumeMigrationJobOperation from a given name. +// The name must be that of a previously created ResumeMigrationJobOperation, possibly from a different process. +func (c *DataMigrationClient) ResumeMigrationJobOperation(name string) *ResumeMigrationJobOperation { + return c.internalClient.ResumeMigrationJobOperation(name) +} + +// PromoteMigrationJob promote a migration job, stopping replication to the destination and +// promoting the destination to be a standalone database. +func (c *DataMigrationClient) PromoteMigrationJob(ctx context.Context, req *clouddmspb.PromoteMigrationJobRequest, opts ...gax.CallOption) (*PromoteMigrationJobOperation, error) { + return c.internalClient.PromoteMigrationJob(ctx, req, opts...) +} + +// PromoteMigrationJobOperation returns a new PromoteMigrationJobOperation from a given name. +// The name must be that of a previously created PromoteMigrationJobOperation, possibly from a different process. +func (c *DataMigrationClient) PromoteMigrationJobOperation(name string) *PromoteMigrationJobOperation { + return c.internalClient.PromoteMigrationJobOperation(name) +} + +// VerifyMigrationJob verify a migration job, making sure the destination can reach the source +// and that all configuration and prerequisites are met. +func (c *DataMigrationClient) VerifyMigrationJob(ctx context.Context, req *clouddmspb.VerifyMigrationJobRequest, opts ...gax.CallOption) (*VerifyMigrationJobOperation, error) { + return c.internalClient.VerifyMigrationJob(ctx, req, opts...) +} + +// VerifyMigrationJobOperation returns a new VerifyMigrationJobOperation from a given name. +// The name must be that of a previously created VerifyMigrationJobOperation, possibly from a different process. +func (c *DataMigrationClient) VerifyMigrationJobOperation(name string) *VerifyMigrationJobOperation { + return c.internalClient.VerifyMigrationJobOperation(name) +} + +// RestartMigrationJob restart a stopped or failed migration job, resetting the destination +// instance to its original state and starting the migration process from +// scratch. +func (c *DataMigrationClient) RestartMigrationJob(ctx context.Context, req *clouddmspb.RestartMigrationJobRequest, opts ...gax.CallOption) (*RestartMigrationJobOperation, error) { + return c.internalClient.RestartMigrationJob(ctx, req, opts...) +} + +// RestartMigrationJobOperation returns a new RestartMigrationJobOperation from a given name. +// The name must be that of a previously created RestartMigrationJobOperation, possibly from a different process. +func (c *DataMigrationClient) RestartMigrationJobOperation(name string) *RestartMigrationJobOperation { + return c.internalClient.RestartMigrationJobOperation(name) +} + +// GenerateSshScript generate a SSH configuration script to configure the reverse SSH +// connectivity. +func (c *DataMigrationClient) GenerateSshScript(ctx context.Context, req *clouddmspb.GenerateSshScriptRequest, opts ...gax.CallOption) (*clouddmspb.SshScript, error) { + return c.internalClient.GenerateSshScript(ctx, req, opts...) +} + +// ListConnectionProfiles retrieve a list of all connection profiles in a given project and location. +func (c *DataMigrationClient) ListConnectionProfiles(ctx context.Context, req *clouddmspb.ListConnectionProfilesRequest, opts ...gax.CallOption) *ConnectionProfileIterator { + return c.internalClient.ListConnectionProfiles(ctx, req, opts...) +} + +// GetConnectionProfile gets details of a single connection profile. +func (c *DataMigrationClient) GetConnectionProfile(ctx context.Context, req *clouddmspb.GetConnectionProfileRequest, opts ...gax.CallOption) (*clouddmspb.ConnectionProfile, error) { + return c.internalClient.GetConnectionProfile(ctx, req, opts...) +} + +// CreateConnectionProfile creates a new connection profile in a given project and location. +func (c *DataMigrationClient) CreateConnectionProfile(ctx context.Context, req *clouddmspb.CreateConnectionProfileRequest, opts ...gax.CallOption) (*CreateConnectionProfileOperation, error) { + return c.internalClient.CreateConnectionProfile(ctx, req, opts...) +} + +// CreateConnectionProfileOperation returns a new CreateConnectionProfileOperation from a given name. +// The name must be that of a previously created CreateConnectionProfileOperation, possibly from a different process. +func (c *DataMigrationClient) CreateConnectionProfileOperation(name string) *CreateConnectionProfileOperation { + return c.internalClient.CreateConnectionProfileOperation(name) +} + +// UpdateConnectionProfile update the configuration of a single connection profile. +func (c *DataMigrationClient) UpdateConnectionProfile(ctx context.Context, req *clouddmspb.UpdateConnectionProfileRequest, opts ...gax.CallOption) (*UpdateConnectionProfileOperation, error) { + return c.internalClient.UpdateConnectionProfile(ctx, req, opts...) +} + +// UpdateConnectionProfileOperation returns a new UpdateConnectionProfileOperation from a given name. +// The name must be that of a previously created UpdateConnectionProfileOperation, possibly from a different process. +func (c *DataMigrationClient) UpdateConnectionProfileOperation(name string) *UpdateConnectionProfileOperation { + return c.internalClient.UpdateConnectionProfileOperation(name) +} + +// DeleteConnectionProfile deletes a single Database Migration Service connection profile. +// A connection profile can only be deleted if it is not in use by any +// active migration jobs. +func (c *DataMigrationClient) DeleteConnectionProfile(ctx context.Context, req *clouddmspb.DeleteConnectionProfileRequest, opts ...gax.CallOption) (*DeleteConnectionProfileOperation, error) { + return c.internalClient.DeleteConnectionProfile(ctx, req, opts...) +} + +// DeleteConnectionProfileOperation returns a new DeleteConnectionProfileOperation from a given name. +// The name must be that of a previously created DeleteConnectionProfileOperation, possibly from a different process. +func (c *DataMigrationClient) DeleteConnectionProfileOperation(name string) *DeleteConnectionProfileOperation { + return c.internalClient.DeleteConnectionProfileOperation(name) +} + +// dataMigrationGRPCClient is a client for interacting with Database Migration API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type dataMigrationGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing DataMigrationClient + CallOptions **DataMigrationCallOptions + // The gRPC API client. dataMigrationClient clouddmspb.DataMigrationServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *DataMigrationCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewDataMigrationClient creates a new data migration service client. +// NewDataMigrationClient creates a new data migration service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Database Migration service func NewDataMigrationClient(ctx context.Context, opts ...option.ClientOption) (*DataMigrationClient, error) { - clientOpts := defaultDataMigrationClientOptions() - + clientOpts := defaultDataMigrationGRPCClientOptions() if newDataMigrationClientHook != nil { hookOpts, err := newDataMigrationClientHook(ctx, clientHookParams{}) if err != nil { @@ -142,16 +382,19 @@ func NewDataMigrationClient(ctx context.Context, opts ...option.ClientOption) (* if err != nil { return nil, err } - c := &DataMigrationClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultDataMigrationCallOptions(), + client := DataMigrationClient{CallOptions: defaultDataMigrationCallOptions()} + c := &dataMigrationGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, dataMigrationClient: clouddmspb.NewDataMigrationServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -161,36 +404,36 @@ func NewDataMigrationClient(ctx context.Context, opts ...option.ClientOption) (* // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *DataMigrationClient) Connection() *grpc.ClientConn { +func (c *dataMigrationGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *DataMigrationClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *DataMigrationClient) setGoogleClientInfo(keyval ...string) { +func (c *dataMigrationGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListMigrationJobs lists migration jobs in a given project and location. -func (c *DataMigrationClient) ListMigrationJobs(ctx context.Context, req *clouddmspb.ListMigrationJobsRequest, opts ...gax.CallOption) *MigrationJobIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *dataMigrationGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *dataMigrationGRPCClient) ListMigrationJobs(ctx context.Context, req *clouddmspb.ListMigrationJobsRequest, opts ...gax.CallOption) *MigrationJobIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListMigrationJobs[0:len(c.CallOptions.ListMigrationJobs):len(c.CallOptions.ListMigrationJobs)], opts...) + opts = append((*c.CallOptions).ListMigrationJobs[0:len((*c.CallOptions).ListMigrationJobs):len((*c.CallOptions).ListMigrationJobs)], opts...) it := &MigrationJobIterator{} req = proto.Clone(req).(*clouddmspb.ListMigrationJobsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*clouddmspb.MigrationJob, string, error) { @@ -227,8 +470,7 @@ func (c *DataMigrationClient) ListMigrationJobs(ctx context.Context, req *cloudd return it } -// GetMigrationJob gets details of a single migration job. -func (c *DataMigrationClient) GetMigrationJob(ctx context.Context, req *clouddmspb.GetMigrationJobRequest, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { +func (c *dataMigrationGRPCClient) GetMigrationJob(ctx context.Context, req *clouddmspb.GetMigrationJobRequest, opts ...gax.CallOption) (*clouddmspb.MigrationJob, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -236,7 +478,7 @@ func (c *DataMigrationClient) GetMigrationJob(ctx context.Context, req *clouddms } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetMigrationJob[0:len(c.CallOptions.GetMigrationJob):len(c.CallOptions.GetMigrationJob)], opts...) + opts = append((*c.CallOptions).GetMigrationJob[0:len((*c.CallOptions).GetMigrationJob):len((*c.CallOptions).GetMigrationJob)], opts...) var resp *clouddmspb.MigrationJob err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -249,8 +491,7 @@ func (c *DataMigrationClient) GetMigrationJob(ctx context.Context, req *clouddms return resp, nil } -// CreateMigrationJob creates a new migration job in a given project and location. -func (c *DataMigrationClient) CreateMigrationJob(ctx context.Context, req *clouddmspb.CreateMigrationJobRequest, opts ...gax.CallOption) (*CreateMigrationJobOperation, error) { +func (c *dataMigrationGRPCClient) CreateMigrationJob(ctx context.Context, req *clouddmspb.CreateMigrationJobRequest, opts ...gax.CallOption) (*CreateMigrationJobOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -258,7 +499,7 @@ func (c *DataMigrationClient) CreateMigrationJob(ctx context.Context, req *cloud } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateMigrationJob[0:len(c.CallOptions.CreateMigrationJob):len(c.CallOptions.CreateMigrationJob)], opts...) + opts = append((*c.CallOptions).CreateMigrationJob[0:len((*c.CallOptions).CreateMigrationJob):len((*c.CallOptions).CreateMigrationJob)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -269,12 +510,11 @@ func (c *DataMigrationClient) CreateMigrationJob(ctx context.Context, req *cloud return nil, err } return &CreateMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateMigrationJob updates the parameters of a single migration job. -func (c *DataMigrationClient) UpdateMigrationJob(ctx context.Context, req *clouddmspb.UpdateMigrationJobRequest, opts ...gax.CallOption) (*UpdateMigrationJobOperation, error) { +func (c *dataMigrationGRPCClient) UpdateMigrationJob(ctx context.Context, req *clouddmspb.UpdateMigrationJobRequest, opts ...gax.CallOption) (*UpdateMigrationJobOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -282,7 +522,7 @@ func (c *DataMigrationClient) UpdateMigrationJob(ctx context.Context, req *cloud } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "migration_job.name", url.QueryEscape(req.GetMigrationJob().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateMigrationJob[0:len(c.CallOptions.UpdateMigrationJob):len(c.CallOptions.UpdateMigrationJob)], opts...) + opts = append((*c.CallOptions).UpdateMigrationJob[0:len((*c.CallOptions).UpdateMigrationJob):len((*c.CallOptions).UpdateMigrationJob)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -293,12 +533,11 @@ func (c *DataMigrationClient) UpdateMigrationJob(ctx context.Context, req *cloud return nil, err } return &UpdateMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteMigrationJob deletes a single migration job. -func (c *DataMigrationClient) DeleteMigrationJob(ctx context.Context, req *clouddmspb.DeleteMigrationJobRequest, opts ...gax.CallOption) (*DeleteMigrationJobOperation, error) { +func (c *dataMigrationGRPCClient) DeleteMigrationJob(ctx context.Context, req *clouddmspb.DeleteMigrationJobRequest, opts ...gax.CallOption) (*DeleteMigrationJobOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -306,7 +545,7 @@ func (c *DataMigrationClient) DeleteMigrationJob(ctx context.Context, req *cloud } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteMigrationJob[0:len(c.CallOptions.DeleteMigrationJob):len(c.CallOptions.DeleteMigrationJob)], opts...) + opts = append((*c.CallOptions).DeleteMigrationJob[0:len((*c.CallOptions).DeleteMigrationJob):len((*c.CallOptions).DeleteMigrationJob)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -317,12 +556,11 @@ func (c *DataMigrationClient) DeleteMigrationJob(ctx context.Context, req *cloud return nil, err } return &DeleteMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// StartMigrationJob start an already created migration job. -func (c *DataMigrationClient) StartMigrationJob(ctx context.Context, req *clouddmspb.StartMigrationJobRequest, opts ...gax.CallOption) (*StartMigrationJobOperation, error) { +func (c *dataMigrationGRPCClient) StartMigrationJob(ctx context.Context, req *clouddmspb.StartMigrationJobRequest, opts ...gax.CallOption) (*StartMigrationJobOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -330,7 +568,7 @@ func (c *DataMigrationClient) StartMigrationJob(ctx context.Context, req *cloudd } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.StartMigrationJob[0:len(c.CallOptions.StartMigrationJob):len(c.CallOptions.StartMigrationJob)], opts...) + opts = append((*c.CallOptions).StartMigrationJob[0:len((*c.CallOptions).StartMigrationJob):len((*c.CallOptions).StartMigrationJob)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -341,12 +579,11 @@ func (c *DataMigrationClient) StartMigrationJob(ctx context.Context, req *cloudd return nil, err } return &StartMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// StopMigrationJob stops a running migration job. -func (c *DataMigrationClient) StopMigrationJob(ctx context.Context, req *clouddmspb.StopMigrationJobRequest, opts ...gax.CallOption) (*StopMigrationJobOperation, error) { +func (c *dataMigrationGRPCClient) StopMigrationJob(ctx context.Context, req *clouddmspb.StopMigrationJobRequest, opts ...gax.CallOption) (*StopMigrationJobOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -354,7 +591,7 @@ func (c *DataMigrationClient) StopMigrationJob(ctx context.Context, req *clouddm } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.StopMigrationJob[0:len(c.CallOptions.StopMigrationJob):len(c.CallOptions.StopMigrationJob)], opts...) + opts = append((*c.CallOptions).StopMigrationJob[0:len((*c.CallOptions).StopMigrationJob):len((*c.CallOptions).StopMigrationJob)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -365,13 +602,11 @@ func (c *DataMigrationClient) StopMigrationJob(ctx context.Context, req *clouddm return nil, err } return &StopMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ResumeMigrationJob resume a migration job that is currently stopped and is resumable (was -// stopped during CDC phase). -func (c *DataMigrationClient) ResumeMigrationJob(ctx context.Context, req *clouddmspb.ResumeMigrationJobRequest, opts ...gax.CallOption) (*ResumeMigrationJobOperation, error) { +func (c *dataMigrationGRPCClient) ResumeMigrationJob(ctx context.Context, req *clouddmspb.ResumeMigrationJobRequest, opts ...gax.CallOption) (*ResumeMigrationJobOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -379,7 +614,7 @@ func (c *DataMigrationClient) ResumeMigrationJob(ctx context.Context, req *cloud } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ResumeMigrationJob[0:len(c.CallOptions.ResumeMigrationJob):len(c.CallOptions.ResumeMigrationJob)], opts...) + opts = append((*c.CallOptions).ResumeMigrationJob[0:len((*c.CallOptions).ResumeMigrationJob):len((*c.CallOptions).ResumeMigrationJob)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -390,13 +625,11 @@ func (c *DataMigrationClient) ResumeMigrationJob(ctx context.Context, req *cloud return nil, err } return &ResumeMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// PromoteMigrationJob promote a migration job, stopping replication to the destination and -// promoting the destination to be a standalone database. -func (c *DataMigrationClient) PromoteMigrationJob(ctx context.Context, req *clouddmspb.PromoteMigrationJobRequest, opts ...gax.CallOption) (*PromoteMigrationJobOperation, error) { +func (c *dataMigrationGRPCClient) PromoteMigrationJob(ctx context.Context, req *clouddmspb.PromoteMigrationJobRequest, opts ...gax.CallOption) (*PromoteMigrationJobOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -404,7 +637,7 @@ func (c *DataMigrationClient) PromoteMigrationJob(ctx context.Context, req *clou } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PromoteMigrationJob[0:len(c.CallOptions.PromoteMigrationJob):len(c.CallOptions.PromoteMigrationJob)], opts...) + opts = append((*c.CallOptions).PromoteMigrationJob[0:len((*c.CallOptions).PromoteMigrationJob):len((*c.CallOptions).PromoteMigrationJob)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -415,13 +648,11 @@ func (c *DataMigrationClient) PromoteMigrationJob(ctx context.Context, req *clou return nil, err } return &PromoteMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// VerifyMigrationJob verify a migration job, making sure the destination can reach the source -// and that all configuration and prerequisites are met. -func (c *DataMigrationClient) VerifyMigrationJob(ctx context.Context, req *clouddmspb.VerifyMigrationJobRequest, opts ...gax.CallOption) (*VerifyMigrationJobOperation, error) { +func (c *dataMigrationGRPCClient) VerifyMigrationJob(ctx context.Context, req *clouddmspb.VerifyMigrationJobRequest, opts ...gax.CallOption) (*VerifyMigrationJobOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -429,7 +660,7 @@ func (c *DataMigrationClient) VerifyMigrationJob(ctx context.Context, req *cloud } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.VerifyMigrationJob[0:len(c.CallOptions.VerifyMigrationJob):len(c.CallOptions.VerifyMigrationJob)], opts...) + opts = append((*c.CallOptions).VerifyMigrationJob[0:len((*c.CallOptions).VerifyMigrationJob):len((*c.CallOptions).VerifyMigrationJob)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -440,14 +671,11 @@ func (c *DataMigrationClient) VerifyMigrationJob(ctx context.Context, req *cloud return nil, err } return &VerifyMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// RestartMigrationJob restart a stopped or failed migration job, resetting the destination -// instance to its original state and starting the migration process from -// scratch. -func (c *DataMigrationClient) RestartMigrationJob(ctx context.Context, req *clouddmspb.RestartMigrationJobRequest, opts ...gax.CallOption) (*RestartMigrationJobOperation, error) { +func (c *dataMigrationGRPCClient) RestartMigrationJob(ctx context.Context, req *clouddmspb.RestartMigrationJobRequest, opts ...gax.CallOption) (*RestartMigrationJobOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -455,7 +683,7 @@ func (c *DataMigrationClient) RestartMigrationJob(ctx context.Context, req *clou } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RestartMigrationJob[0:len(c.CallOptions.RestartMigrationJob):len(c.CallOptions.RestartMigrationJob)], opts...) + opts = append((*c.CallOptions).RestartMigrationJob[0:len((*c.CallOptions).RestartMigrationJob):len((*c.CallOptions).RestartMigrationJob)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -466,13 +694,11 @@ func (c *DataMigrationClient) RestartMigrationJob(ctx context.Context, req *clou return nil, err } return &RestartMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GenerateSshScript generate a SSH configuration script to configure the reverse SSH -// connectivity. -func (c *DataMigrationClient) GenerateSshScript(ctx context.Context, req *clouddmspb.GenerateSshScriptRequest, opts ...gax.CallOption) (*clouddmspb.SshScript, error) { +func (c *dataMigrationGRPCClient) GenerateSshScript(ctx context.Context, req *clouddmspb.GenerateSshScriptRequest, opts ...gax.CallOption) (*clouddmspb.SshScript, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -480,7 +706,7 @@ func (c *DataMigrationClient) GenerateSshScript(ctx context.Context, req *cloudd } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "migration_job", url.QueryEscape(req.GetMigrationJob()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GenerateSshScript[0:len(c.CallOptions.GenerateSshScript):len(c.CallOptions.GenerateSshScript)], opts...) + opts = append((*c.CallOptions).GenerateSshScript[0:len((*c.CallOptions).GenerateSshScript):len((*c.CallOptions).GenerateSshScript)], opts...) var resp *clouddmspb.SshScript err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -493,11 +719,10 @@ func (c *DataMigrationClient) GenerateSshScript(ctx context.Context, req *cloudd return resp, nil } -// ListConnectionProfiles retrieve a list of all connection profiles in a given project and location. -func (c *DataMigrationClient) ListConnectionProfiles(ctx context.Context, req *clouddmspb.ListConnectionProfilesRequest, opts ...gax.CallOption) *ConnectionProfileIterator { +func (c *dataMigrationGRPCClient) ListConnectionProfiles(ctx context.Context, req *clouddmspb.ListConnectionProfilesRequest, opts ...gax.CallOption) *ConnectionProfileIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListConnectionProfiles[0:len(c.CallOptions.ListConnectionProfiles):len(c.CallOptions.ListConnectionProfiles)], opts...) + opts = append((*c.CallOptions).ListConnectionProfiles[0:len((*c.CallOptions).ListConnectionProfiles):len((*c.CallOptions).ListConnectionProfiles)], opts...) it := &ConnectionProfileIterator{} req = proto.Clone(req).(*clouddmspb.ListConnectionProfilesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*clouddmspb.ConnectionProfile, string, error) { @@ -534,8 +759,7 @@ func (c *DataMigrationClient) ListConnectionProfiles(ctx context.Context, req *c return it } -// GetConnectionProfile gets details of a single connection profile. -func (c *DataMigrationClient) GetConnectionProfile(ctx context.Context, req *clouddmspb.GetConnectionProfileRequest, opts ...gax.CallOption) (*clouddmspb.ConnectionProfile, error) { +func (c *dataMigrationGRPCClient) GetConnectionProfile(ctx context.Context, req *clouddmspb.GetConnectionProfileRequest, opts ...gax.CallOption) (*clouddmspb.ConnectionProfile, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -543,7 +767,7 @@ func (c *DataMigrationClient) GetConnectionProfile(ctx context.Context, req *clo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetConnectionProfile[0:len(c.CallOptions.GetConnectionProfile):len(c.CallOptions.GetConnectionProfile)], opts...) + opts = append((*c.CallOptions).GetConnectionProfile[0:len((*c.CallOptions).GetConnectionProfile):len((*c.CallOptions).GetConnectionProfile)], opts...) var resp *clouddmspb.ConnectionProfile err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -556,8 +780,7 @@ func (c *DataMigrationClient) GetConnectionProfile(ctx context.Context, req *clo return resp, nil } -// CreateConnectionProfile creates a new connection profile in a given project and location. -func (c *DataMigrationClient) CreateConnectionProfile(ctx context.Context, req *clouddmspb.CreateConnectionProfileRequest, opts ...gax.CallOption) (*CreateConnectionProfileOperation, error) { +func (c *dataMigrationGRPCClient) CreateConnectionProfile(ctx context.Context, req *clouddmspb.CreateConnectionProfileRequest, opts ...gax.CallOption) (*CreateConnectionProfileOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -565,7 +788,7 @@ func (c *DataMigrationClient) CreateConnectionProfile(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateConnectionProfile[0:len(c.CallOptions.CreateConnectionProfile):len(c.CallOptions.CreateConnectionProfile)], opts...) + opts = append((*c.CallOptions).CreateConnectionProfile[0:len((*c.CallOptions).CreateConnectionProfile):len((*c.CallOptions).CreateConnectionProfile)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -576,12 +799,11 @@ func (c *DataMigrationClient) CreateConnectionProfile(ctx context.Context, req * return nil, err } return &CreateConnectionProfileOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateConnectionProfile update the configuration of a single connection profile. -func (c *DataMigrationClient) UpdateConnectionProfile(ctx context.Context, req *clouddmspb.UpdateConnectionProfileRequest, opts ...gax.CallOption) (*UpdateConnectionProfileOperation, error) { +func (c *dataMigrationGRPCClient) UpdateConnectionProfile(ctx context.Context, req *clouddmspb.UpdateConnectionProfileRequest, opts ...gax.CallOption) (*UpdateConnectionProfileOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -589,7 +811,7 @@ func (c *DataMigrationClient) UpdateConnectionProfile(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "connection_profile.name", url.QueryEscape(req.GetConnectionProfile().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateConnectionProfile[0:len(c.CallOptions.UpdateConnectionProfile):len(c.CallOptions.UpdateConnectionProfile)], opts...) + opts = append((*c.CallOptions).UpdateConnectionProfile[0:len((*c.CallOptions).UpdateConnectionProfile):len((*c.CallOptions).UpdateConnectionProfile)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -600,14 +822,11 @@ func (c *DataMigrationClient) UpdateConnectionProfile(ctx context.Context, req * return nil, err } return &UpdateConnectionProfileOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteConnectionProfile deletes a single Database Migration Service connection profile. -// A connection profile can only be deleted if it is not in use by any -// active migration jobs. -func (c *DataMigrationClient) DeleteConnectionProfile(ctx context.Context, req *clouddmspb.DeleteConnectionProfileRequest, opts ...gax.CallOption) (*DeleteConnectionProfileOperation, error) { +func (c *dataMigrationGRPCClient) DeleteConnectionProfile(ctx context.Context, req *clouddmspb.DeleteConnectionProfileRequest, opts ...gax.CallOption) (*DeleteConnectionProfileOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -615,7 +834,7 @@ func (c *DataMigrationClient) DeleteConnectionProfile(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteConnectionProfile[0:len(c.CallOptions.DeleteConnectionProfile):len(c.CallOptions.DeleteConnectionProfile)], opts...) + opts = append((*c.CallOptions).DeleteConnectionProfile[0:len((*c.CallOptions).DeleteConnectionProfile):len((*c.CallOptions).DeleteConnectionProfile)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -626,7 +845,7 @@ func (c *DataMigrationClient) DeleteConnectionProfile(ctx context.Context, req * return nil, err } return &DeleteConnectionProfileOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -637,9 +856,9 @@ type CreateConnectionProfileOperation struct { // CreateConnectionProfileOperation returns a new CreateConnectionProfileOperation from a given name. // The name must be that of a previously created CreateConnectionProfileOperation, possibly from a different process. -func (c *DataMigrationClient) CreateConnectionProfileOperation(name string) *CreateConnectionProfileOperation { +func (c *dataMigrationGRPCClient) CreateConnectionProfileOperation(name string) *CreateConnectionProfileOperation { return &CreateConnectionProfileOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -706,9 +925,9 @@ type CreateMigrationJobOperation struct { // CreateMigrationJobOperation returns a new CreateMigrationJobOperation from a given name. // The name must be that of a previously created CreateMigrationJobOperation, possibly from a different process. -func (c *DataMigrationClient) CreateMigrationJobOperation(name string) *CreateMigrationJobOperation { +func (c *dataMigrationGRPCClient) CreateMigrationJobOperation(name string) *CreateMigrationJobOperation { return &CreateMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -775,9 +994,9 @@ type DeleteConnectionProfileOperation struct { // DeleteConnectionProfileOperation returns a new DeleteConnectionProfileOperation from a given name. // The name must be that of a previously created DeleteConnectionProfileOperation, possibly from a different process. -func (c *DataMigrationClient) DeleteConnectionProfileOperation(name string) *DeleteConnectionProfileOperation { +func (c *dataMigrationGRPCClient) DeleteConnectionProfileOperation(name string) *DeleteConnectionProfileOperation { return &DeleteConnectionProfileOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -833,9 +1052,9 @@ type DeleteMigrationJobOperation struct { // DeleteMigrationJobOperation returns a new DeleteMigrationJobOperation from a given name. // The name must be that of a previously created DeleteMigrationJobOperation, possibly from a different process. -func (c *DataMigrationClient) DeleteMigrationJobOperation(name string) *DeleteMigrationJobOperation { +func (c *dataMigrationGRPCClient) DeleteMigrationJobOperation(name string) *DeleteMigrationJobOperation { return &DeleteMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -891,9 +1110,9 @@ type PromoteMigrationJobOperation struct { // PromoteMigrationJobOperation returns a new PromoteMigrationJobOperation from a given name. // The name must be that of a previously created PromoteMigrationJobOperation, possibly from a different process. -func (c *DataMigrationClient) PromoteMigrationJobOperation(name string) *PromoteMigrationJobOperation { +func (c *dataMigrationGRPCClient) PromoteMigrationJobOperation(name string) *PromoteMigrationJobOperation { return &PromoteMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -960,9 +1179,9 @@ type RestartMigrationJobOperation struct { // RestartMigrationJobOperation returns a new RestartMigrationJobOperation from a given name. // The name must be that of a previously created RestartMigrationJobOperation, possibly from a different process. -func (c *DataMigrationClient) RestartMigrationJobOperation(name string) *RestartMigrationJobOperation { +func (c *dataMigrationGRPCClient) RestartMigrationJobOperation(name string) *RestartMigrationJobOperation { return &RestartMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1029,9 +1248,9 @@ type ResumeMigrationJobOperation struct { // ResumeMigrationJobOperation returns a new ResumeMigrationJobOperation from a given name. // The name must be that of a previously created ResumeMigrationJobOperation, possibly from a different process. -func (c *DataMigrationClient) ResumeMigrationJobOperation(name string) *ResumeMigrationJobOperation { +func (c *dataMigrationGRPCClient) ResumeMigrationJobOperation(name string) *ResumeMigrationJobOperation { return &ResumeMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1098,9 +1317,9 @@ type StartMigrationJobOperation struct { // StartMigrationJobOperation returns a new StartMigrationJobOperation from a given name. // The name must be that of a previously created StartMigrationJobOperation, possibly from a different process. -func (c *DataMigrationClient) StartMigrationJobOperation(name string) *StartMigrationJobOperation { +func (c *dataMigrationGRPCClient) StartMigrationJobOperation(name string) *StartMigrationJobOperation { return &StartMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1167,9 +1386,9 @@ type StopMigrationJobOperation struct { // StopMigrationJobOperation returns a new StopMigrationJobOperation from a given name. // The name must be that of a previously created StopMigrationJobOperation, possibly from a different process. -func (c *DataMigrationClient) StopMigrationJobOperation(name string) *StopMigrationJobOperation { +func (c *dataMigrationGRPCClient) StopMigrationJobOperation(name string) *StopMigrationJobOperation { return &StopMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1236,9 +1455,9 @@ type UpdateConnectionProfileOperation struct { // UpdateConnectionProfileOperation returns a new UpdateConnectionProfileOperation from a given name. // The name must be that of a previously created UpdateConnectionProfileOperation, possibly from a different process. -func (c *DataMigrationClient) UpdateConnectionProfileOperation(name string) *UpdateConnectionProfileOperation { +func (c *dataMigrationGRPCClient) UpdateConnectionProfileOperation(name string) *UpdateConnectionProfileOperation { return &UpdateConnectionProfileOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1305,9 +1524,9 @@ type UpdateMigrationJobOperation struct { // UpdateMigrationJobOperation returns a new UpdateMigrationJobOperation from a given name. // The name must be that of a previously created UpdateMigrationJobOperation, possibly from a different process. -func (c *DataMigrationClient) UpdateMigrationJobOperation(name string) *UpdateMigrationJobOperation { +func (c *dataMigrationGRPCClient) UpdateMigrationJobOperation(name string) *UpdateMigrationJobOperation { return &UpdateMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1374,9 +1593,9 @@ type VerifyMigrationJobOperation struct { // VerifyMigrationJobOperation returns a new VerifyMigrationJobOperation from a given name. // The name must be that of a previously created VerifyMigrationJobOperation, possibly from a different process. -func (c *DataMigrationClient) VerifyMigrationJobOperation(name string) *VerifyMigrationJobOperation { +func (c *dataMigrationGRPCClient) VerifyMigrationJobOperation(name string) *VerifyMigrationJobOperation { return &VerifyMigrationJobOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/clouddms/apiv1/data_migration_client_example_test.go b/clouddms/apiv1/data_migration_client_example_test.go index 32e321fcdaa2..4c29ab8be368 100644 --- a/clouddms/apiv1/data_migration_client_example_test.go +++ b/clouddms/apiv1/data_migration_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewDataMigrationClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleDataMigrationClient_ListMigrationJobs() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.ListMigrationJobsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleDataMigrationClient_ListMigrationJobs() { } func ExampleDataMigrationClient_GetMigrationJob() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.GetMigrationJobRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleDataMigrationClient_GetMigrationJob() { } func ExampleDataMigrationClient_CreateMigrationJob() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.CreateMigrationJobRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleDataMigrationClient_CreateMigrationJob() { } func ExampleDataMigrationClient_UpdateMigrationJob() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.UpdateMigrationJobRequest{ // TODO: Fill request struct fields. @@ -132,13 +129,12 @@ func ExampleDataMigrationClient_UpdateMigrationJob() { } func ExampleDataMigrationClient_DeleteMigrationJob() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.DeleteMigrationJobRequest{ // TODO: Fill request struct fields. @@ -155,13 +151,12 @@ func ExampleDataMigrationClient_DeleteMigrationJob() { } func ExampleDataMigrationClient_StartMigrationJob() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.StartMigrationJobRequest{ // TODO: Fill request struct fields. @@ -180,13 +175,12 @@ func ExampleDataMigrationClient_StartMigrationJob() { } func ExampleDataMigrationClient_StopMigrationJob() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.StopMigrationJobRequest{ // TODO: Fill request struct fields. @@ -205,13 +199,12 @@ func ExampleDataMigrationClient_StopMigrationJob() { } func ExampleDataMigrationClient_ResumeMigrationJob() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.ResumeMigrationJobRequest{ // TODO: Fill request struct fields. @@ -230,13 +223,12 @@ func ExampleDataMigrationClient_ResumeMigrationJob() { } func ExampleDataMigrationClient_PromoteMigrationJob() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.PromoteMigrationJobRequest{ // TODO: Fill request struct fields. @@ -255,13 +247,12 @@ func ExampleDataMigrationClient_PromoteMigrationJob() { } func ExampleDataMigrationClient_VerifyMigrationJob() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.VerifyMigrationJobRequest{ // TODO: Fill request struct fields. @@ -280,13 +271,12 @@ func ExampleDataMigrationClient_VerifyMigrationJob() { } func ExampleDataMigrationClient_RestartMigrationJob() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.RestartMigrationJobRequest{ // TODO: Fill request struct fields. @@ -305,13 +295,12 @@ func ExampleDataMigrationClient_RestartMigrationJob() { } func ExampleDataMigrationClient_GenerateSshScript() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.GenerateSshScriptRequest{ // TODO: Fill request struct fields. @@ -325,14 +314,12 @@ func ExampleDataMigrationClient_GenerateSshScript() { } func ExampleDataMigrationClient_ListConnectionProfiles() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.ListConnectionProfilesRequest{ // TODO: Fill request struct fields. @@ -352,13 +339,12 @@ func ExampleDataMigrationClient_ListConnectionProfiles() { } func ExampleDataMigrationClient_GetConnectionProfile() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.GetConnectionProfileRequest{ // TODO: Fill request struct fields. @@ -372,13 +358,12 @@ func ExampleDataMigrationClient_GetConnectionProfile() { } func ExampleDataMigrationClient_CreateConnectionProfile() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.CreateConnectionProfileRequest{ // TODO: Fill request struct fields. @@ -397,13 +382,12 @@ func ExampleDataMigrationClient_CreateConnectionProfile() { } func ExampleDataMigrationClient_UpdateConnectionProfile() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.UpdateConnectionProfileRequest{ // TODO: Fill request struct fields. @@ -422,13 +406,12 @@ func ExampleDataMigrationClient_UpdateConnectionProfile() { } func ExampleDataMigrationClient_DeleteConnectionProfile() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.DeleteConnectionProfileRequest{ // TODO: Fill request struct fields. diff --git a/clouddms/apiv1/doc.go b/clouddms/apiv1/doc.go index 2936d6be3d79..9bbca908b133 100644 --- a/clouddms/apiv1/doc.go +++ b/clouddms/apiv1/doc.go @@ -20,6 +20,8 @@ // Manage Cloud Database Migration Service resources on Google Cloud // Platform. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package clouddms // import "cloud.google.com/go/clouddms/apiv1" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/cloudtasks/apiv2/cloud_tasks_client.go b/cloudtasks/apiv2/cloud_tasks_client.go index 002424528084..d2334e3a580d 100644 --- a/cloudtasks/apiv2/cloud_tasks_client.go +++ b/cloudtasks/apiv2/cloud_tasks_client.go @@ -58,7 +58,7 @@ type CallOptions struct { RunTask []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudtasks.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudtasks.mtls.googleapis.com:443"), @@ -179,33 +179,296 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Tasks API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListQueues(context.Context, *taskspb.ListQueuesRequest, ...gax.CallOption) *QueueIterator + GetQueue(context.Context, *taskspb.GetQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + CreateQueue(context.Context, *taskspb.CreateQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + UpdateQueue(context.Context, *taskspb.UpdateQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + DeleteQueue(context.Context, *taskspb.DeleteQueueRequest, ...gax.CallOption) error + PurgeQueue(context.Context, *taskspb.PurgeQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + PauseQueue(context.Context, *taskspb.PauseQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + ResumeQueue(context.Context, *taskspb.ResumeQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) + ListTasks(context.Context, *taskspb.ListTasksRequest, ...gax.CallOption) *TaskIterator + GetTask(context.Context, *taskspb.GetTaskRequest, ...gax.CallOption) (*taskspb.Task, error) + CreateTask(context.Context, *taskspb.CreateTaskRequest, ...gax.CallOption) (*taskspb.Task, error) + DeleteTask(context.Context, *taskspb.DeleteTaskRequest, ...gax.CallOption) error + RunTask(context.Context, *taskspb.RunTaskRequest, ...gax.CallOption) (*taskspb.Task, error) +} + // Client is a client for interacting with Cloud Tasks API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Cloud Tasks allows developers to manage the execution of background +// work in their applications. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListQueues lists queues. +// +// Queues are returned in lexicographical order. +func (c *Client) ListQueues(ctx context.Context, req *taskspb.ListQueuesRequest, opts ...gax.CallOption) *QueueIterator { + return c.internalClient.ListQueues(ctx, req, opts...) +} + +// GetQueue gets a queue. +func (c *Client) GetQueue(ctx context.Context, req *taskspb.GetQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.GetQueue(ctx, req, opts...) +} + +// CreateQueue creates a queue. +// +// Queues created with this method allow tasks to live for a maximum of 31 +// days. After a task is 31 days old, the task will be deleted regardless of whether +// it was dispatched or not. +// +// WARNING: Using this method may have unintended side effects if you are +// using an App Engine queue.yaml or queue.xml file to manage your queues. +// Read +// Overview of Queue Management and +// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using +// this method. +func (c *Client) CreateQueue(ctx context.Context, req *taskspb.CreateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.CreateQueue(ctx, req, opts...) +} + +// UpdateQueue updates a queue. +// +// This method creates the queue if it does not exist and updates +// the queue if it does exist. +// +// Queues created with this method allow tasks to live for a maximum of 31 +// days. After a task is 31 days old, the task will be deleted regardless of whether +// it was dispatched or not. +// +// WARNING: Using this method may have unintended side effects if you are +// using an App Engine queue.yaml or queue.xml file to manage your queues. +// Read +// Overview of Queue Management and +// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using +// this method. +func (c *Client) UpdateQueue(ctx context.Context, req *taskspb.UpdateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.UpdateQueue(ctx, req, opts...) +} + +// DeleteQueue deletes a queue. +// +// This command will delete the queue even if it has tasks in it. +// +// Note: If you delete a queue, a queue with the same name can’t be created +// for 7 days. +// +// WARNING: Using this method may have unintended side effects if you are +// using an App Engine queue.yaml or queue.xml file to manage your queues. +// Read +// Overview of Queue Management and +// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using +// this method. +func (c *Client) DeleteQueue(ctx context.Context, req *taskspb.DeleteQueueRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteQueue(ctx, req, opts...) +} + +// PurgeQueue purges a queue by deleting all of its tasks. +// +// All tasks created before this method is called are permanently deleted. +// +// Purge operations can take up to one minute to take effect. Tasks +// might be dispatched before the purge takes effect. A purge is irreversible. +func (c *Client) PurgeQueue(ctx context.Context, req *taskspb.PurgeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.PurgeQueue(ctx, req, opts...) +} + +// PauseQueue pauses the queue. +// +// If a queue is paused then the system will stop dispatching tasks +// until the queue is resumed via +// ResumeQueue. Tasks can still be added +// when the queue is paused. A queue is paused if its +// state is PAUSED. +func (c *Client) PauseQueue(ctx context.Context, req *taskspb.PauseQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.PauseQueue(ctx, req, opts...) +} + +// ResumeQueue resume a queue. +// +// This method resumes a queue after it has been +// PAUSED or +// DISABLED. The state of a queue is stored +// in the queue’s state; after calling this method it +// will be set to RUNNING. +// +// WARNING: Resuming many high-QPS queues at the same time can +// lead to target overloading. If you are resuming high-QPS +// queues, follow the 500/50/5 pattern described in +// Managing Cloud Tasks Scaling +// Risks (at https://cloud.google.com/tasks/docs/manage-cloud-task-scaling). +func (c *Client) ResumeQueue(ctx context.Context, req *taskspb.ResumeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.ResumeQueue(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy for a Queue. +// Returns an empty policy if the resource exists and does not have a policy +// set. +// +// Authorization requires the following +// Google IAM (at https://cloud.google.com/iam) permission on the specified +// resource parent: +// +// cloudtasks.queues.getIamPolicy +func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// SetIamPolicy sets the access control policy for a Queue. Replaces any existing +// policy. +// +// Note: The Cloud Console does not check queue-level IAM permissions yet. +// Project-level permissions are required to use the Cloud Console. +// +// Authorization requires the following +// Google IAM (at https://cloud.google.com/iam) permission on the specified +// resource parent: +// +// cloudtasks.queues.setIamPolicy +func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns permissions that a caller has on a Queue. +// If the resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building permission-aware +// UIs and command-line tools, not for authorization checking. This operation +// may “fail open” without warning. +func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// ListTasks lists the tasks in a queue. +// +// By default, only the BASIC view is retrieved +// due to performance considerations; +// response_view controls the +// subset of information which is returned. +// +// The tasks may be returned in any order. The ordering may change at any +// time. +func (c *Client) ListTasks(ctx context.Context, req *taskspb.ListTasksRequest, opts ...gax.CallOption) *TaskIterator { + return c.internalClient.ListTasks(ctx, req, opts...) +} + +// GetTask gets a task. +func (c *Client) GetTask(ctx context.Context, req *taskspb.GetTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { + return c.internalClient.GetTask(ctx, req, opts...) +} + +// CreateTask creates a task and adds it to a queue. +// +// Tasks cannot be updated after creation; there is no UpdateTask command. +// +// The maximum task size is 100KB. +func (c *Client) CreateTask(ctx context.Context, req *taskspb.CreateTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { + return c.internalClient.CreateTask(ctx, req, opts...) +} + +// DeleteTask deletes a task. +// +// A task can be deleted if it is scheduled or dispatched. A task +// cannot be deleted if it has executed successfully or permanently +// failed. +func (c *Client) DeleteTask(ctx context.Context, req *taskspb.DeleteTaskRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTask(ctx, req, opts...) +} + +// RunTask forces a task to run now. +// +// When this method is called, Cloud Tasks will dispatch the task, even if +// the task is already running, the queue has reached its RateLimits or +// is PAUSED. +// +// This command is meant to be used for manual debugging. For +// example, RunTask can be used to retry a failed +// task after a fix has been made or to manually force a task to be +// dispatched now. +// +// The dispatched task is returned. That is, the task that is returned +// contains the status after the task is dispatched but +// before the task is received by its target. +// +// If Cloud Tasks receives a successful response from the task’s +// target, then the task will be deleted; otherwise the task’s +// schedule_time will be reset to the time that +// RunTask was called plus the retry delay specified +// in the queue’s RetryConfig. +// +// RunTask returns +// NOT_FOUND when it is called on a +// task that has already succeeded or permanently failed. +func (c *Client) RunTask(ctx context.Context, req *taskspb.RunTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { + return c.internalClient.RunTask(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud Tasks API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client taskspb.CloudTasksClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new cloud tasks client. +// NewClient creates a new cloud tasks client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Cloud Tasks allows developers to manage the execution of background // work in their applications. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -223,47 +486,47 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: taskspb.NewCloudTasksClient(connPool), + client: taskspb.NewCloudTasksClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListQueues lists queues. -// -// Queues are returned in lexicographical order. -func (c *Client) ListQueues(ctx context.Context, req *taskspb.ListQueuesRequest, opts ...gax.CallOption) *QueueIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ListQueues(ctx context.Context, req *taskspb.ListQueuesRequest, opts ...gax.CallOption) *QueueIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListQueues[0:len(c.CallOptions.ListQueues):len(c.CallOptions.ListQueues)], opts...) + opts = append((*c.CallOptions).ListQueues[0:len((*c.CallOptions).ListQueues):len((*c.CallOptions).ListQueues)], opts...) it := &QueueIterator{} req = proto.Clone(req).(*taskspb.ListQueuesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*taskspb.Queue, string, error) { @@ -300,8 +563,7 @@ func (c *Client) ListQueues(ctx context.Context, req *taskspb.ListQueuesRequest, return it } -// GetQueue gets a queue. -func (c *Client) GetQueue(ctx context.Context, req *taskspb.GetQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) GetQueue(ctx context.Context, req *taskspb.GetQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -309,7 +571,7 @@ func (c *Client) GetQueue(ctx context.Context, req *taskspb.GetQueueRequest, opt } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetQueue[0:len(c.CallOptions.GetQueue):len(c.CallOptions.GetQueue)], opts...) + opts = append((*c.CallOptions).GetQueue[0:len((*c.CallOptions).GetQueue):len((*c.CallOptions).GetQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -322,19 +584,7 @@ func (c *Client) GetQueue(ctx context.Context, req *taskspb.GetQueueRequest, opt return resp, nil } -// CreateQueue creates a queue. -// -// Queues created with this method allow tasks to live for a maximum of 31 -// days. After a task is 31 days old, the task will be deleted regardless of whether -// it was dispatched or not. -// -// WARNING: Using this method may have unintended side effects if you are -// using an App Engine queue.yaml or queue.xml file to manage your queues. -// Read -// Overview of Queue Management and -// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using -// this method. -func (c *Client) CreateQueue(ctx context.Context, req *taskspb.CreateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) CreateQueue(ctx context.Context, req *taskspb.CreateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -342,7 +592,7 @@ func (c *Client) CreateQueue(ctx context.Context, req *taskspb.CreateQueueReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateQueue[0:len(c.CallOptions.CreateQueue):len(c.CallOptions.CreateQueue)], opts...) + opts = append((*c.CallOptions).CreateQueue[0:len((*c.CallOptions).CreateQueue):len((*c.CallOptions).CreateQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -355,22 +605,7 @@ func (c *Client) CreateQueue(ctx context.Context, req *taskspb.CreateQueueReques return resp, nil } -// UpdateQueue updates a queue. -// -// This method creates the queue if it does not exist and updates -// the queue if it does exist. -// -// Queues created with this method allow tasks to live for a maximum of 31 -// days. After a task is 31 days old, the task will be deleted regardless of whether -// it was dispatched or not. -// -// WARNING: Using this method may have unintended side effects if you are -// using an App Engine queue.yaml or queue.xml file to manage your queues. -// Read -// Overview of Queue Management and -// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using -// this method. -func (c *Client) UpdateQueue(ctx context.Context, req *taskspb.UpdateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) UpdateQueue(ctx context.Context, req *taskspb.UpdateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -378,7 +613,7 @@ func (c *Client) UpdateQueue(ctx context.Context, req *taskspb.UpdateQueueReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "queue.name", url.QueryEscape(req.GetQueue().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateQueue[0:len(c.CallOptions.UpdateQueue):len(c.CallOptions.UpdateQueue)], opts...) + opts = append((*c.CallOptions).UpdateQueue[0:len((*c.CallOptions).UpdateQueue):len((*c.CallOptions).UpdateQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -391,20 +626,7 @@ func (c *Client) UpdateQueue(ctx context.Context, req *taskspb.UpdateQueueReques return resp, nil } -// DeleteQueue deletes a queue. -// -// This command will delete the queue even if it has tasks in it. -// -// Note: If you delete a queue, a queue with the same name can’t be created -// for 7 days. -// -// WARNING: Using this method may have unintended side effects if you are -// using an App Engine queue.yaml or queue.xml file to manage your queues. -// Read -// Overview of Queue Management and -// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using -// this method. -func (c *Client) DeleteQueue(ctx context.Context, req *taskspb.DeleteQueueRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteQueue(ctx context.Context, req *taskspb.DeleteQueueRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -412,7 +634,7 @@ func (c *Client) DeleteQueue(ctx context.Context, req *taskspb.DeleteQueueReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteQueue[0:len(c.CallOptions.DeleteQueue):len(c.CallOptions.DeleteQueue)], opts...) + opts = append((*c.CallOptions).DeleteQueue[0:len((*c.CallOptions).DeleteQueue):len((*c.CallOptions).DeleteQueue)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteQueue(ctx, req, settings.GRPC...) @@ -421,13 +643,7 @@ func (c *Client) DeleteQueue(ctx context.Context, req *taskspb.DeleteQueueReques return err } -// PurgeQueue purges a queue by deleting all of its tasks. -// -// All tasks created before this method is called are permanently deleted. -// -// Purge operations can take up to one minute to take effect. Tasks -// might be dispatched before the purge takes effect. A purge is irreversible. -func (c *Client) PurgeQueue(ctx context.Context, req *taskspb.PurgeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) PurgeQueue(ctx context.Context, req *taskspb.PurgeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -435,7 +651,7 @@ func (c *Client) PurgeQueue(ctx context.Context, req *taskspb.PurgeQueueRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PurgeQueue[0:len(c.CallOptions.PurgeQueue):len(c.CallOptions.PurgeQueue)], opts...) + opts = append((*c.CallOptions).PurgeQueue[0:len((*c.CallOptions).PurgeQueue):len((*c.CallOptions).PurgeQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -448,14 +664,7 @@ func (c *Client) PurgeQueue(ctx context.Context, req *taskspb.PurgeQueueRequest, return resp, nil } -// PauseQueue pauses the queue. -// -// If a queue is paused then the system will stop dispatching tasks -// until the queue is resumed via -// ResumeQueue. Tasks can still be added -// when the queue is paused. A queue is paused if its -// state is PAUSED. -func (c *Client) PauseQueue(ctx context.Context, req *taskspb.PauseQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) PauseQueue(ctx context.Context, req *taskspb.PauseQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -463,7 +672,7 @@ func (c *Client) PauseQueue(ctx context.Context, req *taskspb.PauseQueueRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PauseQueue[0:len(c.CallOptions.PauseQueue):len(c.CallOptions.PauseQueue)], opts...) + opts = append((*c.CallOptions).PauseQueue[0:len((*c.CallOptions).PauseQueue):len((*c.CallOptions).PauseQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -476,20 +685,7 @@ func (c *Client) PauseQueue(ctx context.Context, req *taskspb.PauseQueueRequest, return resp, nil } -// ResumeQueue resume a queue. -// -// This method resumes a queue after it has been -// PAUSED or -// DISABLED. The state of a queue is stored -// in the queue’s state; after calling this method it -// will be set to RUNNING. -// -// WARNING: Resuming many high-QPS queues at the same time can -// lead to target overloading. If you are resuming high-QPS -// queues, follow the 500/50/5 pattern described in -// Managing Cloud Tasks Scaling -// Risks (at https://cloud.google.com/tasks/docs/manage-cloud-task-scaling). -func (c *Client) ResumeQueue(ctx context.Context, req *taskspb.ResumeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) ResumeQueue(ctx context.Context, req *taskspb.ResumeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -497,7 +693,7 @@ func (c *Client) ResumeQueue(ctx context.Context, req *taskspb.ResumeQueueReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ResumeQueue[0:len(c.CallOptions.ResumeQueue):len(c.CallOptions.ResumeQueue)], opts...) + opts = append((*c.CallOptions).ResumeQueue[0:len((*c.CallOptions).ResumeQueue):len((*c.CallOptions).ResumeQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -510,16 +706,7 @@ func (c *Client) ResumeQueue(ctx context.Context, req *taskspb.ResumeQueueReques return resp, nil } -// GetIamPolicy gets the access control policy for a Queue. -// Returns an empty policy if the resource exists and does not have a policy -// set. -// -// Authorization requires the following -// Google IAM (at https://cloud.google.com/iam) permission on the specified -// resource parent: -// -// cloudtasks.queues.getIamPolicy -func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -527,7 +714,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -540,18 +727,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques return resp, nil } -// SetIamPolicy sets the access control policy for a Queue. Replaces any existing -// policy. -// -// Note: The Cloud Console does not check queue-level IAM permissions yet. -// Project-level permissions are required to use the Cloud Console. -// -// Authorization requires the following -// Google IAM (at https://cloud.google.com/iam) permission on the specified -// resource parent: -// -// cloudtasks.queues.setIamPolicy -func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -559,7 +735,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -572,14 +748,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques return resp, nil } -// TestIamPermissions returns permissions that a caller has on a Queue. -// If the resource does not exist, this will return an empty set of -// permissions, not a NOT_FOUND error. -// -// Note: This operation is designed to be used for building permission-aware -// UIs and command-line tools, not for authorization checking. This operation -// may “fail open” without warning. -func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *gRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -587,7 +756,7 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -600,19 +769,10 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi return resp, nil } -// ListTasks lists the tasks in a queue. -// -// By default, only the BASIC view is retrieved -// due to performance considerations; -// response_view controls the -// subset of information which is returned. -// -// The tasks may be returned in any order. The ordering may change at any -// time. -func (c *Client) ListTasks(ctx context.Context, req *taskspb.ListTasksRequest, opts ...gax.CallOption) *TaskIterator { +func (c *gRPCClient) ListTasks(ctx context.Context, req *taskspb.ListTasksRequest, opts ...gax.CallOption) *TaskIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTasks[0:len(c.CallOptions.ListTasks):len(c.CallOptions.ListTasks)], opts...) + opts = append((*c.CallOptions).ListTasks[0:len((*c.CallOptions).ListTasks):len((*c.CallOptions).ListTasks)], opts...) it := &TaskIterator{} req = proto.Clone(req).(*taskspb.ListTasksRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*taskspb.Task, string, error) { @@ -649,8 +809,7 @@ func (c *Client) ListTasks(ctx context.Context, req *taskspb.ListTasksRequest, o return it } -// GetTask gets a task. -func (c *Client) GetTask(ctx context.Context, req *taskspb.GetTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { +func (c *gRPCClient) GetTask(ctx context.Context, req *taskspb.GetTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -658,7 +817,7 @@ func (c *Client) GetTask(ctx context.Context, req *taskspb.GetTaskRequest, opts } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTask[0:len(c.CallOptions.GetTask):len(c.CallOptions.GetTask)], opts...) + opts = append((*c.CallOptions).GetTask[0:len((*c.CallOptions).GetTask):len((*c.CallOptions).GetTask)], opts...) var resp *taskspb.Task err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -671,12 +830,7 @@ func (c *Client) GetTask(ctx context.Context, req *taskspb.GetTaskRequest, opts return resp, nil } -// CreateTask creates a task and adds it to a queue. -// -// Tasks cannot be updated after creation; there is no UpdateTask command. -// -// The maximum task size is 100KB. -func (c *Client) CreateTask(ctx context.Context, req *taskspb.CreateTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { +func (c *gRPCClient) CreateTask(ctx context.Context, req *taskspb.CreateTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -684,7 +838,7 @@ func (c *Client) CreateTask(ctx context.Context, req *taskspb.CreateTaskRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTask[0:len(c.CallOptions.CreateTask):len(c.CallOptions.CreateTask)], opts...) + opts = append((*c.CallOptions).CreateTask[0:len((*c.CallOptions).CreateTask):len((*c.CallOptions).CreateTask)], opts...) var resp *taskspb.Task err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -697,12 +851,7 @@ func (c *Client) CreateTask(ctx context.Context, req *taskspb.CreateTaskRequest, return resp, nil } -// DeleteTask deletes a task. -// -// A task can be deleted if it is scheduled or dispatched. A task -// cannot be deleted if it has executed successfully or permanently -// failed. -func (c *Client) DeleteTask(ctx context.Context, req *taskspb.DeleteTaskRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteTask(ctx context.Context, req *taskspb.DeleteTaskRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -710,7 +859,7 @@ func (c *Client) DeleteTask(ctx context.Context, req *taskspb.DeleteTaskRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTask[0:len(c.CallOptions.DeleteTask):len(c.CallOptions.DeleteTask)], opts...) + opts = append((*c.CallOptions).DeleteTask[0:len((*c.CallOptions).DeleteTask):len((*c.CallOptions).DeleteTask)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteTask(ctx, req, settings.GRPC...) @@ -719,31 +868,7 @@ func (c *Client) DeleteTask(ctx context.Context, req *taskspb.DeleteTaskRequest, return err } -// RunTask forces a task to run now. -// -// When this method is called, Cloud Tasks will dispatch the task, even if -// the task is already running, the queue has reached its RateLimits or -// is PAUSED. -// -// This command is meant to be used for manual debugging. For -// example, RunTask can be used to retry a failed -// task after a fix has been made or to manually force a task to be -// dispatched now. -// -// The dispatched task is returned. That is, the task that is returned -// contains the status after the task is dispatched but -// before the task is received by its target. -// -// If Cloud Tasks receives a successful response from the task’s -// target, then the task will be deleted; otherwise the task’s -// schedule_time will be reset to the time that -// RunTask was called plus the retry delay specified -// in the queue’s RetryConfig. -// -// RunTask returns -// NOT_FOUND when it is called on a -// task that has already succeeded or permanently failed. -func (c *Client) RunTask(ctx context.Context, req *taskspb.RunTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { +func (c *gRPCClient) RunTask(ctx context.Context, req *taskspb.RunTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -751,7 +876,7 @@ func (c *Client) RunTask(ctx context.Context, req *taskspb.RunTaskRequest, opts } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RunTask[0:len(c.CallOptions.RunTask):len(c.CallOptions.RunTask)], opts...) + opts = append((*c.CallOptions).RunTask[0:len((*c.CallOptions).RunTask):len((*c.CallOptions).RunTask)], opts...) var resp *taskspb.Task err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/cloudtasks/apiv2/cloud_tasks_client_example_test.go b/cloudtasks/apiv2/cloud_tasks_client_example_test.go index a75f829a97f9..3b3c19c6963e 100644 --- a/cloudtasks/apiv2/cloud_tasks_client_example_test.go +++ b/cloudtasks/apiv2/cloud_tasks_client_example_test.go @@ -31,19 +31,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ListQueues() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ListQueuesRequest{ // TODO: Fill request struct fields. @@ -63,13 +63,12 @@ func ExampleClient_ListQueues() { } func ExampleClient_GetQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.GetQueueRequest{ // TODO: Fill request struct fields. @@ -83,13 +82,12 @@ func ExampleClient_GetQueue() { } func ExampleClient_CreateQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.CreateQueueRequest{ // TODO: Fill request struct fields. @@ -103,13 +101,12 @@ func ExampleClient_CreateQueue() { } func ExampleClient_UpdateQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.UpdateQueueRequest{ // TODO: Fill request struct fields. @@ -128,6 +125,7 @@ func ExampleClient_DeleteQueue() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.DeleteQueueRequest{ // TODO: Fill request struct fields. @@ -139,13 +137,12 @@ func ExampleClient_DeleteQueue() { } func ExampleClient_PurgeQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.PurgeQueueRequest{ // TODO: Fill request struct fields. @@ -159,13 +156,12 @@ func ExampleClient_PurgeQueue() { } func ExampleClient_PauseQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.PauseQueueRequest{ // TODO: Fill request struct fields. @@ -179,13 +175,12 @@ func ExampleClient_PauseQueue() { } func ExampleClient_ResumeQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ResumeQueueRequest{ // TODO: Fill request struct fields. @@ -199,13 +194,12 @@ func ExampleClient_ResumeQueue() { } func ExampleClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -219,13 +213,12 @@ func ExampleClient_GetIamPolicy() { } func ExampleClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -239,13 +232,12 @@ func ExampleClient_SetIamPolicy() { } func ExampleClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. @@ -259,14 +251,12 @@ func ExampleClient_TestIamPermissions() { } func ExampleClient_ListTasks() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ListTasksRequest{ // TODO: Fill request struct fields. @@ -286,13 +276,12 @@ func ExampleClient_ListTasks() { } func ExampleClient_GetTask() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.GetTaskRequest{ // TODO: Fill request struct fields. @@ -306,13 +295,12 @@ func ExampleClient_GetTask() { } func ExampleClient_CreateTask() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.CreateTaskRequest{ // TODO: Fill request struct fields. @@ -331,6 +319,7 @@ func ExampleClient_DeleteTask() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.DeleteTaskRequest{ // TODO: Fill request struct fields. @@ -342,13 +331,12 @@ func ExampleClient_DeleteTask() { } func ExampleClient_RunTask() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.RunTaskRequest{ // TODO: Fill request struct fields. diff --git a/cloudtasks/apiv2/doc.go b/cloudtasks/apiv2/doc.go index 10eb477b6411..f35f397c595a 100644 --- a/cloudtasks/apiv2/doc.go +++ b/cloudtasks/apiv2/doc.go @@ -28,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package cloudtasks // import "cloud.google.com/go/cloudtasks/apiv2" import ( @@ -48,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/cloudtasks/apiv2beta2/cloud_tasks_client.go b/cloudtasks/apiv2beta2/cloud_tasks_client.go index 1f4ed98d2888..21151e542723 100644 --- a/cloudtasks/apiv2beta2/cloud_tasks_client.go +++ b/cloudtasks/apiv2beta2/cloud_tasks_client.go @@ -62,7 +62,7 @@ type CallOptions struct { RunTask []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudtasks.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudtasks.mtls.googleapis.com:443"), @@ -187,33 +187,368 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Tasks API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListQueues(context.Context, *taskspb.ListQueuesRequest, ...gax.CallOption) *QueueIterator + GetQueue(context.Context, *taskspb.GetQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + CreateQueue(context.Context, *taskspb.CreateQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + UpdateQueue(context.Context, *taskspb.UpdateQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + DeleteQueue(context.Context, *taskspb.DeleteQueueRequest, ...gax.CallOption) error + PurgeQueue(context.Context, *taskspb.PurgeQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + PauseQueue(context.Context, *taskspb.PauseQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + ResumeQueue(context.Context, *taskspb.ResumeQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) + ListTasks(context.Context, *taskspb.ListTasksRequest, ...gax.CallOption) *TaskIterator + GetTask(context.Context, *taskspb.GetTaskRequest, ...gax.CallOption) (*taskspb.Task, error) + CreateTask(context.Context, *taskspb.CreateTaskRequest, ...gax.CallOption) (*taskspb.Task, error) + DeleteTask(context.Context, *taskspb.DeleteTaskRequest, ...gax.CallOption) error + LeaseTasks(context.Context, *taskspb.LeaseTasksRequest, ...gax.CallOption) (*taskspb.LeaseTasksResponse, error) + AcknowledgeTask(context.Context, *taskspb.AcknowledgeTaskRequest, ...gax.CallOption) error + RenewLease(context.Context, *taskspb.RenewLeaseRequest, ...gax.CallOption) (*taskspb.Task, error) + CancelLease(context.Context, *taskspb.CancelLeaseRequest, ...gax.CallOption) (*taskspb.Task, error) + RunTask(context.Context, *taskspb.RunTaskRequest, ...gax.CallOption) (*taskspb.Task, error) +} + // Client is a client for interacting with Cloud Tasks API. +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Cloud Tasks allows developers to manage the execution of background +// work in their applications. +type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListQueues lists queues. +// +// Queues are returned in lexicographical order. +func (c *Client) ListQueues(ctx context.Context, req *taskspb.ListQueuesRequest, opts ...gax.CallOption) *QueueIterator { + return c.internalClient.ListQueues(ctx, req, opts...) +} + +// GetQueue gets a queue. +func (c *Client) GetQueue(ctx context.Context, req *taskspb.GetQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.GetQueue(ctx, req, opts...) +} + +// CreateQueue creates a queue. +// +// Queues created with this method allow tasks to live for a maximum of 31 +// days. After a task is 31 days old, the task will be deleted regardless of whether +// it was dispatched or not. +// +// WARNING: Using this method may have unintended side effects if you are +// using an App Engine queue.yaml or queue.xml file to manage your queues. +// Read +// Overview of Queue Management and +// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using +// this method. +func (c *Client) CreateQueue(ctx context.Context, req *taskspb.CreateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.CreateQueue(ctx, req, opts...) +} + +// UpdateQueue updates a queue. +// +// This method creates the queue if it does not exist and updates +// the queue if it does exist. +// +// Queues created with this method allow tasks to live for a maximum of 31 +// days. After a task is 31 days old, the task will be deleted regardless of whether +// it was dispatched or not. +// +// WARNING: Using this method may have unintended side effects if you are +// using an App Engine queue.yaml or queue.xml file to manage your queues. +// Read +// Overview of Queue Management and +// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using +// this method. +func (c *Client) UpdateQueue(ctx context.Context, req *taskspb.UpdateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.UpdateQueue(ctx, req, opts...) +} + +// DeleteQueue deletes a queue. +// +// This command will delete the queue even if it has tasks in it. +// +// Note: If you delete a queue, a queue with the same name can’t be created +// for 7 days. +// +// WARNING: Using this method may have unintended side effects if you are +// using an App Engine queue.yaml or queue.xml file to manage your queues. +// Read +// Overview of Queue Management and +// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using +// this method. +func (c *Client) DeleteQueue(ctx context.Context, req *taskspb.DeleteQueueRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteQueue(ctx, req, opts...) +} + +// PurgeQueue purges a queue by deleting all of its tasks. +// +// All tasks created before this method is called are permanently deleted. +// +// Purge operations can take up to one minute to take effect. Tasks +// might be dispatched before the purge takes effect. A purge is irreversible. +func (c *Client) PurgeQueue(ctx context.Context, req *taskspb.PurgeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.PurgeQueue(ctx, req, opts...) +} + +// PauseQueue pauses the queue. +// +// If a queue is paused then the system will stop dispatching tasks +// until the queue is resumed via +// ResumeQueue. Tasks can still be added +// when the queue is paused. A queue is paused if its +// state is PAUSED. +func (c *Client) PauseQueue(ctx context.Context, req *taskspb.PauseQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.PauseQueue(ctx, req, opts...) +} + +// ResumeQueue resume a queue. +// +// This method resumes a queue after it has been +// PAUSED or +// DISABLED. The state of a queue is stored +// in the queue’s state; after calling this method it +// will be set to RUNNING. +// +// WARNING: Resuming many high-QPS queues at the same time can +// lead to target overloading. If you are resuming high-QPS +// queues, follow the 500/50/5 pattern described in +// Managing Cloud Tasks Scaling +// Risks (at https://cloud.google.com/tasks/docs/manage-cloud-task-scaling). +func (c *Client) ResumeQueue(ctx context.Context, req *taskspb.ResumeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.ResumeQueue(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy for a Queue. +// Returns an empty policy if the resource exists and does not have a policy +// set. +// +// Authorization requires the following +// Google IAM (at https://cloud.google.com/iam) permission on the specified +// resource parent: +// +// cloudtasks.queues.getIamPolicy +func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// SetIamPolicy sets the access control policy for a Queue. Replaces any existing +// policy. +// +// Note: The Cloud Console does not check queue-level IAM permissions yet. +// Project-level permissions are required to use the Cloud Console. +// +// Authorization requires the following +// Google IAM (at https://cloud.google.com/iam) permission on the specified +// resource parent: +// +// cloudtasks.queues.setIamPolicy +func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns permissions that a caller has on a Queue. +// If the resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building permission-aware +// UIs and command-line tools, not for authorization checking. This operation +// may “fail open” without warning. +func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// ListTasks lists the tasks in a queue. +// +// By default, only the BASIC view is retrieved +// due to performance considerations; +// response_view controls the +// subset of information which is returned. +// +// The tasks may be returned in any order. The ordering may change at any +// time. +func (c *Client) ListTasks(ctx context.Context, req *taskspb.ListTasksRequest, opts ...gax.CallOption) *TaskIterator { + return c.internalClient.ListTasks(ctx, req, opts...) +} + +// GetTask gets a task. +func (c *Client) GetTask(ctx context.Context, req *taskspb.GetTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { + return c.internalClient.GetTask(ctx, req, opts...) +} + +// CreateTask creates a task and adds it to a queue. +// +// Tasks cannot be updated after creation; there is no UpdateTask command. +// +// For [App Engine queues][google.cloud.tasks.v2beta2.AppEngineHttpTarget], the maximum task size is +// 100KB. +// +// For [pull queues][google.cloud.tasks.v2beta2.PullTarget], the maximum task size is 1MB. +func (c *Client) CreateTask(ctx context.Context, req *taskspb.CreateTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { + return c.internalClient.CreateTask(ctx, req, opts...) +} + +// DeleteTask deletes a task. +// +// A task can be deleted if it is scheduled or dispatched. A task +// cannot be deleted if it has completed successfully or permanently +// failed. +func (c *Client) DeleteTask(ctx context.Context, req *taskspb.DeleteTaskRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTask(ctx, req, opts...) +} + +// LeaseTasks leases tasks from a pull queue for +// lease_duration. +// +// This method is invoked by the worker to obtain a lease. The +// worker must acknowledge the task via +// AcknowledgeTask after they have +// performed the work associated with the task. +// +// The payload is intended to store data that +// the worker needs to perform the work associated with the task. To +// return the payloads in the response, set +// response_view to +// FULL. +// +// A maximum of 10 qps of LeaseTasks +// requests are allowed per +// queue. RESOURCE_EXHAUSTED +// is returned when this limit is +// exceeded. RESOURCE_EXHAUSTED +// is also returned when +// max_tasks_dispatched_per_second +// is exceeded. +func (c *Client) LeaseTasks(ctx context.Context, req *taskspb.LeaseTasksRequest, opts ...gax.CallOption) (*taskspb.LeaseTasksResponse, error) { + return c.internalClient.LeaseTasks(ctx, req, opts...) +} + +// AcknowledgeTask acknowledges a pull task. +// +// The worker, that is, the entity that +// leased this task must call this method +// to indicate that the work associated with the task has finished. +// +// The worker must acknowledge a task within the +// lease_duration or the lease +// will expire and the task will become available to be leased +// again. After the task is acknowledged, it will not be returned +// by a later LeaseTasks, +// GetTask, or +// ListTasks. +func (c *Client) AcknowledgeTask(ctx context.Context, req *taskspb.AcknowledgeTaskRequest, opts ...gax.CallOption) error { + return c.internalClient.AcknowledgeTask(ctx, req, opts...) +} + +// RenewLease renew the current lease of a pull task. +// +// The worker can use this method to extend the lease by a new +// duration, starting from now. The new task lease will be +// returned in the task’s schedule_time. +func (c *Client) RenewLease(ctx context.Context, req *taskspb.RenewLeaseRequest, opts ...gax.CallOption) (*taskspb.Task, error) { + return c.internalClient.RenewLease(ctx, req, opts...) +} + +// CancelLease cancel a pull task’s lease. +// +// The worker can use this method to cancel a task’s lease by +// setting its schedule_time to now. This will +// make the task available to be leased to the next caller of +// LeaseTasks. +func (c *Client) CancelLease(ctx context.Context, req *taskspb.CancelLeaseRequest, opts ...gax.CallOption) (*taskspb.Task, error) { + return c.internalClient.CancelLease(ctx, req, opts...) +} + +// RunTask forces a task to run now. +// +// When this method is called, Cloud Tasks will dispatch the task, even if +// the task is already running, the queue has reached its RateLimits or +// is PAUSED. +// +// This command is meant to be used for manual debugging. For +// example, RunTask can be used to retry a failed +// task after a fix has been made or to manually force a task to be +// dispatched now. +// +// The dispatched task is returned. That is, the task that is returned +// contains the status after the task is dispatched but +// before the task is received by its target. +// +// If Cloud Tasks receives a successful response from the task’s +// target, then the task will be deleted; otherwise the task’s +// schedule_time will be reset to the time that +// RunTask was called plus the retry delay specified +// in the queue’s RetryConfig. +// +// RunTask returns +// NOT_FOUND when it is called on a +// task that has already succeeded or permanently failed. +// +// RunTask cannot be called on a +// [pull task][google.cloud.tasks.v2beta2.PullMessage]. +func (c *Client) RunTask(ctx context.Context, req *taskspb.RunTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { + return c.internalClient.RunTask(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud Tasks API over gRPC transport. // // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. -type Client struct { +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client taskspb.CloudTasksClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new cloud tasks client. +// NewClient creates a new cloud tasks client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Cloud Tasks allows developers to manage the execution of background // work in their applications. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -231,47 +566,47 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: taskspb.NewCloudTasksClient(connPool), + client: taskspb.NewCloudTasksClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListQueues lists queues. -// -// Queues are returned in lexicographical order. -func (c *Client) ListQueues(ctx context.Context, req *taskspb.ListQueuesRequest, opts ...gax.CallOption) *QueueIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ListQueues(ctx context.Context, req *taskspb.ListQueuesRequest, opts ...gax.CallOption) *QueueIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListQueues[0:len(c.CallOptions.ListQueues):len(c.CallOptions.ListQueues)], opts...) + opts = append((*c.CallOptions).ListQueues[0:len((*c.CallOptions).ListQueues):len((*c.CallOptions).ListQueues)], opts...) it := &QueueIterator{} req = proto.Clone(req).(*taskspb.ListQueuesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*taskspb.Queue, string, error) { @@ -308,8 +643,7 @@ func (c *Client) ListQueues(ctx context.Context, req *taskspb.ListQueuesRequest, return it } -// GetQueue gets a queue. -func (c *Client) GetQueue(ctx context.Context, req *taskspb.GetQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) GetQueue(ctx context.Context, req *taskspb.GetQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -317,7 +651,7 @@ func (c *Client) GetQueue(ctx context.Context, req *taskspb.GetQueueRequest, opt } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetQueue[0:len(c.CallOptions.GetQueue):len(c.CallOptions.GetQueue)], opts...) + opts = append((*c.CallOptions).GetQueue[0:len((*c.CallOptions).GetQueue):len((*c.CallOptions).GetQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -330,19 +664,7 @@ func (c *Client) GetQueue(ctx context.Context, req *taskspb.GetQueueRequest, opt return resp, nil } -// CreateQueue creates a queue. -// -// Queues created with this method allow tasks to live for a maximum of 31 -// days. After a task is 31 days old, the task will be deleted regardless of whether -// it was dispatched or not. -// -// WARNING: Using this method may have unintended side effects if you are -// using an App Engine queue.yaml or queue.xml file to manage your queues. -// Read -// Overview of Queue Management and -// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using -// this method. -func (c *Client) CreateQueue(ctx context.Context, req *taskspb.CreateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) CreateQueue(ctx context.Context, req *taskspb.CreateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -350,7 +672,7 @@ func (c *Client) CreateQueue(ctx context.Context, req *taskspb.CreateQueueReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateQueue[0:len(c.CallOptions.CreateQueue):len(c.CallOptions.CreateQueue)], opts...) + opts = append((*c.CallOptions).CreateQueue[0:len((*c.CallOptions).CreateQueue):len((*c.CallOptions).CreateQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -363,22 +685,7 @@ func (c *Client) CreateQueue(ctx context.Context, req *taskspb.CreateQueueReques return resp, nil } -// UpdateQueue updates a queue. -// -// This method creates the queue if it does not exist and updates -// the queue if it does exist. -// -// Queues created with this method allow tasks to live for a maximum of 31 -// days. After a task is 31 days old, the task will be deleted regardless of whether -// it was dispatched or not. -// -// WARNING: Using this method may have unintended side effects if you are -// using an App Engine queue.yaml or queue.xml file to manage your queues. -// Read -// Overview of Queue Management and -// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using -// this method. -func (c *Client) UpdateQueue(ctx context.Context, req *taskspb.UpdateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) UpdateQueue(ctx context.Context, req *taskspb.UpdateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -386,7 +693,7 @@ func (c *Client) UpdateQueue(ctx context.Context, req *taskspb.UpdateQueueReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "queue.name", url.QueryEscape(req.GetQueue().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateQueue[0:len(c.CallOptions.UpdateQueue):len(c.CallOptions.UpdateQueue)], opts...) + opts = append((*c.CallOptions).UpdateQueue[0:len((*c.CallOptions).UpdateQueue):len((*c.CallOptions).UpdateQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -399,20 +706,7 @@ func (c *Client) UpdateQueue(ctx context.Context, req *taskspb.UpdateQueueReques return resp, nil } -// DeleteQueue deletes a queue. -// -// This command will delete the queue even if it has tasks in it. -// -// Note: If you delete a queue, a queue with the same name can’t be created -// for 7 days. -// -// WARNING: Using this method may have unintended side effects if you are -// using an App Engine queue.yaml or queue.xml file to manage your queues. -// Read -// Overview of Queue Management and -// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using -// this method. -func (c *Client) DeleteQueue(ctx context.Context, req *taskspb.DeleteQueueRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteQueue(ctx context.Context, req *taskspb.DeleteQueueRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -420,7 +714,7 @@ func (c *Client) DeleteQueue(ctx context.Context, req *taskspb.DeleteQueueReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteQueue[0:len(c.CallOptions.DeleteQueue):len(c.CallOptions.DeleteQueue)], opts...) + opts = append((*c.CallOptions).DeleteQueue[0:len((*c.CallOptions).DeleteQueue):len((*c.CallOptions).DeleteQueue)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteQueue(ctx, req, settings.GRPC...) @@ -429,13 +723,7 @@ func (c *Client) DeleteQueue(ctx context.Context, req *taskspb.DeleteQueueReques return err } -// PurgeQueue purges a queue by deleting all of its tasks. -// -// All tasks created before this method is called are permanently deleted. -// -// Purge operations can take up to one minute to take effect. Tasks -// might be dispatched before the purge takes effect. A purge is irreversible. -func (c *Client) PurgeQueue(ctx context.Context, req *taskspb.PurgeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) PurgeQueue(ctx context.Context, req *taskspb.PurgeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -443,7 +731,7 @@ func (c *Client) PurgeQueue(ctx context.Context, req *taskspb.PurgeQueueRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PurgeQueue[0:len(c.CallOptions.PurgeQueue):len(c.CallOptions.PurgeQueue)], opts...) + opts = append((*c.CallOptions).PurgeQueue[0:len((*c.CallOptions).PurgeQueue):len((*c.CallOptions).PurgeQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -456,14 +744,7 @@ func (c *Client) PurgeQueue(ctx context.Context, req *taskspb.PurgeQueueRequest, return resp, nil } -// PauseQueue pauses the queue. -// -// If a queue is paused then the system will stop dispatching tasks -// until the queue is resumed via -// ResumeQueue. Tasks can still be added -// when the queue is paused. A queue is paused if its -// state is PAUSED. -func (c *Client) PauseQueue(ctx context.Context, req *taskspb.PauseQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) PauseQueue(ctx context.Context, req *taskspb.PauseQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -471,7 +752,7 @@ func (c *Client) PauseQueue(ctx context.Context, req *taskspb.PauseQueueRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PauseQueue[0:len(c.CallOptions.PauseQueue):len(c.CallOptions.PauseQueue)], opts...) + opts = append((*c.CallOptions).PauseQueue[0:len((*c.CallOptions).PauseQueue):len((*c.CallOptions).PauseQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -484,20 +765,7 @@ func (c *Client) PauseQueue(ctx context.Context, req *taskspb.PauseQueueRequest, return resp, nil } -// ResumeQueue resume a queue. -// -// This method resumes a queue after it has been -// PAUSED or -// DISABLED. The state of a queue is stored -// in the queue’s state; after calling this method it -// will be set to RUNNING. -// -// WARNING: Resuming many high-QPS queues at the same time can -// lead to target overloading. If you are resuming high-QPS -// queues, follow the 500/50/5 pattern described in -// Managing Cloud Tasks Scaling -// Risks (at https://cloud.google.com/tasks/docs/manage-cloud-task-scaling). -func (c *Client) ResumeQueue(ctx context.Context, req *taskspb.ResumeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) ResumeQueue(ctx context.Context, req *taskspb.ResumeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -505,7 +773,7 @@ func (c *Client) ResumeQueue(ctx context.Context, req *taskspb.ResumeQueueReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ResumeQueue[0:len(c.CallOptions.ResumeQueue):len(c.CallOptions.ResumeQueue)], opts...) + opts = append((*c.CallOptions).ResumeQueue[0:len((*c.CallOptions).ResumeQueue):len((*c.CallOptions).ResumeQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -518,16 +786,7 @@ func (c *Client) ResumeQueue(ctx context.Context, req *taskspb.ResumeQueueReques return resp, nil } -// GetIamPolicy gets the access control policy for a Queue. -// Returns an empty policy if the resource exists and does not have a policy -// set. -// -// Authorization requires the following -// Google IAM (at https://cloud.google.com/iam) permission on the specified -// resource parent: -// -// cloudtasks.queues.getIamPolicy -func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -535,7 +794,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -548,18 +807,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques return resp, nil } -// SetIamPolicy sets the access control policy for a Queue. Replaces any existing -// policy. -// -// Note: The Cloud Console does not check queue-level IAM permissions yet. -// Project-level permissions are required to use the Cloud Console. -// -// Authorization requires the following -// Google IAM (at https://cloud.google.com/iam) permission on the specified -// resource parent: -// -// cloudtasks.queues.setIamPolicy -func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -567,7 +815,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -580,14 +828,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques return resp, nil } -// TestIamPermissions returns permissions that a caller has on a Queue. -// If the resource does not exist, this will return an empty set of -// permissions, not a NOT_FOUND error. -// -// Note: This operation is designed to be used for building permission-aware -// UIs and command-line tools, not for authorization checking. This operation -// may “fail open” without warning. -func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *gRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -595,7 +836,7 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -608,19 +849,10 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi return resp, nil } -// ListTasks lists the tasks in a queue. -// -// By default, only the BASIC view is retrieved -// due to performance considerations; -// response_view controls the -// subset of information which is returned. -// -// The tasks may be returned in any order. The ordering may change at any -// time. -func (c *Client) ListTasks(ctx context.Context, req *taskspb.ListTasksRequest, opts ...gax.CallOption) *TaskIterator { +func (c *gRPCClient) ListTasks(ctx context.Context, req *taskspb.ListTasksRequest, opts ...gax.CallOption) *TaskIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTasks[0:len(c.CallOptions.ListTasks):len(c.CallOptions.ListTasks)], opts...) + opts = append((*c.CallOptions).ListTasks[0:len((*c.CallOptions).ListTasks):len((*c.CallOptions).ListTasks)], opts...) it := &TaskIterator{} req = proto.Clone(req).(*taskspb.ListTasksRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*taskspb.Task, string, error) { @@ -657,8 +889,7 @@ func (c *Client) ListTasks(ctx context.Context, req *taskspb.ListTasksRequest, o return it } -// GetTask gets a task. -func (c *Client) GetTask(ctx context.Context, req *taskspb.GetTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { +func (c *gRPCClient) GetTask(ctx context.Context, req *taskspb.GetTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -666,7 +897,7 @@ func (c *Client) GetTask(ctx context.Context, req *taskspb.GetTaskRequest, opts } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTask[0:len(c.CallOptions.GetTask):len(c.CallOptions.GetTask)], opts...) + opts = append((*c.CallOptions).GetTask[0:len((*c.CallOptions).GetTask):len((*c.CallOptions).GetTask)], opts...) var resp *taskspb.Task err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -679,15 +910,7 @@ func (c *Client) GetTask(ctx context.Context, req *taskspb.GetTaskRequest, opts return resp, nil } -// CreateTask creates a task and adds it to a queue. -// -// Tasks cannot be updated after creation; there is no UpdateTask command. -// -// For [App Engine queues][google.cloud.tasks.v2beta2.AppEngineHttpTarget], the maximum task size is -// 100KB. -// -// For [pull queues][google.cloud.tasks.v2beta2.PullTarget], the maximum task size is 1MB. -func (c *Client) CreateTask(ctx context.Context, req *taskspb.CreateTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { +func (c *gRPCClient) CreateTask(ctx context.Context, req *taskspb.CreateTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -695,7 +918,7 @@ func (c *Client) CreateTask(ctx context.Context, req *taskspb.CreateTaskRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTask[0:len(c.CallOptions.CreateTask):len(c.CallOptions.CreateTask)], opts...) + opts = append((*c.CallOptions).CreateTask[0:len((*c.CallOptions).CreateTask):len((*c.CallOptions).CreateTask)], opts...) var resp *taskspb.Task err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -708,12 +931,7 @@ func (c *Client) CreateTask(ctx context.Context, req *taskspb.CreateTaskRequest, return resp, nil } -// DeleteTask deletes a task. -// -// A task can be deleted if it is scheduled or dispatched. A task -// cannot be deleted if it has completed successfully or permanently -// failed. -func (c *Client) DeleteTask(ctx context.Context, req *taskspb.DeleteTaskRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteTask(ctx context.Context, req *taskspb.DeleteTaskRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -721,7 +939,7 @@ func (c *Client) DeleteTask(ctx context.Context, req *taskspb.DeleteTaskRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTask[0:len(c.CallOptions.DeleteTask):len(c.CallOptions.DeleteTask)], opts...) + opts = append((*c.CallOptions).DeleteTask[0:len((*c.CallOptions).DeleteTask):len((*c.CallOptions).DeleteTask)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteTask(ctx, req, settings.GRPC...) @@ -730,29 +948,7 @@ func (c *Client) DeleteTask(ctx context.Context, req *taskspb.DeleteTaskRequest, return err } -// LeaseTasks leases tasks from a pull queue for -// lease_duration. -// -// This method is invoked by the worker to obtain a lease. The -// worker must acknowledge the task via -// AcknowledgeTask after they have -// performed the work associated with the task. -// -// The payload is intended to store data that -// the worker needs to perform the work associated with the task. To -// return the payloads in the response, set -// response_view to -// FULL. -// -// A maximum of 10 qps of LeaseTasks -// requests are allowed per -// queue. RESOURCE_EXHAUSTED -// is returned when this limit is -// exceeded. RESOURCE_EXHAUSTED -// is also returned when -// max_tasks_dispatched_per_second -// is exceeded. -func (c *Client) LeaseTasks(ctx context.Context, req *taskspb.LeaseTasksRequest, opts ...gax.CallOption) (*taskspb.LeaseTasksResponse, error) { +func (c *gRPCClient) LeaseTasks(ctx context.Context, req *taskspb.LeaseTasksRequest, opts ...gax.CallOption) (*taskspb.LeaseTasksResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -760,7 +956,7 @@ func (c *Client) LeaseTasks(ctx context.Context, req *taskspb.LeaseTasksRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.LeaseTasks[0:len(c.CallOptions.LeaseTasks):len(c.CallOptions.LeaseTasks)], opts...) + opts = append((*c.CallOptions).LeaseTasks[0:len((*c.CallOptions).LeaseTasks):len((*c.CallOptions).LeaseTasks)], opts...) var resp *taskspb.LeaseTasksResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -773,20 +969,7 @@ func (c *Client) LeaseTasks(ctx context.Context, req *taskspb.LeaseTasksRequest, return resp, nil } -// AcknowledgeTask acknowledges a pull task. -// -// The worker, that is, the entity that -// leased this task must call this method -// to indicate that the work associated with the task has finished. -// -// The worker must acknowledge a task within the -// lease_duration or the lease -// will expire and the task will become available to be leased -// again. After the task is acknowledged, it will not be returned -// by a later LeaseTasks, -// GetTask, or -// ListTasks. -func (c *Client) AcknowledgeTask(ctx context.Context, req *taskspb.AcknowledgeTaskRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) AcknowledgeTask(ctx context.Context, req *taskspb.AcknowledgeTaskRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -794,7 +977,7 @@ func (c *Client) AcknowledgeTask(ctx context.Context, req *taskspb.AcknowledgeTa } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AcknowledgeTask[0:len(c.CallOptions.AcknowledgeTask):len(c.CallOptions.AcknowledgeTask)], opts...) + opts = append((*c.CallOptions).AcknowledgeTask[0:len((*c.CallOptions).AcknowledgeTask):len((*c.CallOptions).AcknowledgeTask)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.AcknowledgeTask(ctx, req, settings.GRPC...) @@ -803,12 +986,7 @@ func (c *Client) AcknowledgeTask(ctx context.Context, req *taskspb.AcknowledgeTa return err } -// RenewLease renew the current lease of a pull task. -// -// The worker can use this method to extend the lease by a new -// duration, starting from now. The new task lease will be -// returned in the task’s schedule_time. -func (c *Client) RenewLease(ctx context.Context, req *taskspb.RenewLeaseRequest, opts ...gax.CallOption) (*taskspb.Task, error) { +func (c *gRPCClient) RenewLease(ctx context.Context, req *taskspb.RenewLeaseRequest, opts ...gax.CallOption) (*taskspb.Task, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -816,7 +994,7 @@ func (c *Client) RenewLease(ctx context.Context, req *taskspb.RenewLeaseRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RenewLease[0:len(c.CallOptions.RenewLease):len(c.CallOptions.RenewLease)], opts...) + opts = append((*c.CallOptions).RenewLease[0:len((*c.CallOptions).RenewLease):len((*c.CallOptions).RenewLease)], opts...) var resp *taskspb.Task err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -829,13 +1007,7 @@ func (c *Client) RenewLease(ctx context.Context, req *taskspb.RenewLeaseRequest, return resp, nil } -// CancelLease cancel a pull task’s lease. -// -// The worker can use this method to cancel a task’s lease by -// setting its schedule_time to now. This will -// make the task available to be leased to the next caller of -// LeaseTasks. -func (c *Client) CancelLease(ctx context.Context, req *taskspb.CancelLeaseRequest, opts ...gax.CallOption) (*taskspb.Task, error) { +func (c *gRPCClient) CancelLease(ctx context.Context, req *taskspb.CancelLeaseRequest, opts ...gax.CallOption) (*taskspb.Task, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -843,7 +1015,7 @@ func (c *Client) CancelLease(ctx context.Context, req *taskspb.CancelLeaseReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CancelLease[0:len(c.CallOptions.CancelLease):len(c.CallOptions.CancelLease)], opts...) + opts = append((*c.CallOptions).CancelLease[0:len((*c.CallOptions).CancelLease):len((*c.CallOptions).CancelLease)], opts...) var resp *taskspb.Task err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -856,34 +1028,7 @@ func (c *Client) CancelLease(ctx context.Context, req *taskspb.CancelLeaseReques return resp, nil } -// RunTask forces a task to run now. -// -// When this method is called, Cloud Tasks will dispatch the task, even if -// the task is already running, the queue has reached its RateLimits or -// is PAUSED. -// -// This command is meant to be used for manual debugging. For -// example, RunTask can be used to retry a failed -// task after a fix has been made or to manually force a task to be -// dispatched now. -// -// The dispatched task is returned. That is, the task that is returned -// contains the status after the task is dispatched but -// before the task is received by its target. -// -// If Cloud Tasks receives a successful response from the task’s -// target, then the task will be deleted; otherwise the task’s -// schedule_time will be reset to the time that -// RunTask was called plus the retry delay specified -// in the queue’s RetryConfig. -// -// RunTask returns -// NOT_FOUND when it is called on a -// task that has already succeeded or permanently failed. -// -// RunTask cannot be called on a -// [pull task][google.cloud.tasks.v2beta2.PullMessage]. -func (c *Client) RunTask(ctx context.Context, req *taskspb.RunTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { +func (c *gRPCClient) RunTask(ctx context.Context, req *taskspb.RunTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -891,7 +1036,7 @@ func (c *Client) RunTask(ctx context.Context, req *taskspb.RunTaskRequest, opts } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RunTask[0:len(c.CallOptions.RunTask):len(c.CallOptions.RunTask)], opts...) + opts = append((*c.CallOptions).RunTask[0:len((*c.CallOptions).RunTask):len((*c.CallOptions).RunTask)], opts...) var resp *taskspb.Task err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/cloudtasks/apiv2beta2/cloud_tasks_client_example_test.go b/cloudtasks/apiv2beta2/cloud_tasks_client_example_test.go index e3edfa4dc88c..c2243e594b08 100644 --- a/cloudtasks/apiv2beta2/cloud_tasks_client_example_test.go +++ b/cloudtasks/apiv2beta2/cloud_tasks_client_example_test.go @@ -31,19 +31,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ListQueues() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ListQueuesRequest{ // TODO: Fill request struct fields. @@ -63,13 +63,12 @@ func ExampleClient_ListQueues() { } func ExampleClient_GetQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.GetQueueRequest{ // TODO: Fill request struct fields. @@ -83,13 +82,12 @@ func ExampleClient_GetQueue() { } func ExampleClient_CreateQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.CreateQueueRequest{ // TODO: Fill request struct fields. @@ -103,13 +101,12 @@ func ExampleClient_CreateQueue() { } func ExampleClient_UpdateQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.UpdateQueueRequest{ // TODO: Fill request struct fields. @@ -128,6 +125,7 @@ func ExampleClient_DeleteQueue() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.DeleteQueueRequest{ // TODO: Fill request struct fields. @@ -139,13 +137,12 @@ func ExampleClient_DeleteQueue() { } func ExampleClient_PurgeQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.PurgeQueueRequest{ // TODO: Fill request struct fields. @@ -159,13 +156,12 @@ func ExampleClient_PurgeQueue() { } func ExampleClient_PauseQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.PauseQueueRequest{ // TODO: Fill request struct fields. @@ -179,13 +175,12 @@ func ExampleClient_PauseQueue() { } func ExampleClient_ResumeQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ResumeQueueRequest{ // TODO: Fill request struct fields. @@ -199,13 +194,12 @@ func ExampleClient_ResumeQueue() { } func ExampleClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -219,13 +213,12 @@ func ExampleClient_GetIamPolicy() { } func ExampleClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -239,13 +232,12 @@ func ExampleClient_SetIamPolicy() { } func ExampleClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. @@ -259,14 +251,12 @@ func ExampleClient_TestIamPermissions() { } func ExampleClient_ListTasks() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ListTasksRequest{ // TODO: Fill request struct fields. @@ -286,13 +276,12 @@ func ExampleClient_ListTasks() { } func ExampleClient_GetTask() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.GetTaskRequest{ // TODO: Fill request struct fields. @@ -306,13 +295,12 @@ func ExampleClient_GetTask() { } func ExampleClient_CreateTask() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.CreateTaskRequest{ // TODO: Fill request struct fields. @@ -331,6 +319,7 @@ func ExampleClient_DeleteTask() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.DeleteTaskRequest{ // TODO: Fill request struct fields. @@ -342,13 +331,12 @@ func ExampleClient_DeleteTask() { } func ExampleClient_LeaseTasks() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.LeaseTasksRequest{ // TODO: Fill request struct fields. @@ -367,6 +355,7 @@ func ExampleClient_AcknowledgeTask() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.AcknowledgeTaskRequest{ // TODO: Fill request struct fields. @@ -378,13 +367,12 @@ func ExampleClient_AcknowledgeTask() { } func ExampleClient_RenewLease() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.RenewLeaseRequest{ // TODO: Fill request struct fields. @@ -398,13 +386,12 @@ func ExampleClient_RenewLease() { } func ExampleClient_CancelLease() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.CancelLeaseRequest{ // TODO: Fill request struct fields. @@ -418,13 +405,12 @@ func ExampleClient_CancelLease() { } func ExampleClient_RunTask() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.RunTaskRequest{ // TODO: Fill request struct fields. diff --git a/cloudtasks/apiv2beta2/doc.go b/cloudtasks/apiv2beta2/doc.go index 7619c4692342..1d470ec0e489 100644 --- a/cloudtasks/apiv2beta2/doc.go +++ b/cloudtasks/apiv2beta2/doc.go @@ -19,6 +19,8 @@ // // Manages the execution of large numbers of distributed requests. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -28,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package cloudtasks // import "cloud.google.com/go/cloudtasks/apiv2beta2" import ( @@ -48,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/cloudtasks/apiv2beta3/cloud_tasks_client.go b/cloudtasks/apiv2beta3/cloud_tasks_client.go index 2b1d3490bce1..65a983a8eb76 100644 --- a/cloudtasks/apiv2beta3/cloud_tasks_client.go +++ b/cloudtasks/apiv2beta3/cloud_tasks_client.go @@ -58,7 +58,7 @@ type CallOptions struct { RunTask []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudtasks.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudtasks.mtls.googleapis.com:443"), @@ -179,33 +179,296 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Tasks API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListQueues(context.Context, *taskspb.ListQueuesRequest, ...gax.CallOption) *QueueIterator + GetQueue(context.Context, *taskspb.GetQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + CreateQueue(context.Context, *taskspb.CreateQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + UpdateQueue(context.Context, *taskspb.UpdateQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + DeleteQueue(context.Context, *taskspb.DeleteQueueRequest, ...gax.CallOption) error + PurgeQueue(context.Context, *taskspb.PurgeQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + PauseQueue(context.Context, *taskspb.PauseQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + ResumeQueue(context.Context, *taskspb.ResumeQueueRequest, ...gax.CallOption) (*taskspb.Queue, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) + ListTasks(context.Context, *taskspb.ListTasksRequest, ...gax.CallOption) *TaskIterator + GetTask(context.Context, *taskspb.GetTaskRequest, ...gax.CallOption) (*taskspb.Task, error) + CreateTask(context.Context, *taskspb.CreateTaskRequest, ...gax.CallOption) (*taskspb.Task, error) + DeleteTask(context.Context, *taskspb.DeleteTaskRequest, ...gax.CallOption) error + RunTask(context.Context, *taskspb.RunTaskRequest, ...gax.CallOption) (*taskspb.Task, error) +} + // Client is a client for interacting with Cloud Tasks API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Cloud Tasks allows developers to manage the execution of background +// work in their applications. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListQueues lists queues. +// +// Queues are returned in lexicographical order. +func (c *Client) ListQueues(ctx context.Context, req *taskspb.ListQueuesRequest, opts ...gax.CallOption) *QueueIterator { + return c.internalClient.ListQueues(ctx, req, opts...) +} + +// GetQueue gets a queue. +func (c *Client) GetQueue(ctx context.Context, req *taskspb.GetQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.GetQueue(ctx, req, opts...) +} + +// CreateQueue creates a queue. +// +// Queues created with this method allow tasks to live for a maximum of 31 +// days. After a task is 31 days old, the task will be deleted regardless of whether +// it was dispatched or not. +// +// WARNING: Using this method may have unintended side effects if you are +// using an App Engine queue.yaml or queue.xml file to manage your queues. +// Read +// Overview of Queue Management and +// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using +// this method. +func (c *Client) CreateQueue(ctx context.Context, req *taskspb.CreateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.CreateQueue(ctx, req, opts...) +} + +// UpdateQueue updates a queue. +// +// This method creates the queue if it does not exist and updates +// the queue if it does exist. +// +// Queues created with this method allow tasks to live for a maximum of 31 +// days. After a task is 31 days old, the task will be deleted regardless of whether +// it was dispatched or not. +// +// WARNING: Using this method may have unintended side effects if you are +// using an App Engine queue.yaml or queue.xml file to manage your queues. +// Read +// Overview of Queue Management and +// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using +// this method. +func (c *Client) UpdateQueue(ctx context.Context, req *taskspb.UpdateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.UpdateQueue(ctx, req, opts...) +} + +// DeleteQueue deletes a queue. +// +// This command will delete the queue even if it has tasks in it. +// +// Note: If you delete a queue, a queue with the same name can’t be created +// for 7 days. +// +// WARNING: Using this method may have unintended side effects if you are +// using an App Engine queue.yaml or queue.xml file to manage your queues. +// Read +// Overview of Queue Management and +// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using +// this method. +func (c *Client) DeleteQueue(ctx context.Context, req *taskspb.DeleteQueueRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteQueue(ctx, req, opts...) +} + +// PurgeQueue purges a queue by deleting all of its tasks. +// +// All tasks created before this method is called are permanently deleted. +// +// Purge operations can take up to one minute to take effect. Tasks +// might be dispatched before the purge takes effect. A purge is irreversible. +func (c *Client) PurgeQueue(ctx context.Context, req *taskspb.PurgeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.PurgeQueue(ctx, req, opts...) +} + +// PauseQueue pauses the queue. +// +// If a queue is paused then the system will stop dispatching tasks +// until the queue is resumed via +// ResumeQueue. Tasks can still be added +// when the queue is paused. A queue is paused if its +// state is PAUSED. +func (c *Client) PauseQueue(ctx context.Context, req *taskspb.PauseQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.PauseQueue(ctx, req, opts...) +} + +// ResumeQueue resume a queue. +// +// This method resumes a queue after it has been +// PAUSED or +// DISABLED. The state of a queue is stored +// in the queue’s state; after calling this method it +// will be set to RUNNING. +// +// WARNING: Resuming many high-QPS queues at the same time can +// lead to target overloading. If you are resuming high-QPS +// queues, follow the 500/50/5 pattern described in +// Managing Cloud Tasks Scaling +// Risks (at https://cloud.google.com/tasks/docs/manage-cloud-task-scaling). +func (c *Client) ResumeQueue(ctx context.Context, req *taskspb.ResumeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { + return c.internalClient.ResumeQueue(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy for a Queue. +// Returns an empty policy if the resource exists and does not have a policy +// set. +// +// Authorization requires the following +// Google IAM (at https://cloud.google.com/iam) permission on the specified +// resource parent: +// +// cloudtasks.queues.getIamPolicy +func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// SetIamPolicy sets the access control policy for a Queue. Replaces any existing +// policy. +// +// Note: The Cloud Console does not check queue-level IAM permissions yet. +// Project-level permissions are required to use the Cloud Console. +// +// Authorization requires the following +// Google IAM (at https://cloud.google.com/iam) permission on the specified +// resource parent: +// +// cloudtasks.queues.setIamPolicy +func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns permissions that a caller has on a Queue. +// If the resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building permission-aware +// UIs and command-line tools, not for authorization checking. This operation +// may “fail open” without warning. +func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// ListTasks lists the tasks in a queue. +// +// By default, only the BASIC view is retrieved +// due to performance considerations; +// response_view controls the +// subset of information which is returned. +// +// The tasks may be returned in any order. The ordering may change at any +// time. +func (c *Client) ListTasks(ctx context.Context, req *taskspb.ListTasksRequest, opts ...gax.CallOption) *TaskIterator { + return c.internalClient.ListTasks(ctx, req, opts...) +} + +// GetTask gets a task. +func (c *Client) GetTask(ctx context.Context, req *taskspb.GetTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { + return c.internalClient.GetTask(ctx, req, opts...) +} + +// CreateTask creates a task and adds it to a queue. +// +// Tasks cannot be updated after creation; there is no UpdateTask command. +// +// The maximum task size is 100KB. +func (c *Client) CreateTask(ctx context.Context, req *taskspb.CreateTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { + return c.internalClient.CreateTask(ctx, req, opts...) +} + +// DeleteTask deletes a task. +// +// A task can be deleted if it is scheduled or dispatched. A task +// cannot be deleted if it has executed successfully or permanently +// failed. +func (c *Client) DeleteTask(ctx context.Context, req *taskspb.DeleteTaskRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTask(ctx, req, opts...) +} + +// RunTask forces a task to run now. +// +// When this method is called, Cloud Tasks will dispatch the task, even if +// the task is already running, the queue has reached its RateLimits or +// is PAUSED. +// +// This command is meant to be used for manual debugging. For +// example, RunTask can be used to retry a failed +// task after a fix has been made or to manually force a task to be +// dispatched now. +// +// The dispatched task is returned. That is, the task that is returned +// contains the status after the task is dispatched but +// before the task is received by its target. +// +// If Cloud Tasks receives a successful response from the task’s +// target, then the task will be deleted; otherwise the task’s +// schedule_time will be reset to the time that +// RunTask was called plus the retry delay specified +// in the queue’s RetryConfig. +// +// RunTask returns +// NOT_FOUND when it is called on a +// task that has already succeeded or permanently failed. +func (c *Client) RunTask(ctx context.Context, req *taskspb.RunTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { + return c.internalClient.RunTask(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud Tasks API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client taskspb.CloudTasksClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new cloud tasks client. +// NewClient creates a new cloud tasks client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Cloud Tasks allows developers to manage the execution of background // work in their applications. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -223,47 +486,47 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: taskspb.NewCloudTasksClient(connPool), + client: taskspb.NewCloudTasksClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListQueues lists queues. -// -// Queues are returned in lexicographical order. -func (c *Client) ListQueues(ctx context.Context, req *taskspb.ListQueuesRequest, opts ...gax.CallOption) *QueueIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ListQueues(ctx context.Context, req *taskspb.ListQueuesRequest, opts ...gax.CallOption) *QueueIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListQueues[0:len(c.CallOptions.ListQueues):len(c.CallOptions.ListQueues)], opts...) + opts = append((*c.CallOptions).ListQueues[0:len((*c.CallOptions).ListQueues):len((*c.CallOptions).ListQueues)], opts...) it := &QueueIterator{} req = proto.Clone(req).(*taskspb.ListQueuesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*taskspb.Queue, string, error) { @@ -300,8 +563,7 @@ func (c *Client) ListQueues(ctx context.Context, req *taskspb.ListQueuesRequest, return it } -// GetQueue gets a queue. -func (c *Client) GetQueue(ctx context.Context, req *taskspb.GetQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) GetQueue(ctx context.Context, req *taskspb.GetQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -309,7 +571,7 @@ func (c *Client) GetQueue(ctx context.Context, req *taskspb.GetQueueRequest, opt } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetQueue[0:len(c.CallOptions.GetQueue):len(c.CallOptions.GetQueue)], opts...) + opts = append((*c.CallOptions).GetQueue[0:len((*c.CallOptions).GetQueue):len((*c.CallOptions).GetQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -322,19 +584,7 @@ func (c *Client) GetQueue(ctx context.Context, req *taskspb.GetQueueRequest, opt return resp, nil } -// CreateQueue creates a queue. -// -// Queues created with this method allow tasks to live for a maximum of 31 -// days. After a task is 31 days old, the task will be deleted regardless of whether -// it was dispatched or not. -// -// WARNING: Using this method may have unintended side effects if you are -// using an App Engine queue.yaml or queue.xml file to manage your queues. -// Read -// Overview of Queue Management and -// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using -// this method. -func (c *Client) CreateQueue(ctx context.Context, req *taskspb.CreateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) CreateQueue(ctx context.Context, req *taskspb.CreateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -342,7 +592,7 @@ func (c *Client) CreateQueue(ctx context.Context, req *taskspb.CreateQueueReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateQueue[0:len(c.CallOptions.CreateQueue):len(c.CallOptions.CreateQueue)], opts...) + opts = append((*c.CallOptions).CreateQueue[0:len((*c.CallOptions).CreateQueue):len((*c.CallOptions).CreateQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -355,22 +605,7 @@ func (c *Client) CreateQueue(ctx context.Context, req *taskspb.CreateQueueReques return resp, nil } -// UpdateQueue updates a queue. -// -// This method creates the queue if it does not exist and updates -// the queue if it does exist. -// -// Queues created with this method allow tasks to live for a maximum of 31 -// days. After a task is 31 days old, the task will be deleted regardless of whether -// it was dispatched or not. -// -// WARNING: Using this method may have unintended side effects if you are -// using an App Engine queue.yaml or queue.xml file to manage your queues. -// Read -// Overview of Queue Management and -// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using -// this method. -func (c *Client) UpdateQueue(ctx context.Context, req *taskspb.UpdateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) UpdateQueue(ctx context.Context, req *taskspb.UpdateQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -378,7 +613,7 @@ func (c *Client) UpdateQueue(ctx context.Context, req *taskspb.UpdateQueueReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "queue.name", url.QueryEscape(req.GetQueue().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateQueue[0:len(c.CallOptions.UpdateQueue):len(c.CallOptions.UpdateQueue)], opts...) + opts = append((*c.CallOptions).UpdateQueue[0:len((*c.CallOptions).UpdateQueue):len((*c.CallOptions).UpdateQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -391,20 +626,7 @@ func (c *Client) UpdateQueue(ctx context.Context, req *taskspb.UpdateQueueReques return resp, nil } -// DeleteQueue deletes a queue. -// -// This command will delete the queue even if it has tasks in it. -// -// Note: If you delete a queue, a queue with the same name can’t be created -// for 7 days. -// -// WARNING: Using this method may have unintended side effects if you are -// using an App Engine queue.yaml or queue.xml file to manage your queues. -// Read -// Overview of Queue Management and -// queue.yaml (at https://cloud.google.com/tasks/docs/queue-yaml) before using -// this method. -func (c *Client) DeleteQueue(ctx context.Context, req *taskspb.DeleteQueueRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteQueue(ctx context.Context, req *taskspb.DeleteQueueRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -412,7 +634,7 @@ func (c *Client) DeleteQueue(ctx context.Context, req *taskspb.DeleteQueueReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteQueue[0:len(c.CallOptions.DeleteQueue):len(c.CallOptions.DeleteQueue)], opts...) + opts = append((*c.CallOptions).DeleteQueue[0:len((*c.CallOptions).DeleteQueue):len((*c.CallOptions).DeleteQueue)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteQueue(ctx, req, settings.GRPC...) @@ -421,13 +643,7 @@ func (c *Client) DeleteQueue(ctx context.Context, req *taskspb.DeleteQueueReques return err } -// PurgeQueue purges a queue by deleting all of its tasks. -// -// All tasks created before this method is called are permanently deleted. -// -// Purge operations can take up to one minute to take effect. Tasks -// might be dispatched before the purge takes effect. A purge is irreversible. -func (c *Client) PurgeQueue(ctx context.Context, req *taskspb.PurgeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) PurgeQueue(ctx context.Context, req *taskspb.PurgeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -435,7 +651,7 @@ func (c *Client) PurgeQueue(ctx context.Context, req *taskspb.PurgeQueueRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PurgeQueue[0:len(c.CallOptions.PurgeQueue):len(c.CallOptions.PurgeQueue)], opts...) + opts = append((*c.CallOptions).PurgeQueue[0:len((*c.CallOptions).PurgeQueue):len((*c.CallOptions).PurgeQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -448,14 +664,7 @@ func (c *Client) PurgeQueue(ctx context.Context, req *taskspb.PurgeQueueRequest, return resp, nil } -// PauseQueue pauses the queue. -// -// If a queue is paused then the system will stop dispatching tasks -// until the queue is resumed via -// ResumeQueue. Tasks can still be added -// when the queue is paused. A queue is paused if its -// state is PAUSED. -func (c *Client) PauseQueue(ctx context.Context, req *taskspb.PauseQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) PauseQueue(ctx context.Context, req *taskspb.PauseQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -463,7 +672,7 @@ func (c *Client) PauseQueue(ctx context.Context, req *taskspb.PauseQueueRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PauseQueue[0:len(c.CallOptions.PauseQueue):len(c.CallOptions.PauseQueue)], opts...) + opts = append((*c.CallOptions).PauseQueue[0:len((*c.CallOptions).PauseQueue):len((*c.CallOptions).PauseQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -476,20 +685,7 @@ func (c *Client) PauseQueue(ctx context.Context, req *taskspb.PauseQueueRequest, return resp, nil } -// ResumeQueue resume a queue. -// -// This method resumes a queue after it has been -// PAUSED or -// DISABLED. The state of a queue is stored -// in the queue’s state; after calling this method it -// will be set to RUNNING. -// -// WARNING: Resuming many high-QPS queues at the same time can -// lead to target overloading. If you are resuming high-QPS -// queues, follow the 500/50/5 pattern described in -// Managing Cloud Tasks Scaling -// Risks (at https://cloud.google.com/tasks/docs/manage-cloud-task-scaling). -func (c *Client) ResumeQueue(ctx context.Context, req *taskspb.ResumeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { +func (c *gRPCClient) ResumeQueue(ctx context.Context, req *taskspb.ResumeQueueRequest, opts ...gax.CallOption) (*taskspb.Queue, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -497,7 +693,7 @@ func (c *Client) ResumeQueue(ctx context.Context, req *taskspb.ResumeQueueReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ResumeQueue[0:len(c.CallOptions.ResumeQueue):len(c.CallOptions.ResumeQueue)], opts...) + opts = append((*c.CallOptions).ResumeQueue[0:len((*c.CallOptions).ResumeQueue):len((*c.CallOptions).ResumeQueue)], opts...) var resp *taskspb.Queue err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -510,16 +706,7 @@ func (c *Client) ResumeQueue(ctx context.Context, req *taskspb.ResumeQueueReques return resp, nil } -// GetIamPolicy gets the access control policy for a Queue. -// Returns an empty policy if the resource exists and does not have a policy -// set. -// -// Authorization requires the following -// Google IAM (at https://cloud.google.com/iam) permission on the specified -// resource parent: -// -// cloudtasks.queues.getIamPolicy -func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -527,7 +714,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -540,18 +727,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques return resp, nil } -// SetIamPolicy sets the access control policy for a Queue. Replaces any existing -// policy. -// -// Note: The Cloud Console does not check queue-level IAM permissions yet. -// Project-level permissions are required to use the Cloud Console. -// -// Authorization requires the following -// Google IAM (at https://cloud.google.com/iam) permission on the specified -// resource parent: -// -// cloudtasks.queues.setIamPolicy -func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -559,7 +735,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -572,14 +748,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques return resp, nil } -// TestIamPermissions returns permissions that a caller has on a Queue. -// If the resource does not exist, this will return an empty set of -// permissions, not a NOT_FOUND error. -// -// Note: This operation is designed to be used for building permission-aware -// UIs and command-line tools, not for authorization checking. This operation -// may “fail open” without warning. -func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *gRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -587,7 +756,7 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -600,19 +769,10 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi return resp, nil } -// ListTasks lists the tasks in a queue. -// -// By default, only the BASIC view is retrieved -// due to performance considerations; -// response_view controls the -// subset of information which is returned. -// -// The tasks may be returned in any order. The ordering may change at any -// time. -func (c *Client) ListTasks(ctx context.Context, req *taskspb.ListTasksRequest, opts ...gax.CallOption) *TaskIterator { +func (c *gRPCClient) ListTasks(ctx context.Context, req *taskspb.ListTasksRequest, opts ...gax.CallOption) *TaskIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTasks[0:len(c.CallOptions.ListTasks):len(c.CallOptions.ListTasks)], opts...) + opts = append((*c.CallOptions).ListTasks[0:len((*c.CallOptions).ListTasks):len((*c.CallOptions).ListTasks)], opts...) it := &TaskIterator{} req = proto.Clone(req).(*taskspb.ListTasksRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*taskspb.Task, string, error) { @@ -649,8 +809,7 @@ func (c *Client) ListTasks(ctx context.Context, req *taskspb.ListTasksRequest, o return it } -// GetTask gets a task. -func (c *Client) GetTask(ctx context.Context, req *taskspb.GetTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { +func (c *gRPCClient) GetTask(ctx context.Context, req *taskspb.GetTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -658,7 +817,7 @@ func (c *Client) GetTask(ctx context.Context, req *taskspb.GetTaskRequest, opts } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTask[0:len(c.CallOptions.GetTask):len(c.CallOptions.GetTask)], opts...) + opts = append((*c.CallOptions).GetTask[0:len((*c.CallOptions).GetTask):len((*c.CallOptions).GetTask)], opts...) var resp *taskspb.Task err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -671,12 +830,7 @@ func (c *Client) GetTask(ctx context.Context, req *taskspb.GetTaskRequest, opts return resp, nil } -// CreateTask creates a task and adds it to a queue. -// -// Tasks cannot be updated after creation; there is no UpdateTask command. -// -// The maximum task size is 100KB. -func (c *Client) CreateTask(ctx context.Context, req *taskspb.CreateTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { +func (c *gRPCClient) CreateTask(ctx context.Context, req *taskspb.CreateTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -684,7 +838,7 @@ func (c *Client) CreateTask(ctx context.Context, req *taskspb.CreateTaskRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTask[0:len(c.CallOptions.CreateTask):len(c.CallOptions.CreateTask)], opts...) + opts = append((*c.CallOptions).CreateTask[0:len((*c.CallOptions).CreateTask):len((*c.CallOptions).CreateTask)], opts...) var resp *taskspb.Task err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -697,12 +851,7 @@ func (c *Client) CreateTask(ctx context.Context, req *taskspb.CreateTaskRequest, return resp, nil } -// DeleteTask deletes a task. -// -// A task can be deleted if it is scheduled or dispatched. A task -// cannot be deleted if it has executed successfully or permanently -// failed. -func (c *Client) DeleteTask(ctx context.Context, req *taskspb.DeleteTaskRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteTask(ctx context.Context, req *taskspb.DeleteTaskRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -710,7 +859,7 @@ func (c *Client) DeleteTask(ctx context.Context, req *taskspb.DeleteTaskRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTask[0:len(c.CallOptions.DeleteTask):len(c.CallOptions.DeleteTask)], opts...) + opts = append((*c.CallOptions).DeleteTask[0:len((*c.CallOptions).DeleteTask):len((*c.CallOptions).DeleteTask)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteTask(ctx, req, settings.GRPC...) @@ -719,31 +868,7 @@ func (c *Client) DeleteTask(ctx context.Context, req *taskspb.DeleteTaskRequest, return err } -// RunTask forces a task to run now. -// -// When this method is called, Cloud Tasks will dispatch the task, even if -// the task is already running, the queue has reached its RateLimits or -// is PAUSED. -// -// This command is meant to be used for manual debugging. For -// example, RunTask can be used to retry a failed -// task after a fix has been made or to manually force a task to be -// dispatched now. -// -// The dispatched task is returned. That is, the task that is returned -// contains the status after the task is dispatched but -// before the task is received by its target. -// -// If Cloud Tasks receives a successful response from the task’s -// target, then the task will be deleted; otherwise the task’s -// schedule_time will be reset to the time that -// RunTask was called plus the retry delay specified -// in the queue’s RetryConfig. -// -// RunTask returns -// NOT_FOUND when it is called on a -// task that has already succeeded or permanently failed. -func (c *Client) RunTask(ctx context.Context, req *taskspb.RunTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { +func (c *gRPCClient) RunTask(ctx context.Context, req *taskspb.RunTaskRequest, opts ...gax.CallOption) (*taskspb.Task, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -751,7 +876,7 @@ func (c *Client) RunTask(ctx context.Context, req *taskspb.RunTaskRequest, opts } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RunTask[0:len(c.CallOptions.RunTask):len(c.CallOptions.RunTask)], opts...) + opts = append((*c.CallOptions).RunTask[0:len((*c.CallOptions).RunTask):len((*c.CallOptions).RunTask)], opts...) var resp *taskspb.Task err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/cloudtasks/apiv2beta3/cloud_tasks_client_example_test.go b/cloudtasks/apiv2beta3/cloud_tasks_client_example_test.go index 344d94025236..fa0e16fb2a63 100644 --- a/cloudtasks/apiv2beta3/cloud_tasks_client_example_test.go +++ b/cloudtasks/apiv2beta3/cloud_tasks_client_example_test.go @@ -31,19 +31,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ListQueues() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ListQueuesRequest{ // TODO: Fill request struct fields. @@ -63,13 +63,12 @@ func ExampleClient_ListQueues() { } func ExampleClient_GetQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.GetQueueRequest{ // TODO: Fill request struct fields. @@ -83,13 +82,12 @@ func ExampleClient_GetQueue() { } func ExampleClient_CreateQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.CreateQueueRequest{ // TODO: Fill request struct fields. @@ -103,13 +101,12 @@ func ExampleClient_CreateQueue() { } func ExampleClient_UpdateQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.UpdateQueueRequest{ // TODO: Fill request struct fields. @@ -128,6 +125,7 @@ func ExampleClient_DeleteQueue() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.DeleteQueueRequest{ // TODO: Fill request struct fields. @@ -139,13 +137,12 @@ func ExampleClient_DeleteQueue() { } func ExampleClient_PurgeQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.PurgeQueueRequest{ // TODO: Fill request struct fields. @@ -159,13 +156,12 @@ func ExampleClient_PurgeQueue() { } func ExampleClient_PauseQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.PauseQueueRequest{ // TODO: Fill request struct fields. @@ -179,13 +175,12 @@ func ExampleClient_PauseQueue() { } func ExampleClient_ResumeQueue() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ResumeQueueRequest{ // TODO: Fill request struct fields. @@ -199,13 +194,12 @@ func ExampleClient_ResumeQueue() { } func ExampleClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -219,13 +213,12 @@ func ExampleClient_GetIamPolicy() { } func ExampleClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -239,13 +232,12 @@ func ExampleClient_SetIamPolicy() { } func ExampleClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. @@ -259,14 +251,12 @@ func ExampleClient_TestIamPermissions() { } func ExampleClient_ListTasks() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ListTasksRequest{ // TODO: Fill request struct fields. @@ -286,13 +276,12 @@ func ExampleClient_ListTasks() { } func ExampleClient_GetTask() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.GetTaskRequest{ // TODO: Fill request struct fields. @@ -306,13 +295,12 @@ func ExampleClient_GetTask() { } func ExampleClient_CreateTask() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.CreateTaskRequest{ // TODO: Fill request struct fields. @@ -331,6 +319,7 @@ func ExampleClient_DeleteTask() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.DeleteTaskRequest{ // TODO: Fill request struct fields. @@ -342,13 +331,12 @@ func ExampleClient_DeleteTask() { } func ExampleClient_RunTask() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.RunTaskRequest{ // TODO: Fill request struct fields. diff --git a/cloudtasks/apiv2beta3/doc.go b/cloudtasks/apiv2beta3/doc.go index 0acc056926ce..f5e0363ebebd 100644 --- a/cloudtasks/apiv2beta3/doc.go +++ b/cloudtasks/apiv2beta3/doc.go @@ -19,6 +19,8 @@ // // Manages the execution of large numbers of distributed requests. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -28,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package cloudtasks // import "cloud.google.com/go/cloudtasks/apiv2beta3" import ( @@ -48,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/container/apiv1/cluster_manager_client.go b/container/apiv1/cluster_manager_client.go index 2538208f2da3..8edb5a43a742 100644 --- a/container/apiv1/cluster_manager_client.go +++ b/container/apiv1/cluster_manager_client.go @@ -73,7 +73,7 @@ type ClusterManagerCallOptions struct { ListUsableSubnetworks []gax.CallOption } -func defaultClusterManagerClientOptions() []option.ClientOption { +func defaultClusterManagerGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("container.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("container.mtls.googleapis.com:443"), @@ -221,32 +221,298 @@ func defaultClusterManagerCallOptions() *ClusterManagerCallOptions { } } +// internalClusterManagerClient is an interface that defines the methods availaible from Kubernetes Engine API. +type internalClusterManagerClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListClusters(context.Context, *containerpb.ListClustersRequest, ...gax.CallOption) (*containerpb.ListClustersResponse, error) + GetCluster(context.Context, *containerpb.GetClusterRequest, ...gax.CallOption) (*containerpb.Cluster, error) + CreateCluster(context.Context, *containerpb.CreateClusterRequest, ...gax.CallOption) (*containerpb.Operation, error) + UpdateCluster(context.Context, *containerpb.UpdateClusterRequest, ...gax.CallOption) (*containerpb.Operation, error) + UpdateNodePool(context.Context, *containerpb.UpdateNodePoolRequest, ...gax.CallOption) (*containerpb.Operation, error) + SetNodePoolAutoscaling(context.Context, *containerpb.SetNodePoolAutoscalingRequest, ...gax.CallOption) (*containerpb.Operation, error) + SetLoggingService(context.Context, *containerpb.SetLoggingServiceRequest, ...gax.CallOption) (*containerpb.Operation, error) + SetMonitoringService(context.Context, *containerpb.SetMonitoringServiceRequest, ...gax.CallOption) (*containerpb.Operation, error) + SetAddonsConfig(context.Context, *containerpb.SetAddonsConfigRequest, ...gax.CallOption) (*containerpb.Operation, error) + SetLocations(context.Context, *containerpb.SetLocationsRequest, ...gax.CallOption) (*containerpb.Operation, error) + UpdateMaster(context.Context, *containerpb.UpdateMasterRequest, ...gax.CallOption) (*containerpb.Operation, error) + SetMasterAuth(context.Context, *containerpb.SetMasterAuthRequest, ...gax.CallOption) (*containerpb.Operation, error) + DeleteCluster(context.Context, *containerpb.DeleteClusterRequest, ...gax.CallOption) (*containerpb.Operation, error) + ListOperations(context.Context, *containerpb.ListOperationsRequest, ...gax.CallOption) (*containerpb.ListOperationsResponse, error) + GetOperation(context.Context, *containerpb.GetOperationRequest, ...gax.CallOption) (*containerpb.Operation, error) + CancelOperation(context.Context, *containerpb.CancelOperationRequest, ...gax.CallOption) error + GetServerConfig(context.Context, *containerpb.GetServerConfigRequest, ...gax.CallOption) (*containerpb.ServerConfig, error) + GetJSONWebKeys(context.Context, *containerpb.GetJSONWebKeysRequest, ...gax.CallOption) (*containerpb.GetJSONWebKeysResponse, error) + ListNodePools(context.Context, *containerpb.ListNodePoolsRequest, ...gax.CallOption) (*containerpb.ListNodePoolsResponse, error) + GetNodePool(context.Context, *containerpb.GetNodePoolRequest, ...gax.CallOption) (*containerpb.NodePool, error) + CreateNodePool(context.Context, *containerpb.CreateNodePoolRequest, ...gax.CallOption) (*containerpb.Operation, error) + DeleteNodePool(context.Context, *containerpb.DeleteNodePoolRequest, ...gax.CallOption) (*containerpb.Operation, error) + RollbackNodePoolUpgrade(context.Context, *containerpb.RollbackNodePoolUpgradeRequest, ...gax.CallOption) (*containerpb.Operation, error) + SetNodePoolManagement(context.Context, *containerpb.SetNodePoolManagementRequest, ...gax.CallOption) (*containerpb.Operation, error) + SetLabels(context.Context, *containerpb.SetLabelsRequest, ...gax.CallOption) (*containerpb.Operation, error) + SetLegacyAbac(context.Context, *containerpb.SetLegacyAbacRequest, ...gax.CallOption) (*containerpb.Operation, error) + StartIPRotation(context.Context, *containerpb.StartIPRotationRequest, ...gax.CallOption) (*containerpb.Operation, error) + CompleteIPRotation(context.Context, *containerpb.CompleteIPRotationRequest, ...gax.CallOption) (*containerpb.Operation, error) + SetNodePoolSize(context.Context, *containerpb.SetNodePoolSizeRequest, ...gax.CallOption) (*containerpb.Operation, error) + SetNetworkPolicy(context.Context, *containerpb.SetNetworkPolicyRequest, ...gax.CallOption) (*containerpb.Operation, error) + SetMaintenancePolicy(context.Context, *containerpb.SetMaintenancePolicyRequest, ...gax.CallOption) (*containerpb.Operation, error) + ListUsableSubnetworks(context.Context, *containerpb.ListUsableSubnetworksRequest, ...gax.CallOption) *UsableSubnetworkIterator +} + // ClusterManagerClient is a client for interacting with Kubernetes Engine API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Google Kubernetes Engine Cluster Manager v1 type ClusterManagerClient struct { + // The internal transport-dependent client. + internalClient internalClusterManagerClient + + // The call options for this service. + CallOptions *ClusterManagerCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ClusterManagerClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ClusterManagerClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ClusterManagerClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListClusters lists all clusters owned by a project in either the specified zone or all +// zones. +func (c *ClusterManagerClient) ListClusters(ctx context.Context, req *containerpb.ListClustersRequest, opts ...gax.CallOption) (*containerpb.ListClustersResponse, error) { + return c.internalClient.ListClusters(ctx, req, opts...) +} + +// GetCluster gets the details of a specific cluster. +func (c *ClusterManagerClient) GetCluster(ctx context.Context, req *containerpb.GetClusterRequest, opts ...gax.CallOption) (*containerpb.Cluster, error) { + return c.internalClient.GetCluster(ctx, req, opts...) +} + +// CreateCluster creates a cluster, consisting of the specified number and type of Google +// Compute Engine instances. +// +// By default, the cluster is created in the project’s +// default +// network (at https://cloud.google.com/compute/docs/networks-and-firewalls#networks). +// +// One firewall is added for the cluster. After cluster creation, +// the Kubelet creates routes for each node to allow the containers +// on that node to communicate with all other instances in the +// cluster. +// +// Finally, an entry is added to the project’s global metadata indicating +// which CIDR range the cluster is using. +func (c *ClusterManagerClient) CreateCluster(ctx context.Context, req *containerpb.CreateClusterRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.CreateCluster(ctx, req, opts...) +} + +// UpdateCluster updates the settings of a specific cluster. +func (c *ClusterManagerClient) UpdateCluster(ctx context.Context, req *containerpb.UpdateClusterRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.UpdateCluster(ctx, req, opts...) +} + +// UpdateNodePool updates the version and/or image type for the specified node pool. +func (c *ClusterManagerClient) UpdateNodePool(ctx context.Context, req *containerpb.UpdateNodePoolRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.UpdateNodePool(ctx, req, opts...) +} + +// SetNodePoolAutoscaling sets the autoscaling settings for the specified node pool. +func (c *ClusterManagerClient) SetNodePoolAutoscaling(ctx context.Context, req *containerpb.SetNodePoolAutoscalingRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.SetNodePoolAutoscaling(ctx, req, opts...) +} + +// SetLoggingService sets the logging service for a specific cluster. +func (c *ClusterManagerClient) SetLoggingService(ctx context.Context, req *containerpb.SetLoggingServiceRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.SetLoggingService(ctx, req, opts...) +} + +// SetMonitoringService sets the monitoring service for a specific cluster. +func (c *ClusterManagerClient) SetMonitoringService(ctx context.Context, req *containerpb.SetMonitoringServiceRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.SetMonitoringService(ctx, req, opts...) +} + +// SetAddonsConfig sets the addons for a specific cluster. +func (c *ClusterManagerClient) SetAddonsConfig(ctx context.Context, req *containerpb.SetAddonsConfigRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.SetAddonsConfig(ctx, req, opts...) +} + +// SetLocations sets the locations for a specific cluster. +// Deprecated. Use +// projects.locations.clusters.update (at https://cloud.google.com/kubernetes-engine/docs/reference/rest/v1/projects.locations.clusters/update) +// instead. +// +// Deprecated: SetLocations may be removed in a future version. +func (c *ClusterManagerClient) SetLocations(ctx context.Context, req *containerpb.SetLocationsRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.SetLocations(ctx, req, opts...) +} + +// UpdateMaster updates the master for a specific cluster. +func (c *ClusterManagerClient) UpdateMaster(ctx context.Context, req *containerpb.UpdateMasterRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.UpdateMaster(ctx, req, opts...) +} + +// SetMasterAuth sets master auth materials. Currently supports changing the admin password +// or a specific cluster, either via password generation or explicitly setting +// the password. +func (c *ClusterManagerClient) SetMasterAuth(ctx context.Context, req *containerpb.SetMasterAuthRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.SetMasterAuth(ctx, req, opts...) +} + +// DeleteCluster deletes the cluster, including the Kubernetes endpoint and all worker +// nodes. +// +// Firewalls and routes that were configured during cluster creation +// are also deleted. +// +// Other Google Compute Engine resources that might be in use by the cluster, +// such as load balancer resources, are not deleted if they weren’t present +// when the cluster was initially created. +func (c *ClusterManagerClient) DeleteCluster(ctx context.Context, req *containerpb.DeleteClusterRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.DeleteCluster(ctx, req, opts...) +} + +// ListOperations lists all operations in a project in a specific zone or all zones. +func (c *ClusterManagerClient) ListOperations(ctx context.Context, req *containerpb.ListOperationsRequest, opts ...gax.CallOption) (*containerpb.ListOperationsResponse, error) { + return c.internalClient.ListOperations(ctx, req, opts...) +} + +// GetOperation gets the specified operation. +func (c *ClusterManagerClient) GetOperation(ctx context.Context, req *containerpb.GetOperationRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.GetOperation(ctx, req, opts...) +} + +// CancelOperation cancels the specified operation. +func (c *ClusterManagerClient) CancelOperation(ctx context.Context, req *containerpb.CancelOperationRequest, opts ...gax.CallOption) error { + return c.internalClient.CancelOperation(ctx, req, opts...) +} + +// GetServerConfig returns configuration info about the Google Kubernetes Engine service. +func (c *ClusterManagerClient) GetServerConfig(ctx context.Context, req *containerpb.GetServerConfigRequest, opts ...gax.CallOption) (*containerpb.ServerConfig, error) { + return c.internalClient.GetServerConfig(ctx, req, opts...) +} + +// GetJSONWebKeys gets the public component of the cluster signing keys in +// JSON Web Key format. +// This API is not yet intended for general use, and is not available for all +// clusters. +func (c *ClusterManagerClient) GetJSONWebKeys(ctx context.Context, req *containerpb.GetJSONWebKeysRequest, opts ...gax.CallOption) (*containerpb.GetJSONWebKeysResponse, error) { + return c.internalClient.GetJSONWebKeys(ctx, req, opts...) +} + +// ListNodePools lists the node pools for a cluster. +func (c *ClusterManagerClient) ListNodePools(ctx context.Context, req *containerpb.ListNodePoolsRequest, opts ...gax.CallOption) (*containerpb.ListNodePoolsResponse, error) { + return c.internalClient.ListNodePools(ctx, req, opts...) +} + +// GetNodePool retrieves the requested node pool. +func (c *ClusterManagerClient) GetNodePool(ctx context.Context, req *containerpb.GetNodePoolRequest, opts ...gax.CallOption) (*containerpb.NodePool, error) { + return c.internalClient.GetNodePool(ctx, req, opts...) +} + +// CreateNodePool creates a node pool for a cluster. +func (c *ClusterManagerClient) CreateNodePool(ctx context.Context, req *containerpb.CreateNodePoolRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.CreateNodePool(ctx, req, opts...) +} + +// DeleteNodePool deletes a node pool from a cluster. +func (c *ClusterManagerClient) DeleteNodePool(ctx context.Context, req *containerpb.DeleteNodePoolRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.DeleteNodePool(ctx, req, opts...) +} + +// RollbackNodePoolUpgrade rolls back a previously Aborted or Failed NodePool upgrade. +// This makes no changes if the last upgrade successfully completed. +func (c *ClusterManagerClient) RollbackNodePoolUpgrade(ctx context.Context, req *containerpb.RollbackNodePoolUpgradeRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.RollbackNodePoolUpgrade(ctx, req, opts...) +} + +// SetNodePoolManagement sets the NodeManagement options for a node pool. +func (c *ClusterManagerClient) SetNodePoolManagement(ctx context.Context, req *containerpb.SetNodePoolManagementRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.SetNodePoolManagement(ctx, req, opts...) +} + +// SetLabels sets labels on a cluster. +func (c *ClusterManagerClient) SetLabels(ctx context.Context, req *containerpb.SetLabelsRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.SetLabels(ctx, req, opts...) +} + +// SetLegacyAbac enables or disables the ABAC authorization mechanism on a cluster. +func (c *ClusterManagerClient) SetLegacyAbac(ctx context.Context, req *containerpb.SetLegacyAbacRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.SetLegacyAbac(ctx, req, opts...) +} + +// StartIPRotation starts master IP rotation. +func (c *ClusterManagerClient) StartIPRotation(ctx context.Context, req *containerpb.StartIPRotationRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.StartIPRotation(ctx, req, opts...) +} + +// CompleteIPRotation completes master IP rotation. +func (c *ClusterManagerClient) CompleteIPRotation(ctx context.Context, req *containerpb.CompleteIPRotationRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.CompleteIPRotation(ctx, req, opts...) +} + +// SetNodePoolSize sets the size for a specific node pool. +func (c *ClusterManagerClient) SetNodePoolSize(ctx context.Context, req *containerpb.SetNodePoolSizeRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.SetNodePoolSize(ctx, req, opts...) +} + +// SetNetworkPolicy enables or disables Network Policy for a cluster. +func (c *ClusterManagerClient) SetNetworkPolicy(ctx context.Context, req *containerpb.SetNetworkPolicyRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.SetNetworkPolicy(ctx, req, opts...) +} + +// SetMaintenancePolicy sets the maintenance policy for a cluster. +func (c *ClusterManagerClient) SetMaintenancePolicy(ctx context.Context, req *containerpb.SetMaintenancePolicyRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { + return c.internalClient.SetMaintenancePolicy(ctx, req, opts...) +} + +// ListUsableSubnetworks lists subnetworks that are usable for creating clusters in a project. +func (c *ClusterManagerClient) ListUsableSubnetworks(ctx context.Context, req *containerpb.ListUsableSubnetworksRequest, opts ...gax.CallOption) *UsableSubnetworkIterator { + return c.internalClient.ListUsableSubnetworks(ctx, req, opts...) +} + +// clusterManagerGRPCClient is a client for interacting with Kubernetes Engine API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type clusterManagerGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ClusterManagerClient + CallOptions **ClusterManagerCallOptions + // The gRPC API client. clusterManagerClient containerpb.ClusterManagerClient - // The call options for this service. - CallOptions *ClusterManagerCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClusterManagerClient creates a new cluster manager client. +// NewClusterManagerClient creates a new cluster manager client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Google Kubernetes Engine Cluster Manager v1 func NewClusterManagerClient(ctx context.Context, opts ...option.ClientOption) (*ClusterManagerClient, error) { - clientOpts := defaultClusterManagerClientOptions() - + clientOpts := defaultClusterManagerGRPCClientOptions() if newClusterManagerClientHook != nil { hookOpts, err := newClusterManagerClientHook(ctx, clientHookParams{}) if err != nil { @@ -264,43 +530,44 @@ func NewClusterManagerClient(ctx context.Context, opts ...option.ClientOption) ( if err != nil { return nil, err } - c := &ClusterManagerClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultClusterManagerCallOptions(), + client := ClusterManagerClient{CallOptions: defaultClusterManagerCallOptions()} + c := &clusterManagerGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, clusterManagerClient: containerpb.NewClusterManagerClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ClusterManagerClient) Connection() *grpc.ClientConn { +func (c *clusterManagerGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ClusterManagerClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ClusterManagerClient) setGoogleClientInfo(keyval ...string) { +func (c *clusterManagerGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListClusters lists all clusters owned by a project in either the specified zone or all -// zones. -func (c *ClusterManagerClient) ListClusters(ctx context.Context, req *containerpb.ListClustersRequest, opts ...gax.CallOption) (*containerpb.ListClustersResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *clusterManagerGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *clusterManagerGRPCClient) ListClusters(ctx context.Context, req *containerpb.ListClustersRequest, opts ...gax.CallOption) (*containerpb.ListClustersResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -308,7 +575,7 @@ func (c *ClusterManagerClient) ListClusters(ctx context.Context, req *containerp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "parent", url.QueryEscape(req.GetParent()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListClusters[0:len(c.CallOptions.ListClusters):len(c.CallOptions.ListClusters)], opts...) + opts = append((*c.CallOptions).ListClusters[0:len((*c.CallOptions).ListClusters):len((*c.CallOptions).ListClusters)], opts...) var resp *containerpb.ListClustersResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -321,8 +588,7 @@ func (c *ClusterManagerClient) ListClusters(ctx context.Context, req *containerp return resp, nil } -// GetCluster gets the details of a specific cluster. -func (c *ClusterManagerClient) GetCluster(ctx context.Context, req *containerpb.GetClusterRequest, opts ...gax.CallOption) (*containerpb.Cluster, error) { +func (c *clusterManagerGRPCClient) GetCluster(ctx context.Context, req *containerpb.GetClusterRequest, opts ...gax.CallOption) (*containerpb.Cluster, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -330,7 +596,7 @@ func (c *ClusterManagerClient) GetCluster(ctx context.Context, req *containerpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCluster[0:len(c.CallOptions.GetCluster):len(c.CallOptions.GetCluster)], opts...) + opts = append((*c.CallOptions).GetCluster[0:len((*c.CallOptions).GetCluster):len((*c.CallOptions).GetCluster)], opts...) var resp *containerpb.Cluster err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -343,21 +609,7 @@ func (c *ClusterManagerClient) GetCluster(ctx context.Context, req *containerpb. return resp, nil } -// CreateCluster creates a cluster, consisting of the specified number and type of Google -// Compute Engine instances. -// -// By default, the cluster is created in the project’s -// default -// network (at https://cloud.google.com/compute/docs/networks-and-firewalls#networks). -// -// One firewall is added for the cluster. After cluster creation, -// the Kubelet creates routes for each node to allow the containers -// on that node to communicate with all other instances in the -// cluster. -// -// Finally, an entry is added to the project’s global metadata indicating -// which CIDR range the cluster is using. -func (c *ClusterManagerClient) CreateCluster(ctx context.Context, req *containerpb.CreateClusterRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) CreateCluster(ctx context.Context, req *containerpb.CreateClusterRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -365,7 +617,7 @@ func (c *ClusterManagerClient) CreateCluster(ctx context.Context, req *container } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "parent", url.QueryEscape(req.GetParent()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCluster[0:len(c.CallOptions.CreateCluster):len(c.CallOptions.CreateCluster)], opts...) + opts = append((*c.CallOptions).CreateCluster[0:len((*c.CallOptions).CreateCluster):len((*c.CallOptions).CreateCluster)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -378,8 +630,7 @@ func (c *ClusterManagerClient) CreateCluster(ctx context.Context, req *container return resp, nil } -// UpdateCluster updates the settings of a specific cluster. -func (c *ClusterManagerClient) UpdateCluster(ctx context.Context, req *containerpb.UpdateClusterRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) UpdateCluster(ctx context.Context, req *containerpb.UpdateClusterRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -387,7 +638,7 @@ func (c *ClusterManagerClient) UpdateCluster(ctx context.Context, req *container } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCluster[0:len(c.CallOptions.UpdateCluster):len(c.CallOptions.UpdateCluster)], opts...) + opts = append((*c.CallOptions).UpdateCluster[0:len((*c.CallOptions).UpdateCluster):len((*c.CallOptions).UpdateCluster)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -400,8 +651,7 @@ func (c *ClusterManagerClient) UpdateCluster(ctx context.Context, req *container return resp, nil } -// UpdateNodePool updates the version and/or image type for the specified node pool. -func (c *ClusterManagerClient) UpdateNodePool(ctx context.Context, req *containerpb.UpdateNodePoolRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) UpdateNodePool(ctx context.Context, req *containerpb.UpdateNodePoolRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -409,7 +659,7 @@ func (c *ClusterManagerClient) UpdateNodePool(ctx context.Context, req *containe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()), "node_pool_id", url.QueryEscape(req.GetNodePoolId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateNodePool[0:len(c.CallOptions.UpdateNodePool):len(c.CallOptions.UpdateNodePool)], opts...) + opts = append((*c.CallOptions).UpdateNodePool[0:len((*c.CallOptions).UpdateNodePool):len((*c.CallOptions).UpdateNodePool)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -422,8 +672,7 @@ func (c *ClusterManagerClient) UpdateNodePool(ctx context.Context, req *containe return resp, nil } -// SetNodePoolAutoscaling sets the autoscaling settings for the specified node pool. -func (c *ClusterManagerClient) SetNodePoolAutoscaling(ctx context.Context, req *containerpb.SetNodePoolAutoscalingRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) SetNodePoolAutoscaling(ctx context.Context, req *containerpb.SetNodePoolAutoscalingRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -431,7 +680,7 @@ func (c *ClusterManagerClient) SetNodePoolAutoscaling(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()), "node_pool_id", url.QueryEscape(req.GetNodePoolId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetNodePoolAutoscaling[0:len(c.CallOptions.SetNodePoolAutoscaling):len(c.CallOptions.SetNodePoolAutoscaling)], opts...) + opts = append((*c.CallOptions).SetNodePoolAutoscaling[0:len((*c.CallOptions).SetNodePoolAutoscaling):len((*c.CallOptions).SetNodePoolAutoscaling)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -444,8 +693,7 @@ func (c *ClusterManagerClient) SetNodePoolAutoscaling(ctx context.Context, req * return resp, nil } -// SetLoggingService sets the logging service for a specific cluster. -func (c *ClusterManagerClient) SetLoggingService(ctx context.Context, req *containerpb.SetLoggingServiceRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) SetLoggingService(ctx context.Context, req *containerpb.SetLoggingServiceRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -453,7 +701,7 @@ func (c *ClusterManagerClient) SetLoggingService(ctx context.Context, req *conta } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetLoggingService[0:len(c.CallOptions.SetLoggingService):len(c.CallOptions.SetLoggingService)], opts...) + opts = append((*c.CallOptions).SetLoggingService[0:len((*c.CallOptions).SetLoggingService):len((*c.CallOptions).SetLoggingService)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -466,8 +714,7 @@ func (c *ClusterManagerClient) SetLoggingService(ctx context.Context, req *conta return resp, nil } -// SetMonitoringService sets the monitoring service for a specific cluster. -func (c *ClusterManagerClient) SetMonitoringService(ctx context.Context, req *containerpb.SetMonitoringServiceRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) SetMonitoringService(ctx context.Context, req *containerpb.SetMonitoringServiceRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -475,7 +722,7 @@ func (c *ClusterManagerClient) SetMonitoringService(ctx context.Context, req *co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetMonitoringService[0:len(c.CallOptions.SetMonitoringService):len(c.CallOptions.SetMonitoringService)], opts...) + opts = append((*c.CallOptions).SetMonitoringService[0:len((*c.CallOptions).SetMonitoringService):len((*c.CallOptions).SetMonitoringService)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -488,8 +735,7 @@ func (c *ClusterManagerClient) SetMonitoringService(ctx context.Context, req *co return resp, nil } -// SetAddonsConfig sets the addons for a specific cluster. -func (c *ClusterManagerClient) SetAddonsConfig(ctx context.Context, req *containerpb.SetAddonsConfigRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) SetAddonsConfig(ctx context.Context, req *containerpb.SetAddonsConfigRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -497,7 +743,7 @@ func (c *ClusterManagerClient) SetAddonsConfig(ctx context.Context, req *contain } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetAddonsConfig[0:len(c.CallOptions.SetAddonsConfig):len(c.CallOptions.SetAddonsConfig)], opts...) + opts = append((*c.CallOptions).SetAddonsConfig[0:len((*c.CallOptions).SetAddonsConfig):len((*c.CallOptions).SetAddonsConfig)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -510,11 +756,7 @@ func (c *ClusterManagerClient) SetAddonsConfig(ctx context.Context, req *contain return resp, nil } -// SetLocations sets the locations for a specific cluster. -// Deprecated. Use -// projects.locations.clusters.update (at https://cloud.google.com/kubernetes-engine/docs/reference/rest/v1/projects.locations.clusters/update) -// instead. -func (c *ClusterManagerClient) SetLocations(ctx context.Context, req *containerpb.SetLocationsRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) SetLocations(ctx context.Context, req *containerpb.SetLocationsRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -522,7 +764,7 @@ func (c *ClusterManagerClient) SetLocations(ctx context.Context, req *containerp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetLocations[0:len(c.CallOptions.SetLocations):len(c.CallOptions.SetLocations)], opts...) + opts = append((*c.CallOptions).SetLocations[0:len((*c.CallOptions).SetLocations):len((*c.CallOptions).SetLocations)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -535,8 +777,7 @@ func (c *ClusterManagerClient) SetLocations(ctx context.Context, req *containerp return resp, nil } -// UpdateMaster updates the master for a specific cluster. -func (c *ClusterManagerClient) UpdateMaster(ctx context.Context, req *containerpb.UpdateMasterRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) UpdateMaster(ctx context.Context, req *containerpb.UpdateMasterRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -544,7 +785,7 @@ func (c *ClusterManagerClient) UpdateMaster(ctx context.Context, req *containerp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateMaster[0:len(c.CallOptions.UpdateMaster):len(c.CallOptions.UpdateMaster)], opts...) + opts = append((*c.CallOptions).UpdateMaster[0:len((*c.CallOptions).UpdateMaster):len((*c.CallOptions).UpdateMaster)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -557,10 +798,7 @@ func (c *ClusterManagerClient) UpdateMaster(ctx context.Context, req *containerp return resp, nil } -// SetMasterAuth sets master auth materials. Currently supports changing the admin password -// or a specific cluster, either via password generation or explicitly setting -// the password. -func (c *ClusterManagerClient) SetMasterAuth(ctx context.Context, req *containerpb.SetMasterAuthRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) SetMasterAuth(ctx context.Context, req *containerpb.SetMasterAuthRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -568,7 +806,7 @@ func (c *ClusterManagerClient) SetMasterAuth(ctx context.Context, req *container } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetMasterAuth[0:len(c.CallOptions.SetMasterAuth):len(c.CallOptions.SetMasterAuth)], opts...) + opts = append((*c.CallOptions).SetMasterAuth[0:len((*c.CallOptions).SetMasterAuth):len((*c.CallOptions).SetMasterAuth)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -581,16 +819,7 @@ func (c *ClusterManagerClient) SetMasterAuth(ctx context.Context, req *container return resp, nil } -// DeleteCluster deletes the cluster, including the Kubernetes endpoint and all worker -// nodes. -// -// Firewalls and routes that were configured during cluster creation -// are also deleted. -// -// Other Google Compute Engine resources that might be in use by the cluster, -// such as load balancer resources, are not deleted if they weren’t present -// when the cluster was initially created. -func (c *ClusterManagerClient) DeleteCluster(ctx context.Context, req *containerpb.DeleteClusterRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) DeleteCluster(ctx context.Context, req *containerpb.DeleteClusterRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -598,7 +827,7 @@ func (c *ClusterManagerClient) DeleteCluster(ctx context.Context, req *container } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteCluster[0:len(c.CallOptions.DeleteCluster):len(c.CallOptions.DeleteCluster)], opts...) + opts = append((*c.CallOptions).DeleteCluster[0:len((*c.CallOptions).DeleteCluster):len((*c.CallOptions).DeleteCluster)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -611,8 +840,7 @@ func (c *ClusterManagerClient) DeleteCluster(ctx context.Context, req *container return resp, nil } -// ListOperations lists all operations in a project in a specific zone or all zones. -func (c *ClusterManagerClient) ListOperations(ctx context.Context, req *containerpb.ListOperationsRequest, opts ...gax.CallOption) (*containerpb.ListOperationsResponse, error) { +func (c *clusterManagerGRPCClient) ListOperations(ctx context.Context, req *containerpb.ListOperationsRequest, opts ...gax.CallOption) (*containerpb.ListOperationsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -620,7 +848,7 @@ func (c *ClusterManagerClient) ListOperations(ctx context.Context, req *containe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "parent", url.QueryEscape(req.GetParent()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListOperations[0:len(c.CallOptions.ListOperations):len(c.CallOptions.ListOperations)], opts...) + opts = append((*c.CallOptions).ListOperations[0:len((*c.CallOptions).ListOperations):len((*c.CallOptions).ListOperations)], opts...) var resp *containerpb.ListOperationsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -633,8 +861,7 @@ func (c *ClusterManagerClient) ListOperations(ctx context.Context, req *containe return resp, nil } -// GetOperation gets the specified operation. -func (c *ClusterManagerClient) GetOperation(ctx context.Context, req *containerpb.GetOperationRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) GetOperation(ctx context.Context, req *containerpb.GetOperationRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -642,7 +869,7 @@ func (c *ClusterManagerClient) GetOperation(ctx context.Context, req *containerp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "operation_id", url.QueryEscape(req.GetOperationId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetOperation[0:len(c.CallOptions.GetOperation):len(c.CallOptions.GetOperation)], opts...) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -655,8 +882,7 @@ func (c *ClusterManagerClient) GetOperation(ctx context.Context, req *containerp return resp, nil } -// CancelOperation cancels the specified operation. -func (c *ClusterManagerClient) CancelOperation(ctx context.Context, req *containerpb.CancelOperationRequest, opts ...gax.CallOption) error { +func (c *clusterManagerGRPCClient) CancelOperation(ctx context.Context, req *containerpb.CancelOperationRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -664,7 +890,7 @@ func (c *ClusterManagerClient) CancelOperation(ctx context.Context, req *contain } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "operation_id", url.QueryEscape(req.GetOperationId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CancelOperation[0:len(c.CallOptions.CancelOperation):len(c.CallOptions.CancelOperation)], opts...) + opts = append((*c.CallOptions).CancelOperation[0:len((*c.CallOptions).CancelOperation):len((*c.CallOptions).CancelOperation)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.clusterManagerClient.CancelOperation(ctx, req, settings.GRPC...) @@ -673,8 +899,7 @@ func (c *ClusterManagerClient) CancelOperation(ctx context.Context, req *contain return err } -// GetServerConfig returns configuration info about the Google Kubernetes Engine service. -func (c *ClusterManagerClient) GetServerConfig(ctx context.Context, req *containerpb.GetServerConfigRequest, opts ...gax.CallOption) (*containerpb.ServerConfig, error) { +func (c *clusterManagerGRPCClient) GetServerConfig(ctx context.Context, req *containerpb.GetServerConfigRequest, opts ...gax.CallOption) (*containerpb.ServerConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -682,7 +907,7 @@ func (c *ClusterManagerClient) GetServerConfig(ctx context.Context, req *contain } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetServerConfig[0:len(c.CallOptions.GetServerConfig):len(c.CallOptions.GetServerConfig)], opts...) + opts = append((*c.CallOptions).GetServerConfig[0:len((*c.CallOptions).GetServerConfig):len((*c.CallOptions).GetServerConfig)], opts...) var resp *containerpb.ServerConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -695,14 +920,10 @@ func (c *ClusterManagerClient) GetServerConfig(ctx context.Context, req *contain return resp, nil } -// GetJSONWebKeys gets the public component of the cluster signing keys in -// JSON Web Key format. -// This API is not yet intended for general use, and is not available for all -// clusters. -func (c *ClusterManagerClient) GetJSONWebKeys(ctx context.Context, req *containerpb.GetJSONWebKeysRequest, opts ...gax.CallOption) (*containerpb.GetJSONWebKeysResponse, error) { +func (c *clusterManagerGRPCClient) GetJSONWebKeys(ctx context.Context, req *containerpb.GetJSONWebKeysRequest, opts ...gax.CallOption) (*containerpb.GetJSONWebKeysResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetJSONWebKeys[0:len(c.CallOptions.GetJSONWebKeys):len(c.CallOptions.GetJSONWebKeys)], opts...) + opts = append((*c.CallOptions).GetJSONWebKeys[0:len((*c.CallOptions).GetJSONWebKeys):len((*c.CallOptions).GetJSONWebKeys)], opts...) var resp *containerpb.GetJSONWebKeysResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -715,8 +936,7 @@ func (c *ClusterManagerClient) GetJSONWebKeys(ctx context.Context, req *containe return resp, nil } -// ListNodePools lists the node pools for a cluster. -func (c *ClusterManagerClient) ListNodePools(ctx context.Context, req *containerpb.ListNodePoolsRequest, opts ...gax.CallOption) (*containerpb.ListNodePoolsResponse, error) { +func (c *clusterManagerGRPCClient) ListNodePools(ctx context.Context, req *containerpb.ListNodePoolsRequest, opts ...gax.CallOption) (*containerpb.ListNodePoolsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -724,7 +944,7 @@ func (c *ClusterManagerClient) ListNodePools(ctx context.Context, req *container } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "parent", url.QueryEscape(req.GetParent()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListNodePools[0:len(c.CallOptions.ListNodePools):len(c.CallOptions.ListNodePools)], opts...) + opts = append((*c.CallOptions).ListNodePools[0:len((*c.CallOptions).ListNodePools):len((*c.CallOptions).ListNodePools)], opts...) var resp *containerpb.ListNodePoolsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -737,8 +957,7 @@ func (c *ClusterManagerClient) ListNodePools(ctx context.Context, req *container return resp, nil } -// GetNodePool retrieves the requested node pool. -func (c *ClusterManagerClient) GetNodePool(ctx context.Context, req *containerpb.GetNodePoolRequest, opts ...gax.CallOption) (*containerpb.NodePool, error) { +func (c *clusterManagerGRPCClient) GetNodePool(ctx context.Context, req *containerpb.GetNodePoolRequest, opts ...gax.CallOption) (*containerpb.NodePool, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -746,7 +965,7 @@ func (c *ClusterManagerClient) GetNodePool(ctx context.Context, req *containerpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()), "node_pool_id", url.QueryEscape(req.GetNodePoolId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetNodePool[0:len(c.CallOptions.GetNodePool):len(c.CallOptions.GetNodePool)], opts...) + opts = append((*c.CallOptions).GetNodePool[0:len((*c.CallOptions).GetNodePool):len((*c.CallOptions).GetNodePool)], opts...) var resp *containerpb.NodePool err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -759,8 +978,7 @@ func (c *ClusterManagerClient) GetNodePool(ctx context.Context, req *containerpb return resp, nil } -// CreateNodePool creates a node pool for a cluster. -func (c *ClusterManagerClient) CreateNodePool(ctx context.Context, req *containerpb.CreateNodePoolRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) CreateNodePool(ctx context.Context, req *containerpb.CreateNodePoolRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -768,7 +986,7 @@ func (c *ClusterManagerClient) CreateNodePool(ctx context.Context, req *containe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "parent", url.QueryEscape(req.GetParent()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateNodePool[0:len(c.CallOptions.CreateNodePool):len(c.CallOptions.CreateNodePool)], opts...) + opts = append((*c.CallOptions).CreateNodePool[0:len((*c.CallOptions).CreateNodePool):len((*c.CallOptions).CreateNodePool)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -781,8 +999,7 @@ func (c *ClusterManagerClient) CreateNodePool(ctx context.Context, req *containe return resp, nil } -// DeleteNodePool deletes a node pool from a cluster. -func (c *ClusterManagerClient) DeleteNodePool(ctx context.Context, req *containerpb.DeleteNodePoolRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) DeleteNodePool(ctx context.Context, req *containerpb.DeleteNodePoolRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 20000*time.Millisecond) defer cancel() @@ -790,7 +1007,7 @@ func (c *ClusterManagerClient) DeleteNodePool(ctx context.Context, req *containe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()), "node_pool_id", url.QueryEscape(req.GetNodePoolId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteNodePool[0:len(c.CallOptions.DeleteNodePool):len(c.CallOptions.DeleteNodePool)], opts...) + opts = append((*c.CallOptions).DeleteNodePool[0:len((*c.CallOptions).DeleteNodePool):len((*c.CallOptions).DeleteNodePool)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -803,9 +1020,7 @@ func (c *ClusterManagerClient) DeleteNodePool(ctx context.Context, req *containe return resp, nil } -// RollbackNodePoolUpgrade rolls back a previously Aborted or Failed NodePool upgrade. -// This makes no changes if the last upgrade successfully completed. -func (c *ClusterManagerClient) RollbackNodePoolUpgrade(ctx context.Context, req *containerpb.RollbackNodePoolUpgradeRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) RollbackNodePoolUpgrade(ctx context.Context, req *containerpb.RollbackNodePoolUpgradeRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -813,7 +1028,7 @@ func (c *ClusterManagerClient) RollbackNodePoolUpgrade(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()), "node_pool_id", url.QueryEscape(req.GetNodePoolId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RollbackNodePoolUpgrade[0:len(c.CallOptions.RollbackNodePoolUpgrade):len(c.CallOptions.RollbackNodePoolUpgrade)], opts...) + opts = append((*c.CallOptions).RollbackNodePoolUpgrade[0:len((*c.CallOptions).RollbackNodePoolUpgrade):len((*c.CallOptions).RollbackNodePoolUpgrade)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -826,8 +1041,7 @@ func (c *ClusterManagerClient) RollbackNodePoolUpgrade(ctx context.Context, req return resp, nil } -// SetNodePoolManagement sets the NodeManagement options for a node pool. -func (c *ClusterManagerClient) SetNodePoolManagement(ctx context.Context, req *containerpb.SetNodePoolManagementRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) SetNodePoolManagement(ctx context.Context, req *containerpb.SetNodePoolManagementRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -835,7 +1049,7 @@ func (c *ClusterManagerClient) SetNodePoolManagement(ctx context.Context, req *c } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()), "node_pool_id", url.QueryEscape(req.GetNodePoolId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetNodePoolManagement[0:len(c.CallOptions.SetNodePoolManagement):len(c.CallOptions.SetNodePoolManagement)], opts...) + opts = append((*c.CallOptions).SetNodePoolManagement[0:len((*c.CallOptions).SetNodePoolManagement):len((*c.CallOptions).SetNodePoolManagement)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -848,8 +1062,7 @@ func (c *ClusterManagerClient) SetNodePoolManagement(ctx context.Context, req *c return resp, nil } -// SetLabels sets labels on a cluster. -func (c *ClusterManagerClient) SetLabels(ctx context.Context, req *containerpb.SetLabelsRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) SetLabels(ctx context.Context, req *containerpb.SetLabelsRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -857,7 +1070,7 @@ func (c *ClusterManagerClient) SetLabels(ctx context.Context, req *containerpb.S } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetLabels[0:len(c.CallOptions.SetLabels):len(c.CallOptions.SetLabels)], opts...) + opts = append((*c.CallOptions).SetLabels[0:len((*c.CallOptions).SetLabels):len((*c.CallOptions).SetLabels)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -870,8 +1083,7 @@ func (c *ClusterManagerClient) SetLabels(ctx context.Context, req *containerpb.S return resp, nil } -// SetLegacyAbac enables or disables the ABAC authorization mechanism on a cluster. -func (c *ClusterManagerClient) SetLegacyAbac(ctx context.Context, req *containerpb.SetLegacyAbacRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) SetLegacyAbac(ctx context.Context, req *containerpb.SetLegacyAbacRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -879,7 +1091,7 @@ func (c *ClusterManagerClient) SetLegacyAbac(ctx context.Context, req *container } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetLegacyAbac[0:len(c.CallOptions.SetLegacyAbac):len(c.CallOptions.SetLegacyAbac)], opts...) + opts = append((*c.CallOptions).SetLegacyAbac[0:len((*c.CallOptions).SetLegacyAbac):len((*c.CallOptions).SetLegacyAbac)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -892,8 +1104,7 @@ func (c *ClusterManagerClient) SetLegacyAbac(ctx context.Context, req *container return resp, nil } -// StartIPRotation starts master IP rotation. -func (c *ClusterManagerClient) StartIPRotation(ctx context.Context, req *containerpb.StartIPRotationRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) StartIPRotation(ctx context.Context, req *containerpb.StartIPRotationRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -901,7 +1112,7 @@ func (c *ClusterManagerClient) StartIPRotation(ctx context.Context, req *contain } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.StartIPRotation[0:len(c.CallOptions.StartIPRotation):len(c.CallOptions.StartIPRotation)], opts...) + opts = append((*c.CallOptions).StartIPRotation[0:len((*c.CallOptions).StartIPRotation):len((*c.CallOptions).StartIPRotation)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -914,8 +1125,7 @@ func (c *ClusterManagerClient) StartIPRotation(ctx context.Context, req *contain return resp, nil } -// CompleteIPRotation completes master IP rotation. -func (c *ClusterManagerClient) CompleteIPRotation(ctx context.Context, req *containerpb.CompleteIPRotationRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) CompleteIPRotation(ctx context.Context, req *containerpb.CompleteIPRotationRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -923,7 +1133,7 @@ func (c *ClusterManagerClient) CompleteIPRotation(ctx context.Context, req *cont } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CompleteIPRotation[0:len(c.CallOptions.CompleteIPRotation):len(c.CallOptions.CompleteIPRotation)], opts...) + opts = append((*c.CallOptions).CompleteIPRotation[0:len((*c.CallOptions).CompleteIPRotation):len((*c.CallOptions).CompleteIPRotation)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -936,8 +1146,7 @@ func (c *ClusterManagerClient) CompleteIPRotation(ctx context.Context, req *cont return resp, nil } -// SetNodePoolSize sets the size for a specific node pool. -func (c *ClusterManagerClient) SetNodePoolSize(ctx context.Context, req *containerpb.SetNodePoolSizeRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) SetNodePoolSize(ctx context.Context, req *containerpb.SetNodePoolSizeRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -945,7 +1154,7 @@ func (c *ClusterManagerClient) SetNodePoolSize(ctx context.Context, req *contain } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()), "node_pool_id", url.QueryEscape(req.GetNodePoolId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetNodePoolSize[0:len(c.CallOptions.SetNodePoolSize):len(c.CallOptions.SetNodePoolSize)], opts...) + opts = append((*c.CallOptions).SetNodePoolSize[0:len((*c.CallOptions).SetNodePoolSize):len((*c.CallOptions).SetNodePoolSize)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -958,8 +1167,7 @@ func (c *ClusterManagerClient) SetNodePoolSize(ctx context.Context, req *contain return resp, nil } -// SetNetworkPolicy enables or disables Network Policy for a cluster. -func (c *ClusterManagerClient) SetNetworkPolicy(ctx context.Context, req *containerpb.SetNetworkPolicyRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) SetNetworkPolicy(ctx context.Context, req *containerpb.SetNetworkPolicyRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -967,7 +1175,7 @@ func (c *ClusterManagerClient) SetNetworkPolicy(ctx context.Context, req *contai } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetNetworkPolicy[0:len(c.CallOptions.SetNetworkPolicy):len(c.CallOptions.SetNetworkPolicy)], opts...) + opts = append((*c.CallOptions).SetNetworkPolicy[0:len((*c.CallOptions).SetNetworkPolicy):len((*c.CallOptions).SetNetworkPolicy)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -980,8 +1188,7 @@ func (c *ClusterManagerClient) SetNetworkPolicy(ctx context.Context, req *contai return resp, nil } -// SetMaintenancePolicy sets the maintenance policy for a cluster. -func (c *ClusterManagerClient) SetMaintenancePolicy(ctx context.Context, req *containerpb.SetMaintenancePolicyRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { +func (c *clusterManagerGRPCClient) SetMaintenancePolicy(ctx context.Context, req *containerpb.SetMaintenancePolicyRequest, opts ...gax.CallOption) (*containerpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -989,7 +1196,7 @@ func (c *ClusterManagerClient) SetMaintenancePolicy(ctx context.Context, req *co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v&%s=%v", "name", url.QueryEscape(req.GetName()), "project_id", url.QueryEscape(req.GetProjectId()), "zone", url.QueryEscape(req.GetZone()), "cluster_id", url.QueryEscape(req.GetClusterId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetMaintenancePolicy[0:len(c.CallOptions.SetMaintenancePolicy):len(c.CallOptions.SetMaintenancePolicy)], opts...) + opts = append((*c.CallOptions).SetMaintenancePolicy[0:len((*c.CallOptions).SetMaintenancePolicy):len((*c.CallOptions).SetMaintenancePolicy)], opts...) var resp *containerpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1002,11 +1209,10 @@ func (c *ClusterManagerClient) SetMaintenancePolicy(ctx context.Context, req *co return resp, nil } -// ListUsableSubnetworks lists subnetworks that are usable for creating clusters in a project. -func (c *ClusterManagerClient) ListUsableSubnetworks(ctx context.Context, req *containerpb.ListUsableSubnetworksRequest, opts ...gax.CallOption) *UsableSubnetworkIterator { +func (c *clusterManagerGRPCClient) ListUsableSubnetworks(ctx context.Context, req *containerpb.ListUsableSubnetworksRequest, opts ...gax.CallOption) *UsableSubnetworkIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListUsableSubnetworks[0:len(c.CallOptions.ListUsableSubnetworks):len(c.CallOptions.ListUsableSubnetworks)], opts...) + opts = append((*c.CallOptions).ListUsableSubnetworks[0:len((*c.CallOptions).ListUsableSubnetworks):len((*c.CallOptions).ListUsableSubnetworks)], opts...) it := &UsableSubnetworkIterator{} req = proto.Clone(req).(*containerpb.ListUsableSubnetworksRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*containerpb.UsableSubnetwork, string, error) { diff --git a/container/apiv1/cluster_manager_client_example_test.go b/container/apiv1/cluster_manager_client_example_test.go index 4bef5b0cf531..1ae8014411a8 100644 --- a/container/apiv1/cluster_manager_client_example_test.go +++ b/container/apiv1/cluster_manager_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClusterManagerClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClusterManagerClient_ListClusters() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.ListClustersRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleClusterManagerClient_ListClusters() { } func ExampleClusterManagerClient_GetCluster() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.GetClusterRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleClusterManagerClient_GetCluster() { } func ExampleClusterManagerClient_CreateCluster() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.CreateClusterRequest{ // TODO: Fill request struct fields. @@ -95,13 +94,12 @@ func ExampleClusterManagerClient_CreateCluster() { } func ExampleClusterManagerClient_UpdateCluster() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.UpdateClusterRequest{ // TODO: Fill request struct fields. @@ -115,13 +113,12 @@ func ExampleClusterManagerClient_UpdateCluster() { } func ExampleClusterManagerClient_UpdateNodePool() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.UpdateNodePoolRequest{ // TODO: Fill request struct fields. @@ -135,13 +132,12 @@ func ExampleClusterManagerClient_UpdateNodePool() { } func ExampleClusterManagerClient_SetNodePoolAutoscaling() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetNodePoolAutoscalingRequest{ // TODO: Fill request struct fields. @@ -155,13 +151,12 @@ func ExampleClusterManagerClient_SetNodePoolAutoscaling() { } func ExampleClusterManagerClient_SetLoggingService() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetLoggingServiceRequest{ // TODO: Fill request struct fields. @@ -175,13 +170,12 @@ func ExampleClusterManagerClient_SetLoggingService() { } func ExampleClusterManagerClient_SetMonitoringService() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetMonitoringServiceRequest{ // TODO: Fill request struct fields. @@ -195,13 +189,12 @@ func ExampleClusterManagerClient_SetMonitoringService() { } func ExampleClusterManagerClient_SetAddonsConfig() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetAddonsConfigRequest{ // TODO: Fill request struct fields. @@ -215,13 +208,12 @@ func ExampleClusterManagerClient_SetAddonsConfig() { } func ExampleClusterManagerClient_SetLocations() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetLocationsRequest{ // TODO: Fill request struct fields. @@ -235,13 +227,12 @@ func ExampleClusterManagerClient_SetLocations() { } func ExampleClusterManagerClient_UpdateMaster() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.UpdateMasterRequest{ // TODO: Fill request struct fields. @@ -255,13 +246,12 @@ func ExampleClusterManagerClient_UpdateMaster() { } func ExampleClusterManagerClient_SetMasterAuth() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetMasterAuthRequest{ // TODO: Fill request struct fields. @@ -275,13 +265,12 @@ func ExampleClusterManagerClient_SetMasterAuth() { } func ExampleClusterManagerClient_DeleteCluster() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.DeleteClusterRequest{ // TODO: Fill request struct fields. @@ -295,13 +284,12 @@ func ExampleClusterManagerClient_DeleteCluster() { } func ExampleClusterManagerClient_ListOperations() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.ListOperationsRequest{ // TODO: Fill request struct fields. @@ -315,13 +303,12 @@ func ExampleClusterManagerClient_ListOperations() { } func ExampleClusterManagerClient_GetOperation() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.GetOperationRequest{ // TODO: Fill request struct fields. @@ -340,6 +327,7 @@ func ExampleClusterManagerClient_CancelOperation() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.CancelOperationRequest{ // TODO: Fill request struct fields. @@ -351,13 +339,12 @@ func ExampleClusterManagerClient_CancelOperation() { } func ExampleClusterManagerClient_GetServerConfig() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.GetServerConfigRequest{ // TODO: Fill request struct fields. @@ -371,13 +358,12 @@ func ExampleClusterManagerClient_GetServerConfig() { } func ExampleClusterManagerClient_GetJSONWebKeys() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.GetJSONWebKeysRequest{ // TODO: Fill request struct fields. @@ -391,13 +377,12 @@ func ExampleClusterManagerClient_GetJSONWebKeys() { } func ExampleClusterManagerClient_ListNodePools() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.ListNodePoolsRequest{ // TODO: Fill request struct fields. @@ -411,13 +396,12 @@ func ExampleClusterManagerClient_ListNodePools() { } func ExampleClusterManagerClient_GetNodePool() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.GetNodePoolRequest{ // TODO: Fill request struct fields. @@ -431,13 +415,12 @@ func ExampleClusterManagerClient_GetNodePool() { } func ExampleClusterManagerClient_CreateNodePool() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.CreateNodePoolRequest{ // TODO: Fill request struct fields. @@ -451,13 +434,12 @@ func ExampleClusterManagerClient_CreateNodePool() { } func ExampleClusterManagerClient_DeleteNodePool() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.DeleteNodePoolRequest{ // TODO: Fill request struct fields. @@ -471,13 +453,12 @@ func ExampleClusterManagerClient_DeleteNodePool() { } func ExampleClusterManagerClient_RollbackNodePoolUpgrade() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.RollbackNodePoolUpgradeRequest{ // TODO: Fill request struct fields. @@ -491,13 +472,12 @@ func ExampleClusterManagerClient_RollbackNodePoolUpgrade() { } func ExampleClusterManagerClient_SetNodePoolManagement() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetNodePoolManagementRequest{ // TODO: Fill request struct fields. @@ -511,13 +491,12 @@ func ExampleClusterManagerClient_SetNodePoolManagement() { } func ExampleClusterManagerClient_SetLabels() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetLabelsRequest{ // TODO: Fill request struct fields. @@ -531,13 +510,12 @@ func ExampleClusterManagerClient_SetLabels() { } func ExampleClusterManagerClient_SetLegacyAbac() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetLegacyAbacRequest{ // TODO: Fill request struct fields. @@ -551,13 +529,12 @@ func ExampleClusterManagerClient_SetLegacyAbac() { } func ExampleClusterManagerClient_StartIPRotation() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.StartIPRotationRequest{ // TODO: Fill request struct fields. @@ -571,13 +548,12 @@ func ExampleClusterManagerClient_StartIPRotation() { } func ExampleClusterManagerClient_CompleteIPRotation() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.CompleteIPRotationRequest{ // TODO: Fill request struct fields. @@ -591,13 +567,12 @@ func ExampleClusterManagerClient_CompleteIPRotation() { } func ExampleClusterManagerClient_SetNodePoolSize() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetNodePoolSizeRequest{ // TODO: Fill request struct fields. @@ -611,13 +586,12 @@ func ExampleClusterManagerClient_SetNodePoolSize() { } func ExampleClusterManagerClient_SetNetworkPolicy() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetNetworkPolicyRequest{ // TODO: Fill request struct fields. @@ -631,13 +605,12 @@ func ExampleClusterManagerClient_SetNetworkPolicy() { } func ExampleClusterManagerClient_SetMaintenancePolicy() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetMaintenancePolicyRequest{ // TODO: Fill request struct fields. @@ -651,14 +624,12 @@ func ExampleClusterManagerClient_SetMaintenancePolicy() { } func ExampleClusterManagerClient_ListUsableSubnetworks() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.ListUsableSubnetworksRequest{ // TODO: Fill request struct fields. diff --git a/container/apiv1/doc.go b/container/apiv1/doc.go index 9cc59d70b858..9f9adb8ebfd9 100644 --- a/container/apiv1/doc.go +++ b/container/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package container // import "cloud.google.com/go/container/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/containeranalysis/apiv1beta1/container_analysis_v1_beta1_client.go b/containeranalysis/apiv1beta1/container_analysis_v1_beta1_client.go index 203f88c479d8..3855b9f33c6e 100644 --- a/containeranalysis/apiv1beta1/container_analysis_v1_beta1_client.go +++ b/containeranalysis/apiv1beta1/container_analysis_v1_beta1_client.go @@ -48,7 +48,7 @@ type ContainerAnalysisV1Beta1CallOptions struct { UpdateScanConfig []gax.CallOption } -func defaultContainerAnalysisV1Beta1ClientOptions() []option.ClientOption { +func defaultContainerAnalysisV1Beta1GRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("containeranalysis.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("containeranalysis.mtls.googleapis.com:443"), @@ -93,27 +93,137 @@ func defaultContainerAnalysisV1Beta1CallOptions() *ContainerAnalysisV1Beta1CallO } } +// internalContainerAnalysisV1Beta1Client is an interface that defines the methods availaible from Container Analysis API. +type internalContainerAnalysisV1Beta1Client interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) + GetScanConfig(context.Context, *containeranalysispb.GetScanConfigRequest, ...gax.CallOption) (*containeranalysispb.ScanConfig, error) + ListScanConfigs(context.Context, *containeranalysispb.ListScanConfigsRequest, ...gax.CallOption) *ScanConfigIterator + UpdateScanConfig(context.Context, *containeranalysispb.UpdateScanConfigRequest, ...gax.CallOption) (*containeranalysispb.ScanConfig, error) +} + // ContainerAnalysisV1Beta1Client is a client for interacting with Container Analysis API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Retrieves analysis results of Cloud components such as Docker container +// images. The Container Analysis API is an implementation of the +// Grafeas (at grafeas.io) API. +// +// Analysis results are stored as a series of occurrences. An Occurrence +// contains information about a specific analysis instance on a resource. An +// occurrence refers to a Note. A note contains details describing the +// analysis and is generally stored in a separate project, called a Provider. +// Multiple occurrences can refer to the same note. +// +// For example, an SSL vulnerability could affect multiple images. In this case, +// there would be one note for the vulnerability and an occurrence for each +// image with the vulnerability referring to that note. type ContainerAnalysisV1Beta1Client struct { + // The internal transport-dependent client. + internalClient internalContainerAnalysisV1Beta1Client + + // The call options for this service. + CallOptions *ContainerAnalysisV1Beta1CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ContainerAnalysisV1Beta1Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ContainerAnalysisV1Beta1Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ContainerAnalysisV1Beta1Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// SetIamPolicy sets the access control policy on the specified note or occurrence. +// Requires containeranalysis.notes.setIamPolicy or +// containeranalysis.occurrences.setIamPolicy permission if the resource is +// a note or an occurrence, respectively. +// +// The resource takes the format projects/[PROJECT_ID]/notes/[NOTE_ID] for +// notes and projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID] for +// occurrences. +func (c *ContainerAnalysisV1Beta1Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy for a note or an occurrence resource. +// Requires containeranalysis.notes.setIamPolicy or +// containeranalysis.occurrences.setIamPolicy permission if the resource is +// a note or occurrence, respectively. +// +// The resource takes the format projects/[PROJECT_ID]/notes/[NOTE_ID] for +// notes and projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID] for +// occurrences. +func (c *ContainerAnalysisV1Beta1Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns the permissions that a caller has on the specified note or +// occurrence. Requires list permission on the project (for example, +// containeranalysis.notes.list). +// +// The resource takes the format projects/[PROJECT_ID]/notes/[NOTE_ID] for +// notes and projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID] for +// occurrences. +func (c *ContainerAnalysisV1Beta1Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// GetScanConfig gets the specified scan configuration. +func (c *ContainerAnalysisV1Beta1Client) GetScanConfig(ctx context.Context, req *containeranalysispb.GetScanConfigRequest, opts ...gax.CallOption) (*containeranalysispb.ScanConfig, error) { + return c.internalClient.GetScanConfig(ctx, req, opts...) +} + +// ListScanConfigs lists scan configurations for the specified project. +func (c *ContainerAnalysisV1Beta1Client) ListScanConfigs(ctx context.Context, req *containeranalysispb.ListScanConfigsRequest, opts ...gax.CallOption) *ScanConfigIterator { + return c.internalClient.ListScanConfigs(ctx, req, opts...) +} + +// UpdateScanConfig updates the specified scan configuration. +func (c *ContainerAnalysisV1Beta1Client) UpdateScanConfig(ctx context.Context, req *containeranalysispb.UpdateScanConfigRequest, opts ...gax.CallOption) (*containeranalysispb.ScanConfig, error) { + return c.internalClient.UpdateScanConfig(ctx, req, opts...) +} + +// containerAnalysisV1Beta1GRPCClient is a client for interacting with Container Analysis API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type containerAnalysisV1Beta1GRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ContainerAnalysisV1Beta1Client + CallOptions **ContainerAnalysisV1Beta1CallOptions + // The gRPC API client. containerAnalysisV1Beta1Client containeranalysispb.ContainerAnalysisV1Beta1Client - // The call options for this service. - CallOptions *ContainerAnalysisV1Beta1CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewContainerAnalysisV1Beta1Client creates a new container analysis v1 beta1 client. +// NewContainerAnalysisV1Beta1Client creates a new container analysis v1 beta1 client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Retrieves analysis results of Cloud components such as Docker container // images. The Container Analysis API is an implementation of the @@ -129,8 +239,7 @@ type ContainerAnalysisV1Beta1Client struct { // there would be one note for the vulnerability and an occurrence for each // image with the vulnerability referring to that note. func NewContainerAnalysisV1Beta1Client(ctx context.Context, opts ...option.ClientOption) (*ContainerAnalysisV1Beta1Client, error) { - clientOpts := defaultContainerAnalysisV1Beta1ClientOptions() - + clientOpts := defaultContainerAnalysisV1Beta1GRPCClientOptions() if newContainerAnalysisV1Beta1ClientHook != nil { hookOpts, err := newContainerAnalysisV1Beta1ClientHook(ctx, clientHookParams{}) if err != nil { @@ -148,49 +257,44 @@ func NewContainerAnalysisV1Beta1Client(ctx context.Context, opts ...option.Clien if err != nil { return nil, err } - c := &ContainerAnalysisV1Beta1Client{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultContainerAnalysisV1Beta1CallOptions(), + client := ContainerAnalysisV1Beta1Client{CallOptions: defaultContainerAnalysisV1Beta1CallOptions()} + c := &containerAnalysisV1Beta1GRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, containerAnalysisV1Beta1Client: containeranalysispb.NewContainerAnalysisV1Beta1Client(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ContainerAnalysisV1Beta1Client) Connection() *grpc.ClientConn { +func (c *containerAnalysisV1Beta1GRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ContainerAnalysisV1Beta1Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ContainerAnalysisV1Beta1Client) setGoogleClientInfo(keyval ...string) { +func (c *containerAnalysisV1Beta1GRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// SetIamPolicy sets the access control policy on the specified note or occurrence. -// Requires containeranalysis.notes.setIamPolicy or -// containeranalysis.occurrences.setIamPolicy permission if the resource is -// a note or an occurrence, respectively. -// -// The resource takes the format projects/[PROJECT_ID]/notes/[NOTE_ID] for -// notes and projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID] for -// occurrences. -func (c *ContainerAnalysisV1Beta1Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *containerAnalysisV1Beta1GRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *containerAnalysisV1Beta1GRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -198,7 +302,7 @@ func (c *ContainerAnalysisV1Beta1Client) SetIamPolicy(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -211,15 +315,7 @@ func (c *ContainerAnalysisV1Beta1Client) SetIamPolicy(ctx context.Context, req * return resp, nil } -// GetIamPolicy gets the access control policy for a note or an occurrence resource. -// Requires containeranalysis.notes.setIamPolicy or -// containeranalysis.occurrences.setIamPolicy permission if the resource is -// a note or occurrence, respectively. -// -// The resource takes the format projects/[PROJECT_ID]/notes/[NOTE_ID] for -// notes and projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID] for -// occurrences. -func (c *ContainerAnalysisV1Beta1Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *containerAnalysisV1Beta1GRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -227,7 +323,7 @@ func (c *ContainerAnalysisV1Beta1Client) GetIamPolicy(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -240,14 +336,7 @@ func (c *ContainerAnalysisV1Beta1Client) GetIamPolicy(ctx context.Context, req * return resp, nil } -// TestIamPermissions returns the permissions that a caller has on the specified note or -// occurrence. Requires list permission on the project (for example, -// containeranalysis.notes.list). -// -// The resource takes the format projects/[PROJECT_ID]/notes/[NOTE_ID] for -// notes and projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID] for -// occurrences. -func (c *ContainerAnalysisV1Beta1Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *containerAnalysisV1Beta1GRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -255,7 +344,7 @@ func (c *ContainerAnalysisV1Beta1Client) TestIamPermissions(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -268,8 +357,7 @@ func (c *ContainerAnalysisV1Beta1Client) TestIamPermissions(ctx context.Context, return resp, nil } -// GetScanConfig gets the specified scan configuration. -func (c *ContainerAnalysisV1Beta1Client) GetScanConfig(ctx context.Context, req *containeranalysispb.GetScanConfigRequest, opts ...gax.CallOption) (*containeranalysispb.ScanConfig, error) { +func (c *containerAnalysisV1Beta1GRPCClient) GetScanConfig(ctx context.Context, req *containeranalysispb.GetScanConfigRequest, opts ...gax.CallOption) (*containeranalysispb.ScanConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -277,7 +365,7 @@ func (c *ContainerAnalysisV1Beta1Client) GetScanConfig(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetScanConfig[0:len(c.CallOptions.GetScanConfig):len(c.CallOptions.GetScanConfig)], opts...) + opts = append((*c.CallOptions).GetScanConfig[0:len((*c.CallOptions).GetScanConfig):len((*c.CallOptions).GetScanConfig)], opts...) var resp *containeranalysispb.ScanConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -290,11 +378,10 @@ func (c *ContainerAnalysisV1Beta1Client) GetScanConfig(ctx context.Context, req return resp, nil } -// ListScanConfigs lists scan configurations for the specified project. -func (c *ContainerAnalysisV1Beta1Client) ListScanConfigs(ctx context.Context, req *containeranalysispb.ListScanConfigsRequest, opts ...gax.CallOption) *ScanConfigIterator { +func (c *containerAnalysisV1Beta1GRPCClient) ListScanConfigs(ctx context.Context, req *containeranalysispb.ListScanConfigsRequest, opts ...gax.CallOption) *ScanConfigIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListScanConfigs[0:len(c.CallOptions.ListScanConfigs):len(c.CallOptions.ListScanConfigs)], opts...) + opts = append((*c.CallOptions).ListScanConfigs[0:len((*c.CallOptions).ListScanConfigs):len((*c.CallOptions).ListScanConfigs)], opts...) it := &ScanConfigIterator{} req = proto.Clone(req).(*containeranalysispb.ListScanConfigsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*containeranalysispb.ScanConfig, string, error) { @@ -331,8 +418,7 @@ func (c *ContainerAnalysisV1Beta1Client) ListScanConfigs(ctx context.Context, re return it } -// UpdateScanConfig updates the specified scan configuration. -func (c *ContainerAnalysisV1Beta1Client) UpdateScanConfig(ctx context.Context, req *containeranalysispb.UpdateScanConfigRequest, opts ...gax.CallOption) (*containeranalysispb.ScanConfig, error) { +func (c *containerAnalysisV1Beta1GRPCClient) UpdateScanConfig(ctx context.Context, req *containeranalysispb.UpdateScanConfigRequest, opts ...gax.CallOption) (*containeranalysispb.ScanConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -340,7 +426,7 @@ func (c *ContainerAnalysisV1Beta1Client) UpdateScanConfig(ctx context.Context, r } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateScanConfig[0:len(c.CallOptions.UpdateScanConfig):len(c.CallOptions.UpdateScanConfig)], opts...) + opts = append((*c.CallOptions).UpdateScanConfig[0:len((*c.CallOptions).UpdateScanConfig):len((*c.CallOptions).UpdateScanConfig)], opts...) var resp *containeranalysispb.ScanConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/containeranalysis/apiv1beta1/container_analysis_v1_beta1_client_example_test.go b/containeranalysis/apiv1beta1/container_analysis_v1_beta1_client_example_test.go index 6c91331ddb2e..c4fe2e273e94 100644 --- a/containeranalysis/apiv1beta1/container_analysis_v1_beta1_client_example_test.go +++ b/containeranalysis/apiv1beta1/container_analysis_v1_beta1_client_example_test.go @@ -31,18 +31,19 @@ func ExampleNewContainerAnalysisV1Beta1Client() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleContainerAnalysisV1Beta1Client_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := containeranalysis.NewContainerAnalysisV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -56,13 +57,12 @@ func ExampleContainerAnalysisV1Beta1Client_SetIamPolicy() { } func ExampleContainerAnalysisV1Beta1Client_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := containeranalysis.NewContainerAnalysisV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -76,13 +76,12 @@ func ExampleContainerAnalysisV1Beta1Client_GetIamPolicy() { } func ExampleContainerAnalysisV1Beta1Client_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := containeranalysis.NewContainerAnalysisV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. @@ -96,13 +95,12 @@ func ExampleContainerAnalysisV1Beta1Client_TestIamPermissions() { } func ExampleContainerAnalysisV1Beta1Client_GetScanConfig() { - // import containeranalysispb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1" - ctx := context.Background() c, err := containeranalysis.NewContainerAnalysisV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containeranalysispb.GetScanConfigRequest{ // TODO: Fill request struct fields. @@ -116,14 +114,12 @@ func ExampleContainerAnalysisV1Beta1Client_GetScanConfig() { } func ExampleContainerAnalysisV1Beta1Client_ListScanConfigs() { - // import containeranalysispb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := containeranalysis.NewContainerAnalysisV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containeranalysispb.ListScanConfigsRequest{ // TODO: Fill request struct fields. @@ -143,13 +139,12 @@ func ExampleContainerAnalysisV1Beta1Client_ListScanConfigs() { } func ExampleContainerAnalysisV1Beta1Client_UpdateScanConfig() { - // import containeranalysispb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1" - ctx := context.Background() c, err := containeranalysis.NewContainerAnalysisV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containeranalysispb.UpdateScanConfigRequest{ // TODO: Fill request struct fields. diff --git a/containeranalysis/apiv1beta1/doc.go b/containeranalysis/apiv1beta1/doc.go index 782782fc0a20..4584092ab906 100644 --- a/containeranalysis/apiv1beta1/doc.go +++ b/containeranalysis/apiv1beta1/doc.go @@ -20,6 +20,8 @@ // An implementation of the Grafeas API, which stores, and enables querying // and retrieval of critical metadata about all of your software artifacts. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package containeranalysis // import "cloud.google.com/go/containeranalysis/apiv1beta1" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/containeranalysis/apiv1beta1/grafeas_v1_beta1_client.go b/containeranalysis/apiv1beta1/grafeas_v1_beta1_client.go index 17e21f575821..07bc313f7ad2 100644 --- a/containeranalysis/apiv1beta1/grafeas_v1_beta1_client.go +++ b/containeranalysis/apiv1beta1/grafeas_v1_beta1_client.go @@ -56,7 +56,7 @@ type GrafeasV1Beta1CallOptions struct { GetVulnerabilityOccurrencesSummary []gax.CallOption } -func defaultGrafeasV1Beta1ClientOptions() []option.ClientOption { +func defaultGrafeasV1Beta1GRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("containeranalysis.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("containeranalysis.mtls.googleapis.com:443"), @@ -187,27 +187,177 @@ func defaultGrafeasV1Beta1CallOptions() *GrafeasV1Beta1CallOptions { } } +// internalGrafeasV1Beta1Client is an interface that defines the methods availaible from Container Analysis API. +type internalGrafeasV1Beta1Client interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + GetOccurrence(context.Context, *grafeaspb.GetOccurrenceRequest, ...gax.CallOption) (*grafeaspb.Occurrence, error) + ListOccurrences(context.Context, *grafeaspb.ListOccurrencesRequest, ...gax.CallOption) *OccurrenceIterator + DeleteOccurrence(context.Context, *grafeaspb.DeleteOccurrenceRequest, ...gax.CallOption) error + CreateOccurrence(context.Context, *grafeaspb.CreateOccurrenceRequest, ...gax.CallOption) (*grafeaspb.Occurrence, error) + BatchCreateOccurrences(context.Context, *grafeaspb.BatchCreateOccurrencesRequest, ...gax.CallOption) (*grafeaspb.BatchCreateOccurrencesResponse, error) + UpdateOccurrence(context.Context, *grafeaspb.UpdateOccurrenceRequest, ...gax.CallOption) (*grafeaspb.Occurrence, error) + GetOccurrenceNote(context.Context, *grafeaspb.GetOccurrenceNoteRequest, ...gax.CallOption) (*grafeaspb.Note, error) + GetNote(context.Context, *grafeaspb.GetNoteRequest, ...gax.CallOption) (*grafeaspb.Note, error) + ListNotes(context.Context, *grafeaspb.ListNotesRequest, ...gax.CallOption) *NoteIterator + DeleteNote(context.Context, *grafeaspb.DeleteNoteRequest, ...gax.CallOption) error + CreateNote(context.Context, *grafeaspb.CreateNoteRequest, ...gax.CallOption) (*grafeaspb.Note, error) + BatchCreateNotes(context.Context, *grafeaspb.BatchCreateNotesRequest, ...gax.CallOption) (*grafeaspb.BatchCreateNotesResponse, error) + UpdateNote(context.Context, *grafeaspb.UpdateNoteRequest, ...gax.CallOption) (*grafeaspb.Note, error) + ListNoteOccurrences(context.Context, *grafeaspb.ListNoteOccurrencesRequest, ...gax.CallOption) *OccurrenceIterator + GetVulnerabilityOccurrencesSummary(context.Context, *grafeaspb.GetVulnerabilityOccurrencesSummaryRequest, ...gax.CallOption) (*grafeaspb.VulnerabilityOccurrencesSummary, error) +} + // GrafeasV1Beta1Client is a client for interacting with Container Analysis API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Grafeas (at grafeas.io) API. +// +// Retrieves analysis results of Cloud components such as Docker container +// images. +// +// Analysis results are stored as a series of occurrences. An Occurrence +// contains information about a specific analysis instance on a resource. An +// occurrence refers to a Note. A note contains details describing the +// analysis and is generally stored in a separate project, called a Provider. +// Multiple occurrences can refer to the same note. +// +// For example, an SSL vulnerability could affect multiple images. In this case, +// there would be one note for the vulnerability and an occurrence for each +// image with the vulnerability referring to that note. type GrafeasV1Beta1Client struct { + // The internal transport-dependent client. + internalClient internalGrafeasV1Beta1Client + + // The call options for this service. + CallOptions *GrafeasV1Beta1CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *GrafeasV1Beta1Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *GrafeasV1Beta1Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *GrafeasV1Beta1Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// GetOccurrence gets the specified occurrence. +func (c *GrafeasV1Beta1Client) GetOccurrence(ctx context.Context, req *grafeaspb.GetOccurrenceRequest, opts ...gax.CallOption) (*grafeaspb.Occurrence, error) { + return c.internalClient.GetOccurrence(ctx, req, opts...) +} + +// ListOccurrences lists occurrences for the specified project. +func (c *GrafeasV1Beta1Client) ListOccurrences(ctx context.Context, req *grafeaspb.ListOccurrencesRequest, opts ...gax.CallOption) *OccurrenceIterator { + return c.internalClient.ListOccurrences(ctx, req, opts...) +} + +// DeleteOccurrence deletes the specified occurrence. For example, use this method to delete an +// occurrence when the occurrence is no longer applicable for the given +// resource. +func (c *GrafeasV1Beta1Client) DeleteOccurrence(ctx context.Context, req *grafeaspb.DeleteOccurrenceRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteOccurrence(ctx, req, opts...) +} + +// CreateOccurrence creates a new occurrence. +func (c *GrafeasV1Beta1Client) CreateOccurrence(ctx context.Context, req *grafeaspb.CreateOccurrenceRequest, opts ...gax.CallOption) (*grafeaspb.Occurrence, error) { + return c.internalClient.CreateOccurrence(ctx, req, opts...) +} + +// BatchCreateOccurrences creates new occurrences in batch. +func (c *GrafeasV1Beta1Client) BatchCreateOccurrences(ctx context.Context, req *grafeaspb.BatchCreateOccurrencesRequest, opts ...gax.CallOption) (*grafeaspb.BatchCreateOccurrencesResponse, error) { + return c.internalClient.BatchCreateOccurrences(ctx, req, opts...) +} + +// UpdateOccurrence updates the specified occurrence. +func (c *GrafeasV1Beta1Client) UpdateOccurrence(ctx context.Context, req *grafeaspb.UpdateOccurrenceRequest, opts ...gax.CallOption) (*grafeaspb.Occurrence, error) { + return c.internalClient.UpdateOccurrence(ctx, req, opts...) +} + +// GetOccurrenceNote gets the note attached to the specified occurrence. Consumer projects can +// use this method to get a note that belongs to a provider project. +func (c *GrafeasV1Beta1Client) GetOccurrenceNote(ctx context.Context, req *grafeaspb.GetOccurrenceNoteRequest, opts ...gax.CallOption) (*grafeaspb.Note, error) { + return c.internalClient.GetOccurrenceNote(ctx, req, opts...) +} + +// GetNote gets the specified note. +func (c *GrafeasV1Beta1Client) GetNote(ctx context.Context, req *grafeaspb.GetNoteRequest, opts ...gax.CallOption) (*grafeaspb.Note, error) { + return c.internalClient.GetNote(ctx, req, opts...) +} + +// ListNotes lists notes for the specified project. +func (c *GrafeasV1Beta1Client) ListNotes(ctx context.Context, req *grafeaspb.ListNotesRequest, opts ...gax.CallOption) *NoteIterator { + return c.internalClient.ListNotes(ctx, req, opts...) +} + +// DeleteNote deletes the specified note. +func (c *GrafeasV1Beta1Client) DeleteNote(ctx context.Context, req *grafeaspb.DeleteNoteRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteNote(ctx, req, opts...) +} + +// CreateNote creates a new note. +func (c *GrafeasV1Beta1Client) CreateNote(ctx context.Context, req *grafeaspb.CreateNoteRequest, opts ...gax.CallOption) (*grafeaspb.Note, error) { + return c.internalClient.CreateNote(ctx, req, opts...) +} + +// BatchCreateNotes creates new notes in batch. +func (c *GrafeasV1Beta1Client) BatchCreateNotes(ctx context.Context, req *grafeaspb.BatchCreateNotesRequest, opts ...gax.CallOption) (*grafeaspb.BatchCreateNotesResponse, error) { + return c.internalClient.BatchCreateNotes(ctx, req, opts...) +} + +// UpdateNote updates the specified note. +func (c *GrafeasV1Beta1Client) UpdateNote(ctx context.Context, req *grafeaspb.UpdateNoteRequest, opts ...gax.CallOption) (*grafeaspb.Note, error) { + return c.internalClient.UpdateNote(ctx, req, opts...) +} + +// ListNoteOccurrences lists occurrences referencing the specified note. Provider projects can use +// this method to get all occurrences across consumer projects referencing the +// specified note. +func (c *GrafeasV1Beta1Client) ListNoteOccurrences(ctx context.Context, req *grafeaspb.ListNoteOccurrencesRequest, opts ...gax.CallOption) *OccurrenceIterator { + return c.internalClient.ListNoteOccurrences(ctx, req, opts...) +} + +// GetVulnerabilityOccurrencesSummary gets a summary of the number and severity of occurrences. +func (c *GrafeasV1Beta1Client) GetVulnerabilityOccurrencesSummary(ctx context.Context, req *grafeaspb.GetVulnerabilityOccurrencesSummaryRequest, opts ...gax.CallOption) (*grafeaspb.VulnerabilityOccurrencesSummary, error) { + return c.internalClient.GetVulnerabilityOccurrencesSummary(ctx, req, opts...) +} + +// grafeasV1Beta1GRPCClient is a client for interacting with Container Analysis API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type grafeasV1Beta1GRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing GrafeasV1Beta1Client + CallOptions **GrafeasV1Beta1CallOptions + // The gRPC API client. grafeasV1Beta1Client grafeaspb.GrafeasV1Beta1Client - // The call options for this service. - CallOptions *GrafeasV1Beta1CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewGrafeasV1Beta1Client creates a new grafeas v1 beta1 client. +// NewGrafeasV1Beta1Client creates a new grafeas v1 beta1 client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Grafeas (at grafeas.io) API. // @@ -224,8 +374,7 @@ type GrafeasV1Beta1Client struct { // there would be one note for the vulnerability and an occurrence for each // image with the vulnerability referring to that note. func NewGrafeasV1Beta1Client(ctx context.Context, opts ...option.ClientOption) (*GrafeasV1Beta1Client, error) { - clientOpts := defaultGrafeasV1Beta1ClientOptions() - + clientOpts := defaultGrafeasV1Beta1GRPCClientOptions() if newGrafeasV1Beta1ClientHook != nil { hookOpts, err := newGrafeasV1Beta1ClientHook(ctx, clientHookParams{}) if err != nil { @@ -243,42 +392,44 @@ func NewGrafeasV1Beta1Client(ctx context.Context, opts ...option.ClientOption) ( if err != nil { return nil, err } - c := &GrafeasV1Beta1Client{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultGrafeasV1Beta1CallOptions(), + client := GrafeasV1Beta1Client{CallOptions: defaultGrafeasV1Beta1CallOptions()} + c := &grafeasV1Beta1GRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, grafeasV1Beta1Client: grafeaspb.NewGrafeasV1Beta1Client(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *GrafeasV1Beta1Client) Connection() *grpc.ClientConn { +func (c *grafeasV1Beta1GRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *GrafeasV1Beta1Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *GrafeasV1Beta1Client) setGoogleClientInfo(keyval ...string) { +func (c *grafeasV1Beta1GRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// GetOccurrence gets the specified occurrence. -func (c *GrafeasV1Beta1Client) GetOccurrence(ctx context.Context, req *grafeaspb.GetOccurrenceRequest, opts ...gax.CallOption) (*grafeaspb.Occurrence, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *grafeasV1Beta1GRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *grafeasV1Beta1GRPCClient) GetOccurrence(ctx context.Context, req *grafeaspb.GetOccurrenceRequest, opts ...gax.CallOption) (*grafeaspb.Occurrence, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -286,7 +437,7 @@ func (c *GrafeasV1Beta1Client) GetOccurrence(ctx context.Context, req *grafeaspb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetOccurrence[0:len(c.CallOptions.GetOccurrence):len(c.CallOptions.GetOccurrence)], opts...) + opts = append((*c.CallOptions).GetOccurrence[0:len((*c.CallOptions).GetOccurrence):len((*c.CallOptions).GetOccurrence)], opts...) var resp *grafeaspb.Occurrence err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -299,11 +450,10 @@ func (c *GrafeasV1Beta1Client) GetOccurrence(ctx context.Context, req *grafeaspb return resp, nil } -// ListOccurrences lists occurrences for the specified project. -func (c *GrafeasV1Beta1Client) ListOccurrences(ctx context.Context, req *grafeaspb.ListOccurrencesRequest, opts ...gax.CallOption) *OccurrenceIterator { +func (c *grafeasV1Beta1GRPCClient) ListOccurrences(ctx context.Context, req *grafeaspb.ListOccurrencesRequest, opts ...gax.CallOption) *OccurrenceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListOccurrences[0:len(c.CallOptions.ListOccurrences):len(c.CallOptions.ListOccurrences)], opts...) + opts = append((*c.CallOptions).ListOccurrences[0:len((*c.CallOptions).ListOccurrences):len((*c.CallOptions).ListOccurrences)], opts...) it := &OccurrenceIterator{} req = proto.Clone(req).(*grafeaspb.ListOccurrencesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*grafeaspb.Occurrence, string, error) { @@ -340,10 +490,7 @@ func (c *GrafeasV1Beta1Client) ListOccurrences(ctx context.Context, req *grafeas return it } -// DeleteOccurrence deletes the specified occurrence. For example, use this method to delete an -// occurrence when the occurrence is no longer applicable for the given -// resource. -func (c *GrafeasV1Beta1Client) DeleteOccurrence(ctx context.Context, req *grafeaspb.DeleteOccurrenceRequest, opts ...gax.CallOption) error { +func (c *grafeasV1Beta1GRPCClient) DeleteOccurrence(ctx context.Context, req *grafeaspb.DeleteOccurrenceRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -351,7 +498,7 @@ func (c *GrafeasV1Beta1Client) DeleteOccurrence(ctx context.Context, req *grafea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteOccurrence[0:len(c.CallOptions.DeleteOccurrence):len(c.CallOptions.DeleteOccurrence)], opts...) + opts = append((*c.CallOptions).DeleteOccurrence[0:len((*c.CallOptions).DeleteOccurrence):len((*c.CallOptions).DeleteOccurrence)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.grafeasV1Beta1Client.DeleteOccurrence(ctx, req, settings.GRPC...) @@ -360,8 +507,7 @@ func (c *GrafeasV1Beta1Client) DeleteOccurrence(ctx context.Context, req *grafea return err } -// CreateOccurrence creates a new occurrence. -func (c *GrafeasV1Beta1Client) CreateOccurrence(ctx context.Context, req *grafeaspb.CreateOccurrenceRequest, opts ...gax.CallOption) (*grafeaspb.Occurrence, error) { +func (c *grafeasV1Beta1GRPCClient) CreateOccurrence(ctx context.Context, req *grafeaspb.CreateOccurrenceRequest, opts ...gax.CallOption) (*grafeaspb.Occurrence, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -369,7 +515,7 @@ func (c *GrafeasV1Beta1Client) CreateOccurrence(ctx context.Context, req *grafea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateOccurrence[0:len(c.CallOptions.CreateOccurrence):len(c.CallOptions.CreateOccurrence)], opts...) + opts = append((*c.CallOptions).CreateOccurrence[0:len((*c.CallOptions).CreateOccurrence):len((*c.CallOptions).CreateOccurrence)], opts...) var resp *grafeaspb.Occurrence err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -382,8 +528,7 @@ func (c *GrafeasV1Beta1Client) CreateOccurrence(ctx context.Context, req *grafea return resp, nil } -// BatchCreateOccurrences creates new occurrences in batch. -func (c *GrafeasV1Beta1Client) BatchCreateOccurrences(ctx context.Context, req *grafeaspb.BatchCreateOccurrencesRequest, opts ...gax.CallOption) (*grafeaspb.BatchCreateOccurrencesResponse, error) { +func (c *grafeasV1Beta1GRPCClient) BatchCreateOccurrences(ctx context.Context, req *grafeaspb.BatchCreateOccurrencesRequest, opts ...gax.CallOption) (*grafeaspb.BatchCreateOccurrencesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -391,7 +536,7 @@ func (c *GrafeasV1Beta1Client) BatchCreateOccurrences(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchCreateOccurrences[0:len(c.CallOptions.BatchCreateOccurrences):len(c.CallOptions.BatchCreateOccurrences)], opts...) + opts = append((*c.CallOptions).BatchCreateOccurrences[0:len((*c.CallOptions).BatchCreateOccurrences):len((*c.CallOptions).BatchCreateOccurrences)], opts...) var resp *grafeaspb.BatchCreateOccurrencesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -404,8 +549,7 @@ func (c *GrafeasV1Beta1Client) BatchCreateOccurrences(ctx context.Context, req * return resp, nil } -// UpdateOccurrence updates the specified occurrence. -func (c *GrafeasV1Beta1Client) UpdateOccurrence(ctx context.Context, req *grafeaspb.UpdateOccurrenceRequest, opts ...gax.CallOption) (*grafeaspb.Occurrence, error) { +func (c *grafeasV1Beta1GRPCClient) UpdateOccurrence(ctx context.Context, req *grafeaspb.UpdateOccurrenceRequest, opts ...gax.CallOption) (*grafeaspb.Occurrence, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -413,7 +557,7 @@ func (c *GrafeasV1Beta1Client) UpdateOccurrence(ctx context.Context, req *grafea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateOccurrence[0:len(c.CallOptions.UpdateOccurrence):len(c.CallOptions.UpdateOccurrence)], opts...) + opts = append((*c.CallOptions).UpdateOccurrence[0:len((*c.CallOptions).UpdateOccurrence):len((*c.CallOptions).UpdateOccurrence)], opts...) var resp *grafeaspb.Occurrence err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -426,9 +570,7 @@ func (c *GrafeasV1Beta1Client) UpdateOccurrence(ctx context.Context, req *grafea return resp, nil } -// GetOccurrenceNote gets the note attached to the specified occurrence. Consumer projects can -// use this method to get a note that belongs to a provider project. -func (c *GrafeasV1Beta1Client) GetOccurrenceNote(ctx context.Context, req *grafeaspb.GetOccurrenceNoteRequest, opts ...gax.CallOption) (*grafeaspb.Note, error) { +func (c *grafeasV1Beta1GRPCClient) GetOccurrenceNote(ctx context.Context, req *grafeaspb.GetOccurrenceNoteRequest, opts ...gax.CallOption) (*grafeaspb.Note, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -436,7 +578,7 @@ func (c *GrafeasV1Beta1Client) GetOccurrenceNote(ctx context.Context, req *grafe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetOccurrenceNote[0:len(c.CallOptions.GetOccurrenceNote):len(c.CallOptions.GetOccurrenceNote)], opts...) + opts = append((*c.CallOptions).GetOccurrenceNote[0:len((*c.CallOptions).GetOccurrenceNote):len((*c.CallOptions).GetOccurrenceNote)], opts...) var resp *grafeaspb.Note err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -449,8 +591,7 @@ func (c *GrafeasV1Beta1Client) GetOccurrenceNote(ctx context.Context, req *grafe return resp, nil } -// GetNote gets the specified note. -func (c *GrafeasV1Beta1Client) GetNote(ctx context.Context, req *grafeaspb.GetNoteRequest, opts ...gax.CallOption) (*grafeaspb.Note, error) { +func (c *grafeasV1Beta1GRPCClient) GetNote(ctx context.Context, req *grafeaspb.GetNoteRequest, opts ...gax.CallOption) (*grafeaspb.Note, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -458,7 +599,7 @@ func (c *GrafeasV1Beta1Client) GetNote(ctx context.Context, req *grafeaspb.GetNo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetNote[0:len(c.CallOptions.GetNote):len(c.CallOptions.GetNote)], opts...) + opts = append((*c.CallOptions).GetNote[0:len((*c.CallOptions).GetNote):len((*c.CallOptions).GetNote)], opts...) var resp *grafeaspb.Note err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -471,11 +612,10 @@ func (c *GrafeasV1Beta1Client) GetNote(ctx context.Context, req *grafeaspb.GetNo return resp, nil } -// ListNotes lists notes for the specified project. -func (c *GrafeasV1Beta1Client) ListNotes(ctx context.Context, req *grafeaspb.ListNotesRequest, opts ...gax.CallOption) *NoteIterator { +func (c *grafeasV1Beta1GRPCClient) ListNotes(ctx context.Context, req *grafeaspb.ListNotesRequest, opts ...gax.CallOption) *NoteIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListNotes[0:len(c.CallOptions.ListNotes):len(c.CallOptions.ListNotes)], opts...) + opts = append((*c.CallOptions).ListNotes[0:len((*c.CallOptions).ListNotes):len((*c.CallOptions).ListNotes)], opts...) it := &NoteIterator{} req = proto.Clone(req).(*grafeaspb.ListNotesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*grafeaspb.Note, string, error) { @@ -512,8 +652,7 @@ func (c *GrafeasV1Beta1Client) ListNotes(ctx context.Context, req *grafeaspb.Lis return it } -// DeleteNote deletes the specified note. -func (c *GrafeasV1Beta1Client) DeleteNote(ctx context.Context, req *grafeaspb.DeleteNoteRequest, opts ...gax.CallOption) error { +func (c *grafeasV1Beta1GRPCClient) DeleteNote(ctx context.Context, req *grafeaspb.DeleteNoteRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -521,7 +660,7 @@ func (c *GrafeasV1Beta1Client) DeleteNote(ctx context.Context, req *grafeaspb.De } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteNote[0:len(c.CallOptions.DeleteNote):len(c.CallOptions.DeleteNote)], opts...) + opts = append((*c.CallOptions).DeleteNote[0:len((*c.CallOptions).DeleteNote):len((*c.CallOptions).DeleteNote)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.grafeasV1Beta1Client.DeleteNote(ctx, req, settings.GRPC...) @@ -530,8 +669,7 @@ func (c *GrafeasV1Beta1Client) DeleteNote(ctx context.Context, req *grafeaspb.De return err } -// CreateNote creates a new note. -func (c *GrafeasV1Beta1Client) CreateNote(ctx context.Context, req *grafeaspb.CreateNoteRequest, opts ...gax.CallOption) (*grafeaspb.Note, error) { +func (c *grafeasV1Beta1GRPCClient) CreateNote(ctx context.Context, req *grafeaspb.CreateNoteRequest, opts ...gax.CallOption) (*grafeaspb.Note, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -539,7 +677,7 @@ func (c *GrafeasV1Beta1Client) CreateNote(ctx context.Context, req *grafeaspb.Cr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateNote[0:len(c.CallOptions.CreateNote):len(c.CallOptions.CreateNote)], opts...) + opts = append((*c.CallOptions).CreateNote[0:len((*c.CallOptions).CreateNote):len((*c.CallOptions).CreateNote)], opts...) var resp *grafeaspb.Note err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -552,8 +690,7 @@ func (c *GrafeasV1Beta1Client) CreateNote(ctx context.Context, req *grafeaspb.Cr return resp, nil } -// BatchCreateNotes creates new notes in batch. -func (c *GrafeasV1Beta1Client) BatchCreateNotes(ctx context.Context, req *grafeaspb.BatchCreateNotesRequest, opts ...gax.CallOption) (*grafeaspb.BatchCreateNotesResponse, error) { +func (c *grafeasV1Beta1GRPCClient) BatchCreateNotes(ctx context.Context, req *grafeaspb.BatchCreateNotesRequest, opts ...gax.CallOption) (*grafeaspb.BatchCreateNotesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -561,7 +698,7 @@ func (c *GrafeasV1Beta1Client) BatchCreateNotes(ctx context.Context, req *grafea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchCreateNotes[0:len(c.CallOptions.BatchCreateNotes):len(c.CallOptions.BatchCreateNotes)], opts...) + opts = append((*c.CallOptions).BatchCreateNotes[0:len((*c.CallOptions).BatchCreateNotes):len((*c.CallOptions).BatchCreateNotes)], opts...) var resp *grafeaspb.BatchCreateNotesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -574,8 +711,7 @@ func (c *GrafeasV1Beta1Client) BatchCreateNotes(ctx context.Context, req *grafea return resp, nil } -// UpdateNote updates the specified note. -func (c *GrafeasV1Beta1Client) UpdateNote(ctx context.Context, req *grafeaspb.UpdateNoteRequest, opts ...gax.CallOption) (*grafeaspb.Note, error) { +func (c *grafeasV1Beta1GRPCClient) UpdateNote(ctx context.Context, req *grafeaspb.UpdateNoteRequest, opts ...gax.CallOption) (*grafeaspb.Note, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -583,7 +719,7 @@ func (c *GrafeasV1Beta1Client) UpdateNote(ctx context.Context, req *grafeaspb.Up } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateNote[0:len(c.CallOptions.UpdateNote):len(c.CallOptions.UpdateNote)], opts...) + opts = append((*c.CallOptions).UpdateNote[0:len((*c.CallOptions).UpdateNote):len((*c.CallOptions).UpdateNote)], opts...) var resp *grafeaspb.Note err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -596,13 +732,10 @@ func (c *GrafeasV1Beta1Client) UpdateNote(ctx context.Context, req *grafeaspb.Up return resp, nil } -// ListNoteOccurrences lists occurrences referencing the specified note. Provider projects can use -// this method to get all occurrences across consumer projects referencing the -// specified note. -func (c *GrafeasV1Beta1Client) ListNoteOccurrences(ctx context.Context, req *grafeaspb.ListNoteOccurrencesRequest, opts ...gax.CallOption) *OccurrenceIterator { +func (c *grafeasV1Beta1GRPCClient) ListNoteOccurrences(ctx context.Context, req *grafeaspb.ListNoteOccurrencesRequest, opts ...gax.CallOption) *OccurrenceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListNoteOccurrences[0:len(c.CallOptions.ListNoteOccurrences):len(c.CallOptions.ListNoteOccurrences)], opts...) + opts = append((*c.CallOptions).ListNoteOccurrences[0:len((*c.CallOptions).ListNoteOccurrences):len((*c.CallOptions).ListNoteOccurrences)], opts...) it := &OccurrenceIterator{} req = proto.Clone(req).(*grafeaspb.ListNoteOccurrencesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*grafeaspb.Occurrence, string, error) { @@ -639,8 +772,7 @@ func (c *GrafeasV1Beta1Client) ListNoteOccurrences(ctx context.Context, req *gra return it } -// GetVulnerabilityOccurrencesSummary gets a summary of the number and severity of occurrences. -func (c *GrafeasV1Beta1Client) GetVulnerabilityOccurrencesSummary(ctx context.Context, req *grafeaspb.GetVulnerabilityOccurrencesSummaryRequest, opts ...gax.CallOption) (*grafeaspb.VulnerabilityOccurrencesSummary, error) { +func (c *grafeasV1Beta1GRPCClient) GetVulnerabilityOccurrencesSummary(ctx context.Context, req *grafeaspb.GetVulnerabilityOccurrencesSummaryRequest, opts ...gax.CallOption) (*grafeaspb.VulnerabilityOccurrencesSummary, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -648,7 +780,7 @@ func (c *GrafeasV1Beta1Client) GetVulnerabilityOccurrencesSummary(ctx context.Co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetVulnerabilityOccurrencesSummary[0:len(c.CallOptions.GetVulnerabilityOccurrencesSummary):len(c.CallOptions.GetVulnerabilityOccurrencesSummary)], opts...) + opts = append((*c.CallOptions).GetVulnerabilityOccurrencesSummary[0:len((*c.CallOptions).GetVulnerabilityOccurrencesSummary):len((*c.CallOptions).GetVulnerabilityOccurrencesSummary)], opts...) var resp *grafeaspb.VulnerabilityOccurrencesSummary err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/containeranalysis/apiv1beta1/grafeas_v1_beta1_client_example_test.go b/containeranalysis/apiv1beta1/grafeas_v1_beta1_client_example_test.go index ca3120321536..984d7a8c53d0 100644 --- a/containeranalysis/apiv1beta1/grafeas_v1_beta1_client_example_test.go +++ b/containeranalysis/apiv1beta1/grafeas_v1_beta1_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewGrafeasV1Beta1Client() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleGrafeasV1Beta1Client_GetOccurrence() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.GetOccurrenceRequest{ // TODO: Fill request struct fields. @@ -55,14 +56,12 @@ func ExampleGrafeasV1Beta1Client_GetOccurrence() { } func ExampleGrafeasV1Beta1Client_ListOccurrences() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.ListOccurrencesRequest{ // TODO: Fill request struct fields. @@ -87,6 +86,7 @@ func ExampleGrafeasV1Beta1Client_DeleteOccurrence() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.DeleteOccurrenceRequest{ // TODO: Fill request struct fields. @@ -98,13 +98,12 @@ func ExampleGrafeasV1Beta1Client_DeleteOccurrence() { } func ExampleGrafeasV1Beta1Client_CreateOccurrence() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.CreateOccurrenceRequest{ // TODO: Fill request struct fields. @@ -118,13 +117,12 @@ func ExampleGrafeasV1Beta1Client_CreateOccurrence() { } func ExampleGrafeasV1Beta1Client_BatchCreateOccurrences() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.BatchCreateOccurrencesRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleGrafeasV1Beta1Client_BatchCreateOccurrences() { } func ExampleGrafeasV1Beta1Client_UpdateOccurrence() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.UpdateOccurrenceRequest{ // TODO: Fill request struct fields. @@ -158,13 +155,12 @@ func ExampleGrafeasV1Beta1Client_UpdateOccurrence() { } func ExampleGrafeasV1Beta1Client_GetOccurrenceNote() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.GetOccurrenceNoteRequest{ // TODO: Fill request struct fields. @@ -178,13 +174,12 @@ func ExampleGrafeasV1Beta1Client_GetOccurrenceNote() { } func ExampleGrafeasV1Beta1Client_GetNote() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.GetNoteRequest{ // TODO: Fill request struct fields. @@ -198,14 +193,12 @@ func ExampleGrafeasV1Beta1Client_GetNote() { } func ExampleGrafeasV1Beta1Client_ListNotes() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.ListNotesRequest{ // TODO: Fill request struct fields. @@ -230,6 +223,7 @@ func ExampleGrafeasV1Beta1Client_DeleteNote() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.DeleteNoteRequest{ // TODO: Fill request struct fields. @@ -241,13 +235,12 @@ func ExampleGrafeasV1Beta1Client_DeleteNote() { } func ExampleGrafeasV1Beta1Client_CreateNote() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.CreateNoteRequest{ // TODO: Fill request struct fields. @@ -261,13 +254,12 @@ func ExampleGrafeasV1Beta1Client_CreateNote() { } func ExampleGrafeasV1Beta1Client_BatchCreateNotes() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.BatchCreateNotesRequest{ // TODO: Fill request struct fields. @@ -281,13 +273,12 @@ func ExampleGrafeasV1Beta1Client_BatchCreateNotes() { } func ExampleGrafeasV1Beta1Client_UpdateNote() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.UpdateNoteRequest{ // TODO: Fill request struct fields. @@ -301,14 +292,12 @@ func ExampleGrafeasV1Beta1Client_UpdateNote() { } func ExampleGrafeasV1Beta1Client_ListNoteOccurrences() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.ListNoteOccurrencesRequest{ // TODO: Fill request struct fields. @@ -328,13 +317,12 @@ func ExampleGrafeasV1Beta1Client_ListNoteOccurrences() { } func ExampleGrafeasV1Beta1Client_GetVulnerabilityOccurrencesSummary() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.GetVulnerabilityOccurrencesSummaryRequest{ // TODO: Fill request struct fields. diff --git a/datacatalog/apiv1/data_catalog_client.go b/datacatalog/apiv1/data_catalog_client.go index b3c460131eea..becde35573a6 100644 --- a/datacatalog/apiv1/data_catalog_client.go +++ b/datacatalog/apiv1/data_catalog_client.go @@ -70,7 +70,7 @@ type CallOptions struct { TestIamPermissions []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("datacatalog.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("datacatalog.mtls.googleapis.com:443"), @@ -195,33 +195,396 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Google Cloud Data Catalog API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + SearchCatalog(context.Context, *datacatalogpb.SearchCatalogRequest, ...gax.CallOption) *SearchCatalogResultIterator + CreateEntryGroup(context.Context, *datacatalogpb.CreateEntryGroupRequest, ...gax.CallOption) (*datacatalogpb.EntryGroup, error) + GetEntryGroup(context.Context, *datacatalogpb.GetEntryGroupRequest, ...gax.CallOption) (*datacatalogpb.EntryGroup, error) + UpdateEntryGroup(context.Context, *datacatalogpb.UpdateEntryGroupRequest, ...gax.CallOption) (*datacatalogpb.EntryGroup, error) + DeleteEntryGroup(context.Context, *datacatalogpb.DeleteEntryGroupRequest, ...gax.CallOption) error + ListEntryGroups(context.Context, *datacatalogpb.ListEntryGroupsRequest, ...gax.CallOption) *EntryGroupIterator + CreateEntry(context.Context, *datacatalogpb.CreateEntryRequest, ...gax.CallOption) (*datacatalogpb.Entry, error) + UpdateEntry(context.Context, *datacatalogpb.UpdateEntryRequest, ...gax.CallOption) (*datacatalogpb.Entry, error) + DeleteEntry(context.Context, *datacatalogpb.DeleteEntryRequest, ...gax.CallOption) error + GetEntry(context.Context, *datacatalogpb.GetEntryRequest, ...gax.CallOption) (*datacatalogpb.Entry, error) + LookupEntry(context.Context, *datacatalogpb.LookupEntryRequest, ...gax.CallOption) (*datacatalogpb.Entry, error) + ListEntries(context.Context, *datacatalogpb.ListEntriesRequest, ...gax.CallOption) *EntryIterator + CreateTagTemplate(context.Context, *datacatalogpb.CreateTagTemplateRequest, ...gax.CallOption) (*datacatalogpb.TagTemplate, error) + GetTagTemplate(context.Context, *datacatalogpb.GetTagTemplateRequest, ...gax.CallOption) (*datacatalogpb.TagTemplate, error) + UpdateTagTemplate(context.Context, *datacatalogpb.UpdateTagTemplateRequest, ...gax.CallOption) (*datacatalogpb.TagTemplate, error) + DeleteTagTemplate(context.Context, *datacatalogpb.DeleteTagTemplateRequest, ...gax.CallOption) error + CreateTagTemplateField(context.Context, *datacatalogpb.CreateTagTemplateFieldRequest, ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) + UpdateTagTemplateField(context.Context, *datacatalogpb.UpdateTagTemplateFieldRequest, ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) + RenameTagTemplateField(context.Context, *datacatalogpb.RenameTagTemplateFieldRequest, ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) + RenameTagTemplateFieldEnumValue(context.Context, *datacatalogpb.RenameTagTemplateFieldEnumValueRequest, ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) + DeleteTagTemplateField(context.Context, *datacatalogpb.DeleteTagTemplateFieldRequest, ...gax.CallOption) error + CreateTag(context.Context, *datacatalogpb.CreateTagRequest, ...gax.CallOption) (*datacatalogpb.Tag, error) + UpdateTag(context.Context, *datacatalogpb.UpdateTagRequest, ...gax.CallOption) (*datacatalogpb.Tag, error) + DeleteTag(context.Context, *datacatalogpb.DeleteTagRequest, ...gax.CallOption) error + ListTags(context.Context, *datacatalogpb.ListTagsRequest, ...gax.CallOption) *TagIterator + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) +} + // Client is a client for interacting with Google Cloud Data Catalog API. +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Data Catalog API service allows clients to discover, understand, and manage +// their data. +type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// SearchCatalog searches Data Catalog for multiple resources like entries, tags that +// match a query. +// +// This is a custom method +// (https://cloud.google.com/apis/design/custom_methods (at https://cloud.google.com/apis/design/custom_methods)) and does not return +// the complete resource, only the resource identifier and high level +// fields. Clients can subsequently call Get methods. +// +// Note that Data Catalog search queries do not guarantee full recall. Query +// results that match your query may not be returned, even in subsequent +// result pages. Also note that results returned (and not returned) can vary +// across repeated search queries. +// +// See Data Catalog Search +// Syntax (at https://cloud.google.com/data-catalog/docs/how-to/search-reference) +// for more information. +func (c *Client) SearchCatalog(ctx context.Context, req *datacatalogpb.SearchCatalogRequest, opts ...gax.CallOption) *SearchCatalogResultIterator { + return c.internalClient.SearchCatalog(ctx, req, opts...) +} + +// CreateEntryGroup creates an EntryGroup. +// +// An entry group contains logically related entries together with Cloud +// Identity and Access Management policies that specify the users who can +// create, edit, and view entries within the entry group. +// +// Data Catalog automatically creates an entry group for BigQuery entries +// (“@bigquery”) and Pub/Sub topics ("@pubsub"). Users create their own entry +// group to contain Cloud Storage fileset entries or custom type entries, +// and the IAM policies associated with those entries. Entry groups, like +// entries, can be searched. +// +// A maximum of 10,000 entry groups may be created per organization across all +// locations. +// +// Users should enable the Data Catalog API in the project identified by +// the parent parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) CreateEntryGroup(ctx context.Context, req *datacatalogpb.CreateEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { + return c.internalClient.CreateEntryGroup(ctx, req, opts...) +} + +// GetEntryGroup gets an EntryGroup. +func (c *Client) GetEntryGroup(ctx context.Context, req *datacatalogpb.GetEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { + return c.internalClient.GetEntryGroup(ctx, req, opts...) +} + +// UpdateEntryGroup updates an EntryGroup. The user should enable the Data Catalog API in the +// project identified by the entry_group.name parameter (see [Data Catalog +// Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) UpdateEntryGroup(ctx context.Context, req *datacatalogpb.UpdateEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { + return c.internalClient.UpdateEntryGroup(ctx, req, opts...) +} + +// DeleteEntryGroup deletes an EntryGroup. Only entry groups that do not contain entries can be +// deleted. Users should enable the Data Catalog API in the project +// identified by the name parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) DeleteEntryGroup(ctx context.Context, req *datacatalogpb.DeleteEntryGroupRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteEntryGroup(ctx, req, opts...) +} + +// ListEntryGroups lists entry groups. +func (c *Client) ListEntryGroups(ctx context.Context, req *datacatalogpb.ListEntryGroupsRequest, opts ...gax.CallOption) *EntryGroupIterator { + return c.internalClient.ListEntryGroups(ctx, req, opts...) +} + +// CreateEntry creates an entry. Only entries of types ‘FILESET’, ‘CLUSTER’, ‘DATA_STREAM’ +// or with a user-specified type can be created. +// +// Users should enable the Data Catalog API in the project identified by +// the parent parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +// +// A maximum of 100,000 entries may be created per entry group. +func (c *Client) CreateEntry(ctx context.Context, req *datacatalogpb.CreateEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { + return c.internalClient.CreateEntry(ctx, req, opts...) +} + +// UpdateEntry updates an existing entry. +// Users should enable the Data Catalog API in the project identified by +// the entry.name parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) UpdateEntry(ctx context.Context, req *datacatalogpb.UpdateEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { + return c.internalClient.UpdateEntry(ctx, req, opts...) +} + +// DeleteEntry deletes an existing entry. Only entries created through +// CreateEntry +// method can be deleted. +// Users should enable the Data Catalog API in the project identified by +// the name parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) DeleteEntry(ctx context.Context, req *datacatalogpb.DeleteEntryRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteEntry(ctx, req, opts...) +} + +// GetEntry gets an entry. +func (c *Client) GetEntry(ctx context.Context, req *datacatalogpb.GetEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { + return c.internalClient.GetEntry(ctx, req, opts...) +} + +// LookupEntry get an entry by target resource name. This method allows clients to use +// the resource name from the source Google Cloud Platform service to get the +// Data Catalog Entry. +func (c *Client) LookupEntry(ctx context.Context, req *datacatalogpb.LookupEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { + return c.internalClient.LookupEntry(ctx, req, opts...) +} + +// ListEntries lists entries. +func (c *Client) ListEntries(ctx context.Context, req *datacatalogpb.ListEntriesRequest, opts ...gax.CallOption) *EntryIterator { + return c.internalClient.ListEntries(ctx, req, opts...) +} + +// CreateTagTemplate creates a tag template. The user should enable the Data Catalog API in +// the project identified by the parent parameter (see Data Catalog +// Resource +// Project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project) +// for more information). +func (c *Client) CreateTagTemplate(ctx context.Context, req *datacatalogpb.CreateTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { + return c.internalClient.CreateTagTemplate(ctx, req, opts...) +} + +// GetTagTemplate gets a tag template. +func (c *Client) GetTagTemplate(ctx context.Context, req *datacatalogpb.GetTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { + return c.internalClient.GetTagTemplate(ctx, req, opts...) +} + +// UpdateTagTemplate updates a tag template. This method cannot be used to update the fields of +// a template. The tag template fields are represented as separate resources +// and should be updated using their own create/update/delete methods. +// Users should enable the Data Catalog API in the project identified by +// the tag_template.name parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) UpdateTagTemplate(ctx context.Context, req *datacatalogpb.UpdateTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { + return c.internalClient.UpdateTagTemplate(ctx, req, opts...) +} + +// DeleteTagTemplate deletes a tag template and all tags using the template. +// Users should enable the Data Catalog API in the project identified by +// the name parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) DeleteTagTemplate(ctx context.Context, req *datacatalogpb.DeleteTagTemplateRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTagTemplate(ctx, req, opts...) +} + +// CreateTagTemplateField creates a field in a tag template. The user should enable the Data Catalog +// API in the project identified by the parent parameter (see +// Data Catalog Resource +// Project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project) +// for more information). +func (c *Client) CreateTagTemplateField(ctx context.Context, req *datacatalogpb.CreateTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { + return c.internalClient.CreateTagTemplateField(ctx, req, opts...) +} + +// UpdateTagTemplateField updates a field in a tag template. This method cannot be used to update the +// field type. Users should enable the Data Catalog API in the project +// identified by the name parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) UpdateTagTemplateField(ctx context.Context, req *datacatalogpb.UpdateTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { + return c.internalClient.UpdateTagTemplateField(ctx, req, opts...) +} + +// RenameTagTemplateField renames a field in a tag template. The user should enable the Data Catalog +// API in the project identified by the name parameter (see Data Catalog +// Resource +// Project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project) +// for more information). +func (c *Client) RenameTagTemplateField(ctx context.Context, req *datacatalogpb.RenameTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { + return c.internalClient.RenameTagTemplateField(ctx, req, opts...) +} + +// RenameTagTemplateFieldEnumValue renames an enum value in a tag template. The enum values have to be unique +// within one enum field. +func (c *Client) RenameTagTemplateFieldEnumValue(ctx context.Context, req *datacatalogpb.RenameTagTemplateFieldEnumValueRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { + return c.internalClient.RenameTagTemplateFieldEnumValue(ctx, req, opts...) +} + +// DeleteTagTemplateField deletes a field in a tag template and all uses of that field. +// Users should enable the Data Catalog API in the project identified by +// the name parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) DeleteTagTemplateField(ctx context.Context, req *datacatalogpb.DeleteTagTemplateFieldRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTagTemplateField(ctx, req, opts...) +} + +// CreateTag creates a tag on an Entry. +// Note: The project identified by the parent parameter for the +// tag (at https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries.tags/create#path-parameters) +// and the +// tag +// template (at https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.tagTemplates/create#path-parameters) +// used to create the tag must be from the same organization. +func (c *Client) CreateTag(ctx context.Context, req *datacatalogpb.CreateTagRequest, opts ...gax.CallOption) (*datacatalogpb.Tag, error) { + return c.internalClient.CreateTag(ctx, req, opts...) +} + +// UpdateTag updates an existing tag. +func (c *Client) UpdateTag(ctx context.Context, req *datacatalogpb.UpdateTagRequest, opts ...gax.CallOption) (*datacatalogpb.Tag, error) { + return c.internalClient.UpdateTag(ctx, req, opts...) +} + +// DeleteTag deletes a tag. +func (c *Client) DeleteTag(ctx context.Context, req *datacatalogpb.DeleteTagRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTag(ctx, req, opts...) +} + +// ListTags lists the tags on an Entry. +func (c *Client) ListTags(ctx context.Context, req *datacatalogpb.ListTagsRequest, opts ...gax.CallOption) *TagIterator { + return c.internalClient.ListTags(ctx, req, opts...) +} + +// SetIamPolicy sets the access control policy for a resource. Replaces any existing +// policy. +// Supported resources are: +// +// Tag templates. +// +// Entries. +// +// Entry groups. +// Note, this method cannot be used to manage policies for BigQuery, Pub/Sub +// and any external Google Cloud Platform resources synced to Data Catalog. +// +// Callers must have following Google IAM permission +// +// datacatalog.tagTemplates.setIamPolicy to set policies on tag +// templates. +// +// datacatalog.entries.setIamPolicy to set policies on entries. +// +// datacatalog.entryGroups.setIamPolicy to set policies on entry groups. +func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy for a resource. A NOT_FOUND error +// is returned if the resource does not exist. An empty policy is returned +// if the resource exists but does not have a policy set on it. +// +// Supported resources are: +// +// Tag templates. +// +// Entries. +// +// Entry groups. +// Note, this method cannot be used to manage policies for BigQuery, Pub/Sub +// and any external Google Cloud Platform resources synced to Data Catalog. +// +// Callers must have following Google IAM permission +// +// datacatalog.tagTemplates.getIamPolicy to get policies on tag +// templates. +// +// datacatalog.entries.getIamPolicy to get policies on entries. +// +// datacatalog.entryGroups.getIamPolicy to get policies on entry groups. +func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns the caller’s permissions on a resource. +// If the resource does not exist, an empty set of permissions is returned +// (We don’t return a NOT_FOUND error). +// +// Supported resources are: +// +// Tag templates. +// +// Entries. +// +// Entry groups. +// Note, this method cannot be used to manage policies for BigQuery, Pub/Sub +// and any external Google Cloud Platform resources synced to Data Catalog. +// +// A caller is not required to have Google IAM permission to make this +// request. +func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Google Cloud Data Catalog API over gRPC transport. // // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. -type Client struct { +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client datacatalogpb.DataCatalogClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new data catalog client. +// NewClient creates a new data catalog client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Data Catalog API service allows clients to discover, understand, and manage // their data. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -239,59 +602,46 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: datacatalogpb.NewDataCatalogClient(connPool), + client: datacatalogpb.NewDataCatalogClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// SearchCatalog searches Data Catalog for multiple resources like entries, tags that -// match a query. -// -// This is a custom method -// (https://cloud.google.com/apis/design/custom_methods (at https://cloud.google.com/apis/design/custom_methods)) and does not return -// the complete resource, only the resource identifier and high level -// fields. Clients can subsequently call Get methods. -// -// Note that Data Catalog search queries do not guarantee full recall. Query -// results that match your query may not be returned, even in subsequent -// result pages. Also note that results returned (and not returned) can vary -// across repeated search queries. -// -// See Data Catalog Search -// Syntax (at https://cloud.google.com/data-catalog/docs/how-to/search-reference) -// for more information. -func (c *Client) SearchCatalog(ctx context.Context, req *datacatalogpb.SearchCatalogRequest, opts ...gax.CallOption) *SearchCatalogResultIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) SearchCatalog(ctx context.Context, req *datacatalogpb.SearchCatalogRequest, opts ...gax.CallOption) *SearchCatalogResultIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.SearchCatalog[0:len(c.CallOptions.SearchCatalog):len(c.CallOptions.SearchCatalog)], opts...) + opts = append((*c.CallOptions).SearchCatalog[0:len((*c.CallOptions).SearchCatalog):len((*c.CallOptions).SearchCatalog)], opts...) it := &SearchCatalogResultIterator{} req = proto.Clone(req).(*datacatalogpb.SearchCatalogRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.SearchCatalogResult, string, error) { @@ -328,26 +678,7 @@ func (c *Client) SearchCatalog(ctx context.Context, req *datacatalogpb.SearchCat return it } -// CreateEntryGroup creates an EntryGroup. -// -// An entry group contains logically related entries together with Cloud -// Identity and Access Management policies that specify the users who can -// create, edit, and view entries within the entry group. -// -// Data Catalog automatically creates an entry group for BigQuery entries -// (“@bigquery”) and Pub/Sub topics ("@pubsub"). Users create their own entry -// group to contain Cloud Storage fileset entries or custom type entries, -// and the IAM policies associated with those entries. Entry groups, like -// entries, can be searched. -// -// A maximum of 10,000 entry groups may be created per organization across all -// locations. -// -// Users should enable the Data Catalog API in the project identified by -// the parent parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) CreateEntryGroup(ctx context.Context, req *datacatalogpb.CreateEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { +func (c *gRPCClient) CreateEntryGroup(ctx context.Context, req *datacatalogpb.CreateEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -355,7 +686,7 @@ func (c *Client) CreateEntryGroup(ctx context.Context, req *datacatalogpb.Create } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateEntryGroup[0:len(c.CallOptions.CreateEntryGroup):len(c.CallOptions.CreateEntryGroup)], opts...) + opts = append((*c.CallOptions).CreateEntryGroup[0:len((*c.CallOptions).CreateEntryGroup):len((*c.CallOptions).CreateEntryGroup)], opts...) var resp *datacatalogpb.EntryGroup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -368,8 +699,7 @@ func (c *Client) CreateEntryGroup(ctx context.Context, req *datacatalogpb.Create return resp, nil } -// GetEntryGroup gets an EntryGroup. -func (c *Client) GetEntryGroup(ctx context.Context, req *datacatalogpb.GetEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { +func (c *gRPCClient) GetEntryGroup(ctx context.Context, req *datacatalogpb.GetEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -377,7 +707,7 @@ func (c *Client) GetEntryGroup(ctx context.Context, req *datacatalogpb.GetEntryG } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEntryGroup[0:len(c.CallOptions.GetEntryGroup):len(c.CallOptions.GetEntryGroup)], opts...) + opts = append((*c.CallOptions).GetEntryGroup[0:len((*c.CallOptions).GetEntryGroup):len((*c.CallOptions).GetEntryGroup)], opts...) var resp *datacatalogpb.EntryGroup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -390,12 +720,7 @@ func (c *Client) GetEntryGroup(ctx context.Context, req *datacatalogpb.GetEntryG return resp, nil } -// UpdateEntryGroup updates an EntryGroup. The user should enable the Data Catalog API in the -// project identified by the entry_group.name parameter (see [Data Catalog -// Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) UpdateEntryGroup(ctx context.Context, req *datacatalogpb.UpdateEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { +func (c *gRPCClient) UpdateEntryGroup(ctx context.Context, req *datacatalogpb.UpdateEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -403,7 +728,7 @@ func (c *Client) UpdateEntryGroup(ctx context.Context, req *datacatalogpb.Update } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "entry_group.name", url.QueryEscape(req.GetEntryGroup().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateEntryGroup[0:len(c.CallOptions.UpdateEntryGroup):len(c.CallOptions.UpdateEntryGroup)], opts...) + opts = append((*c.CallOptions).UpdateEntryGroup[0:len((*c.CallOptions).UpdateEntryGroup):len((*c.CallOptions).UpdateEntryGroup)], opts...) var resp *datacatalogpb.EntryGroup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -416,12 +741,7 @@ func (c *Client) UpdateEntryGroup(ctx context.Context, req *datacatalogpb.Update return resp, nil } -// DeleteEntryGroup deletes an EntryGroup. Only entry groups that do not contain entries can be -// deleted. Users should enable the Data Catalog API in the project -// identified by the name parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) DeleteEntryGroup(ctx context.Context, req *datacatalogpb.DeleteEntryGroupRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteEntryGroup(ctx context.Context, req *datacatalogpb.DeleteEntryGroupRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -429,7 +749,7 @@ func (c *Client) DeleteEntryGroup(ctx context.Context, req *datacatalogpb.Delete } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteEntryGroup[0:len(c.CallOptions.DeleteEntryGroup):len(c.CallOptions.DeleteEntryGroup)], opts...) + opts = append((*c.CallOptions).DeleteEntryGroup[0:len((*c.CallOptions).DeleteEntryGroup):len((*c.CallOptions).DeleteEntryGroup)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteEntryGroup(ctx, req, settings.GRPC...) @@ -438,11 +758,10 @@ func (c *Client) DeleteEntryGroup(ctx context.Context, req *datacatalogpb.Delete return err } -// ListEntryGroups lists entry groups. -func (c *Client) ListEntryGroups(ctx context.Context, req *datacatalogpb.ListEntryGroupsRequest, opts ...gax.CallOption) *EntryGroupIterator { +func (c *gRPCClient) ListEntryGroups(ctx context.Context, req *datacatalogpb.ListEntryGroupsRequest, opts ...gax.CallOption) *EntryGroupIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListEntryGroups[0:len(c.CallOptions.ListEntryGroups):len(c.CallOptions.ListEntryGroups)], opts...) + opts = append((*c.CallOptions).ListEntryGroups[0:len((*c.CallOptions).ListEntryGroups):len((*c.CallOptions).ListEntryGroups)], opts...) it := &EntryGroupIterator{} req = proto.Clone(req).(*datacatalogpb.ListEntryGroupsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.EntryGroup, string, error) { @@ -479,16 +798,7 @@ func (c *Client) ListEntryGroups(ctx context.Context, req *datacatalogpb.ListEnt return it } -// CreateEntry creates an entry. Only entries of types ‘FILESET’, ‘CLUSTER’, ‘DATA_STREAM’ -// or with a user-specified type can be created. -// -// Users should enable the Data Catalog API in the project identified by -// the parent parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -// -// A maximum of 100,000 entries may be created per entry group. -func (c *Client) CreateEntry(ctx context.Context, req *datacatalogpb.CreateEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { +func (c *gRPCClient) CreateEntry(ctx context.Context, req *datacatalogpb.CreateEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -496,7 +806,7 @@ func (c *Client) CreateEntry(ctx context.Context, req *datacatalogpb.CreateEntry } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateEntry[0:len(c.CallOptions.CreateEntry):len(c.CallOptions.CreateEntry)], opts...) + opts = append((*c.CallOptions).CreateEntry[0:len((*c.CallOptions).CreateEntry):len((*c.CallOptions).CreateEntry)], opts...) var resp *datacatalogpb.Entry err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -509,12 +819,7 @@ func (c *Client) CreateEntry(ctx context.Context, req *datacatalogpb.CreateEntry return resp, nil } -// UpdateEntry updates an existing entry. -// Users should enable the Data Catalog API in the project identified by -// the entry.name parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) UpdateEntry(ctx context.Context, req *datacatalogpb.UpdateEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { +func (c *gRPCClient) UpdateEntry(ctx context.Context, req *datacatalogpb.UpdateEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -522,7 +827,7 @@ func (c *Client) UpdateEntry(ctx context.Context, req *datacatalogpb.UpdateEntry } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "entry.name", url.QueryEscape(req.GetEntry().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateEntry[0:len(c.CallOptions.UpdateEntry):len(c.CallOptions.UpdateEntry)], opts...) + opts = append((*c.CallOptions).UpdateEntry[0:len((*c.CallOptions).UpdateEntry):len((*c.CallOptions).UpdateEntry)], opts...) var resp *datacatalogpb.Entry err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -535,14 +840,7 @@ func (c *Client) UpdateEntry(ctx context.Context, req *datacatalogpb.UpdateEntry return resp, nil } -// DeleteEntry deletes an existing entry. Only entries created through -// CreateEntry -// method can be deleted. -// Users should enable the Data Catalog API in the project identified by -// the name parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) DeleteEntry(ctx context.Context, req *datacatalogpb.DeleteEntryRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteEntry(ctx context.Context, req *datacatalogpb.DeleteEntryRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -550,7 +848,7 @@ func (c *Client) DeleteEntry(ctx context.Context, req *datacatalogpb.DeleteEntry } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteEntry[0:len(c.CallOptions.DeleteEntry):len(c.CallOptions.DeleteEntry)], opts...) + opts = append((*c.CallOptions).DeleteEntry[0:len((*c.CallOptions).DeleteEntry):len((*c.CallOptions).DeleteEntry)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteEntry(ctx, req, settings.GRPC...) @@ -559,8 +857,7 @@ func (c *Client) DeleteEntry(ctx context.Context, req *datacatalogpb.DeleteEntry return err } -// GetEntry gets an entry. -func (c *Client) GetEntry(ctx context.Context, req *datacatalogpb.GetEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { +func (c *gRPCClient) GetEntry(ctx context.Context, req *datacatalogpb.GetEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -568,7 +865,7 @@ func (c *Client) GetEntry(ctx context.Context, req *datacatalogpb.GetEntryReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEntry[0:len(c.CallOptions.GetEntry):len(c.CallOptions.GetEntry)], opts...) + opts = append((*c.CallOptions).GetEntry[0:len((*c.CallOptions).GetEntry):len((*c.CallOptions).GetEntry)], opts...) var resp *datacatalogpb.Entry err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -581,17 +878,14 @@ func (c *Client) GetEntry(ctx context.Context, req *datacatalogpb.GetEntryReques return resp, nil } -// LookupEntry get an entry by target resource name. This method allows clients to use -// the resource name from the source Google Cloud Platform service to get the -// Data Catalog Entry. -func (c *Client) LookupEntry(ctx context.Context, req *datacatalogpb.LookupEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { +func (c *gRPCClient) LookupEntry(ctx context.Context, req *datacatalogpb.LookupEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.LookupEntry[0:len(c.CallOptions.LookupEntry):len(c.CallOptions.LookupEntry)], opts...) + opts = append((*c.CallOptions).LookupEntry[0:len((*c.CallOptions).LookupEntry):len((*c.CallOptions).LookupEntry)], opts...) var resp *datacatalogpb.Entry err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -604,11 +898,10 @@ func (c *Client) LookupEntry(ctx context.Context, req *datacatalogpb.LookupEntry return resp, nil } -// ListEntries lists entries. -func (c *Client) ListEntries(ctx context.Context, req *datacatalogpb.ListEntriesRequest, opts ...gax.CallOption) *EntryIterator { +func (c *gRPCClient) ListEntries(ctx context.Context, req *datacatalogpb.ListEntriesRequest, opts ...gax.CallOption) *EntryIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListEntries[0:len(c.CallOptions.ListEntries):len(c.CallOptions.ListEntries)], opts...) + opts = append((*c.CallOptions).ListEntries[0:len((*c.CallOptions).ListEntries):len((*c.CallOptions).ListEntries)], opts...) it := &EntryIterator{} req = proto.Clone(req).(*datacatalogpb.ListEntriesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.Entry, string, error) { @@ -645,12 +938,7 @@ func (c *Client) ListEntries(ctx context.Context, req *datacatalogpb.ListEntries return it } -// CreateTagTemplate creates a tag template. The user should enable the Data Catalog API in -// the project identified by the parent parameter (see Data Catalog -// Resource -// Project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project) -// for more information). -func (c *Client) CreateTagTemplate(ctx context.Context, req *datacatalogpb.CreateTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { +func (c *gRPCClient) CreateTagTemplate(ctx context.Context, req *datacatalogpb.CreateTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -658,7 +946,7 @@ func (c *Client) CreateTagTemplate(ctx context.Context, req *datacatalogpb.Creat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTagTemplate[0:len(c.CallOptions.CreateTagTemplate):len(c.CallOptions.CreateTagTemplate)], opts...) + opts = append((*c.CallOptions).CreateTagTemplate[0:len((*c.CallOptions).CreateTagTemplate):len((*c.CallOptions).CreateTagTemplate)], opts...) var resp *datacatalogpb.TagTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -671,8 +959,7 @@ func (c *Client) CreateTagTemplate(ctx context.Context, req *datacatalogpb.Creat return resp, nil } -// GetTagTemplate gets a tag template. -func (c *Client) GetTagTemplate(ctx context.Context, req *datacatalogpb.GetTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { +func (c *gRPCClient) GetTagTemplate(ctx context.Context, req *datacatalogpb.GetTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -680,7 +967,7 @@ func (c *Client) GetTagTemplate(ctx context.Context, req *datacatalogpb.GetTagTe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTagTemplate[0:len(c.CallOptions.GetTagTemplate):len(c.CallOptions.GetTagTemplate)], opts...) + opts = append((*c.CallOptions).GetTagTemplate[0:len((*c.CallOptions).GetTagTemplate):len((*c.CallOptions).GetTagTemplate)], opts...) var resp *datacatalogpb.TagTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -693,14 +980,7 @@ func (c *Client) GetTagTemplate(ctx context.Context, req *datacatalogpb.GetTagTe return resp, nil } -// UpdateTagTemplate updates a tag template. This method cannot be used to update the fields of -// a template. The tag template fields are represented as separate resources -// and should be updated using their own create/update/delete methods. -// Users should enable the Data Catalog API in the project identified by -// the tag_template.name parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) UpdateTagTemplate(ctx context.Context, req *datacatalogpb.UpdateTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { +func (c *gRPCClient) UpdateTagTemplate(ctx context.Context, req *datacatalogpb.UpdateTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -708,7 +988,7 @@ func (c *Client) UpdateTagTemplate(ctx context.Context, req *datacatalogpb.Updat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "tag_template.name", url.QueryEscape(req.GetTagTemplate().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTagTemplate[0:len(c.CallOptions.UpdateTagTemplate):len(c.CallOptions.UpdateTagTemplate)], opts...) + opts = append((*c.CallOptions).UpdateTagTemplate[0:len((*c.CallOptions).UpdateTagTemplate):len((*c.CallOptions).UpdateTagTemplate)], opts...) var resp *datacatalogpb.TagTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -721,12 +1001,7 @@ func (c *Client) UpdateTagTemplate(ctx context.Context, req *datacatalogpb.Updat return resp, nil } -// DeleteTagTemplate deletes a tag template and all tags using the template. -// Users should enable the Data Catalog API in the project identified by -// the name parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) DeleteTagTemplate(ctx context.Context, req *datacatalogpb.DeleteTagTemplateRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteTagTemplate(ctx context.Context, req *datacatalogpb.DeleteTagTemplateRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -734,7 +1009,7 @@ func (c *Client) DeleteTagTemplate(ctx context.Context, req *datacatalogpb.Delet } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTagTemplate[0:len(c.CallOptions.DeleteTagTemplate):len(c.CallOptions.DeleteTagTemplate)], opts...) + opts = append((*c.CallOptions).DeleteTagTemplate[0:len((*c.CallOptions).DeleteTagTemplate):len((*c.CallOptions).DeleteTagTemplate)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteTagTemplate(ctx, req, settings.GRPC...) @@ -743,12 +1018,7 @@ func (c *Client) DeleteTagTemplate(ctx context.Context, req *datacatalogpb.Delet return err } -// CreateTagTemplateField creates a field in a tag template. The user should enable the Data Catalog -// API in the project identified by the parent parameter (see -// Data Catalog Resource -// Project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project) -// for more information). -func (c *Client) CreateTagTemplateField(ctx context.Context, req *datacatalogpb.CreateTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { +func (c *gRPCClient) CreateTagTemplateField(ctx context.Context, req *datacatalogpb.CreateTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -756,7 +1026,7 @@ func (c *Client) CreateTagTemplateField(ctx context.Context, req *datacatalogpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTagTemplateField[0:len(c.CallOptions.CreateTagTemplateField):len(c.CallOptions.CreateTagTemplateField)], opts...) + opts = append((*c.CallOptions).CreateTagTemplateField[0:len((*c.CallOptions).CreateTagTemplateField):len((*c.CallOptions).CreateTagTemplateField)], opts...) var resp *datacatalogpb.TagTemplateField err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -769,12 +1039,7 @@ func (c *Client) CreateTagTemplateField(ctx context.Context, req *datacatalogpb. return resp, nil } -// UpdateTagTemplateField updates a field in a tag template. This method cannot be used to update the -// field type. Users should enable the Data Catalog API in the project -// identified by the name parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) UpdateTagTemplateField(ctx context.Context, req *datacatalogpb.UpdateTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { +func (c *gRPCClient) UpdateTagTemplateField(ctx context.Context, req *datacatalogpb.UpdateTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -782,7 +1047,7 @@ func (c *Client) UpdateTagTemplateField(ctx context.Context, req *datacatalogpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTagTemplateField[0:len(c.CallOptions.UpdateTagTemplateField):len(c.CallOptions.UpdateTagTemplateField)], opts...) + opts = append((*c.CallOptions).UpdateTagTemplateField[0:len((*c.CallOptions).UpdateTagTemplateField):len((*c.CallOptions).UpdateTagTemplateField)], opts...) var resp *datacatalogpb.TagTemplateField err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -795,12 +1060,7 @@ func (c *Client) UpdateTagTemplateField(ctx context.Context, req *datacatalogpb. return resp, nil } -// RenameTagTemplateField renames a field in a tag template. The user should enable the Data Catalog -// API in the project identified by the name parameter (see Data Catalog -// Resource -// Project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project) -// for more information). -func (c *Client) RenameTagTemplateField(ctx context.Context, req *datacatalogpb.RenameTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { +func (c *gRPCClient) RenameTagTemplateField(ctx context.Context, req *datacatalogpb.RenameTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -808,7 +1068,7 @@ func (c *Client) RenameTagTemplateField(ctx context.Context, req *datacatalogpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RenameTagTemplateField[0:len(c.CallOptions.RenameTagTemplateField):len(c.CallOptions.RenameTagTemplateField)], opts...) + opts = append((*c.CallOptions).RenameTagTemplateField[0:len((*c.CallOptions).RenameTagTemplateField):len((*c.CallOptions).RenameTagTemplateField)], opts...) var resp *datacatalogpb.TagTemplateField err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -821,9 +1081,7 @@ func (c *Client) RenameTagTemplateField(ctx context.Context, req *datacatalogpb. return resp, nil } -// RenameTagTemplateFieldEnumValue renames an enum value in a tag template. The enum values have to be unique -// within one enum field. -func (c *Client) RenameTagTemplateFieldEnumValue(ctx context.Context, req *datacatalogpb.RenameTagTemplateFieldEnumValueRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { +func (c *gRPCClient) RenameTagTemplateFieldEnumValue(ctx context.Context, req *datacatalogpb.RenameTagTemplateFieldEnumValueRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -831,7 +1089,7 @@ func (c *Client) RenameTagTemplateFieldEnumValue(ctx context.Context, req *datac } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RenameTagTemplateFieldEnumValue[0:len(c.CallOptions.RenameTagTemplateFieldEnumValue):len(c.CallOptions.RenameTagTemplateFieldEnumValue)], opts...) + opts = append((*c.CallOptions).RenameTagTemplateFieldEnumValue[0:len((*c.CallOptions).RenameTagTemplateFieldEnumValue):len((*c.CallOptions).RenameTagTemplateFieldEnumValue)], opts...) var resp *datacatalogpb.TagTemplateField err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -844,12 +1102,7 @@ func (c *Client) RenameTagTemplateFieldEnumValue(ctx context.Context, req *datac return resp, nil } -// DeleteTagTemplateField deletes a field in a tag template and all uses of that field. -// Users should enable the Data Catalog API in the project identified by -// the name parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) DeleteTagTemplateField(ctx context.Context, req *datacatalogpb.DeleteTagTemplateFieldRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteTagTemplateField(ctx context.Context, req *datacatalogpb.DeleteTagTemplateFieldRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -857,7 +1110,7 @@ func (c *Client) DeleteTagTemplateField(ctx context.Context, req *datacatalogpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTagTemplateField[0:len(c.CallOptions.DeleteTagTemplateField):len(c.CallOptions.DeleteTagTemplateField)], opts...) + opts = append((*c.CallOptions).DeleteTagTemplateField[0:len((*c.CallOptions).DeleteTagTemplateField):len((*c.CallOptions).DeleteTagTemplateField)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteTagTemplateField(ctx, req, settings.GRPC...) @@ -866,14 +1119,7 @@ func (c *Client) DeleteTagTemplateField(ctx context.Context, req *datacatalogpb. return err } -// CreateTag creates a tag on an Entry. -// Note: The project identified by the parent parameter for the -// tag (at https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.entryGroups.entries.tags/create#path-parameters) -// and the -// tag -// template (at https://cloud.google.com/data-catalog/docs/reference/rest/v1/projects.locations.tagTemplates/create#path-parameters) -// used to create the tag must be from the same organization. -func (c *Client) CreateTag(ctx context.Context, req *datacatalogpb.CreateTagRequest, opts ...gax.CallOption) (*datacatalogpb.Tag, error) { +func (c *gRPCClient) CreateTag(ctx context.Context, req *datacatalogpb.CreateTagRequest, opts ...gax.CallOption) (*datacatalogpb.Tag, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -881,7 +1127,7 @@ func (c *Client) CreateTag(ctx context.Context, req *datacatalogpb.CreateTagRequ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTag[0:len(c.CallOptions.CreateTag):len(c.CallOptions.CreateTag)], opts...) + opts = append((*c.CallOptions).CreateTag[0:len((*c.CallOptions).CreateTag):len((*c.CallOptions).CreateTag)], opts...) var resp *datacatalogpb.Tag err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -894,8 +1140,7 @@ func (c *Client) CreateTag(ctx context.Context, req *datacatalogpb.CreateTagRequ return resp, nil } -// UpdateTag updates an existing tag. -func (c *Client) UpdateTag(ctx context.Context, req *datacatalogpb.UpdateTagRequest, opts ...gax.CallOption) (*datacatalogpb.Tag, error) { +func (c *gRPCClient) UpdateTag(ctx context.Context, req *datacatalogpb.UpdateTagRequest, opts ...gax.CallOption) (*datacatalogpb.Tag, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -903,7 +1148,7 @@ func (c *Client) UpdateTag(ctx context.Context, req *datacatalogpb.UpdateTagRequ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "tag.name", url.QueryEscape(req.GetTag().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTag[0:len(c.CallOptions.UpdateTag):len(c.CallOptions.UpdateTag)], opts...) + opts = append((*c.CallOptions).UpdateTag[0:len((*c.CallOptions).UpdateTag):len((*c.CallOptions).UpdateTag)], opts...) var resp *datacatalogpb.Tag err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -916,8 +1161,7 @@ func (c *Client) UpdateTag(ctx context.Context, req *datacatalogpb.UpdateTagRequ return resp, nil } -// DeleteTag deletes a tag. -func (c *Client) DeleteTag(ctx context.Context, req *datacatalogpb.DeleteTagRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteTag(ctx context.Context, req *datacatalogpb.DeleteTagRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -925,7 +1169,7 @@ func (c *Client) DeleteTag(ctx context.Context, req *datacatalogpb.DeleteTagRequ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTag[0:len(c.CallOptions.DeleteTag):len(c.CallOptions.DeleteTag)], opts...) + opts = append((*c.CallOptions).DeleteTag[0:len((*c.CallOptions).DeleteTag):len((*c.CallOptions).DeleteTag)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteTag(ctx, req, settings.GRPC...) @@ -934,11 +1178,10 @@ func (c *Client) DeleteTag(ctx context.Context, req *datacatalogpb.DeleteTagRequ return err } -// ListTags lists the tags on an Entry. -func (c *Client) ListTags(ctx context.Context, req *datacatalogpb.ListTagsRequest, opts ...gax.CallOption) *TagIterator { +func (c *gRPCClient) ListTags(ctx context.Context, req *datacatalogpb.ListTagsRequest, opts ...gax.CallOption) *TagIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTags[0:len(c.CallOptions.ListTags):len(c.CallOptions.ListTags)], opts...) + opts = append((*c.CallOptions).ListTags[0:len((*c.CallOptions).ListTags):len((*c.CallOptions).ListTags)], opts...) it := &TagIterator{} req = proto.Clone(req).(*datacatalogpb.ListTagsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.Tag, string, error) { @@ -975,27 +1218,7 @@ func (c *Client) ListTags(ctx context.Context, req *datacatalogpb.ListTagsReques return it } -// SetIamPolicy sets the access control policy for a resource. Replaces any existing -// policy. -// Supported resources are: -// -// Tag templates. -// -// Entries. -// -// Entry groups. -// Note, this method cannot be used to manage policies for BigQuery, Pub/Sub -// and any external Google Cloud Platform resources synced to Data Catalog. -// -// Callers must have following Google IAM permission -// -// datacatalog.tagTemplates.setIamPolicy to set policies on tag -// templates. -// -// datacatalog.entries.setIamPolicy to set policies on entries. -// -// datacatalog.entryGroups.setIamPolicy to set policies on entry groups. -func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1003,7 +1226,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1016,29 +1239,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques return resp, nil } -// GetIamPolicy gets the access control policy for a resource. A NOT_FOUND error -// is returned if the resource does not exist. An empty policy is returned -// if the resource exists but does not have a policy set on it. -// -// Supported resources are: -// -// Tag templates. -// -// Entries. -// -// Entry groups. -// Note, this method cannot be used to manage policies for BigQuery, Pub/Sub -// and any external Google Cloud Platform resources synced to Data Catalog. -// -// Callers must have following Google IAM permission -// -// datacatalog.tagTemplates.getIamPolicy to get policies on tag -// templates. -// -// datacatalog.entries.getIamPolicy to get policies on entries. -// -// datacatalog.entryGroups.getIamPolicy to get policies on entry groups. -func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1046,7 +1247,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1059,23 +1260,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques return resp, nil } -// TestIamPermissions returns the caller’s permissions on a resource. -// If the resource does not exist, an empty set of permissions is returned -// (We don’t return a NOT_FOUND error). -// -// Supported resources are: -// -// Tag templates. -// -// Entries. -// -// Entry groups. -// Note, this method cannot be used to manage policies for BigQuery, Pub/Sub -// and any external Google Cloud Platform resources synced to Data Catalog. -// -// A caller is not required to have Google IAM permission to make this -// request. -func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *gRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1083,7 +1268,7 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/datacatalog/apiv1/data_catalog_client_example_test.go b/datacatalog/apiv1/data_catalog_client_example_test.go index 9dd461fc8b45..0424f1220f4f 100644 --- a/datacatalog/apiv1/data_catalog_client_example_test.go +++ b/datacatalog/apiv1/data_catalog_client_example_test.go @@ -31,19 +31,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_SearchCatalog() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.SearchCatalogRequest{ // TODO: Fill request struct fields. @@ -63,13 +63,12 @@ func ExampleClient_SearchCatalog() { } func ExampleClient_CreateEntryGroup() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateEntryGroupRequest{ // TODO: Fill request struct fields. @@ -83,13 +82,12 @@ func ExampleClient_CreateEntryGroup() { } func ExampleClient_GetEntryGroup() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetEntryGroupRequest{ // TODO: Fill request struct fields. @@ -103,13 +101,12 @@ func ExampleClient_GetEntryGroup() { } func ExampleClient_UpdateEntryGroup() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateEntryGroupRequest{ // TODO: Fill request struct fields. @@ -128,6 +125,7 @@ func ExampleClient_DeleteEntryGroup() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteEntryGroupRequest{ // TODO: Fill request struct fields. @@ -139,14 +137,12 @@ func ExampleClient_DeleteEntryGroup() { } func ExampleClient_ListEntryGroups() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListEntryGroupsRequest{ // TODO: Fill request struct fields. @@ -166,13 +162,12 @@ func ExampleClient_ListEntryGroups() { } func ExampleClient_CreateEntry() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateEntryRequest{ // TODO: Fill request struct fields. @@ -186,13 +181,12 @@ func ExampleClient_CreateEntry() { } func ExampleClient_UpdateEntry() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateEntryRequest{ // TODO: Fill request struct fields. @@ -211,6 +205,7 @@ func ExampleClient_DeleteEntry() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteEntryRequest{ // TODO: Fill request struct fields. @@ -222,13 +217,12 @@ func ExampleClient_DeleteEntry() { } func ExampleClient_GetEntry() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetEntryRequest{ // TODO: Fill request struct fields. @@ -242,13 +236,12 @@ func ExampleClient_GetEntry() { } func ExampleClient_LookupEntry() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.LookupEntryRequest{ // TODO: Fill request struct fields. @@ -262,14 +255,12 @@ func ExampleClient_LookupEntry() { } func ExampleClient_ListEntries() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListEntriesRequest{ // TODO: Fill request struct fields. @@ -289,13 +280,12 @@ func ExampleClient_ListEntries() { } func ExampleClient_CreateTagTemplate() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateTagTemplateRequest{ // TODO: Fill request struct fields. @@ -309,13 +299,12 @@ func ExampleClient_CreateTagTemplate() { } func ExampleClient_GetTagTemplate() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetTagTemplateRequest{ // TODO: Fill request struct fields. @@ -329,13 +318,12 @@ func ExampleClient_GetTagTemplate() { } func ExampleClient_UpdateTagTemplate() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateTagTemplateRequest{ // TODO: Fill request struct fields. @@ -354,6 +342,7 @@ func ExampleClient_DeleteTagTemplate() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteTagTemplateRequest{ // TODO: Fill request struct fields. @@ -365,13 +354,12 @@ func ExampleClient_DeleteTagTemplate() { } func ExampleClient_CreateTagTemplateField() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateTagTemplateFieldRequest{ // TODO: Fill request struct fields. @@ -385,13 +373,12 @@ func ExampleClient_CreateTagTemplateField() { } func ExampleClient_UpdateTagTemplateField() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateTagTemplateFieldRequest{ // TODO: Fill request struct fields. @@ -405,13 +392,12 @@ func ExampleClient_UpdateTagTemplateField() { } func ExampleClient_RenameTagTemplateField() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.RenameTagTemplateFieldRequest{ // TODO: Fill request struct fields. @@ -425,13 +411,12 @@ func ExampleClient_RenameTagTemplateField() { } func ExampleClient_RenameTagTemplateFieldEnumValue() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.RenameTagTemplateFieldEnumValueRequest{ // TODO: Fill request struct fields. @@ -450,6 +435,7 @@ func ExampleClient_DeleteTagTemplateField() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteTagTemplateFieldRequest{ // TODO: Fill request struct fields. @@ -461,13 +447,12 @@ func ExampleClient_DeleteTagTemplateField() { } func ExampleClient_CreateTag() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateTagRequest{ // TODO: Fill request struct fields. @@ -481,13 +466,12 @@ func ExampleClient_CreateTag() { } func ExampleClient_UpdateTag() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateTagRequest{ // TODO: Fill request struct fields. @@ -506,6 +490,7 @@ func ExampleClient_DeleteTag() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteTagRequest{ // TODO: Fill request struct fields. @@ -517,14 +502,12 @@ func ExampleClient_DeleteTag() { } func ExampleClient_ListTags() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListTagsRequest{ // TODO: Fill request struct fields. @@ -544,13 +527,12 @@ func ExampleClient_ListTags() { } func ExampleClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -564,13 +546,12 @@ func ExampleClient_SetIamPolicy() { } func ExampleClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -584,13 +565,12 @@ func ExampleClient_GetIamPolicy() { } func ExampleClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/datacatalog/apiv1/doc.go b/datacatalog/apiv1/doc.go index 065012a29435..928d2b3cfcfc 100644 --- a/datacatalog/apiv1/doc.go +++ b/datacatalog/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package datacatalog // import "cloud.google.com/go/datacatalog/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/datacatalog/apiv1/policy_tag_manager_client.go b/datacatalog/apiv1/policy_tag_manager_client.go index 6cd7b0155feb..7e1208a6af7f 100644 --- a/datacatalog/apiv1/policy_tag_manager_client.go +++ b/datacatalog/apiv1/policy_tag_manager_client.go @@ -54,7 +54,7 @@ type PolicyTagManagerCallOptions struct { TestIamPermissions []gax.CallOption } -func defaultPolicyTagManagerClientOptions() []option.ClientOption { +func defaultPolicyTagManagerGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("datacatalog.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("datacatalog.mtls.googleapis.com:443"), @@ -84,27 +84,166 @@ func defaultPolicyTagManagerCallOptions() *PolicyTagManagerCallOptions { } } +// internalPolicyTagManagerClient is an interface that defines the methods availaible from Google Cloud Data Catalog API. +type internalPolicyTagManagerClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateTaxonomy(context.Context, *datacatalogpb.CreateTaxonomyRequest, ...gax.CallOption) (*datacatalogpb.Taxonomy, error) + DeleteTaxonomy(context.Context, *datacatalogpb.DeleteTaxonomyRequest, ...gax.CallOption) error + UpdateTaxonomy(context.Context, *datacatalogpb.UpdateTaxonomyRequest, ...gax.CallOption) (*datacatalogpb.Taxonomy, error) + ListTaxonomies(context.Context, *datacatalogpb.ListTaxonomiesRequest, ...gax.CallOption) *TaxonomyIterator + GetTaxonomy(context.Context, *datacatalogpb.GetTaxonomyRequest, ...gax.CallOption) (*datacatalogpb.Taxonomy, error) + CreatePolicyTag(context.Context, *datacatalogpb.CreatePolicyTagRequest, ...gax.CallOption) (*datacatalogpb.PolicyTag, error) + DeletePolicyTag(context.Context, *datacatalogpb.DeletePolicyTagRequest, ...gax.CallOption) error + UpdatePolicyTag(context.Context, *datacatalogpb.UpdatePolicyTagRequest, ...gax.CallOption) (*datacatalogpb.PolicyTag, error) + ListPolicyTags(context.Context, *datacatalogpb.ListPolicyTagsRequest, ...gax.CallOption) *PolicyTagIterator + GetPolicyTag(context.Context, *datacatalogpb.GetPolicyTagRequest, ...gax.CallOption) (*datacatalogpb.PolicyTag, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) +} + // PolicyTagManagerClient is a client for interacting with Google Cloud Data Catalog API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Policy Tag Manager API service allows clients to manage their policy tags and +// taxonomies. +// +// Policy tags are used to tag BigQuery columns and apply additional access +// control policies. A taxonomy is a hierarchical grouping of policy tags that +// classify data along a common axis. type PolicyTagManagerClient struct { + // The internal transport-dependent client. + internalClient internalPolicyTagManagerClient + + // The call options for this service. + CallOptions *PolicyTagManagerCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *PolicyTagManagerClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *PolicyTagManagerClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *PolicyTagManagerClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateTaxonomy creates a taxonomy in a specified project. The taxonomy is initially empty, +// i.e., does not contain policy tags. +func (c *PolicyTagManagerClient) CreateTaxonomy(ctx context.Context, req *datacatalogpb.CreateTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { + return c.internalClient.CreateTaxonomy(ctx, req, opts...) +} + +// DeleteTaxonomy deletes a taxonomy. This method will also delete all policy tags in this +// taxonomy, their associated policies, and the policy tags references from +// BigQuery columns. +func (c *PolicyTagManagerClient) DeleteTaxonomy(ctx context.Context, req *datacatalogpb.DeleteTaxonomyRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTaxonomy(ctx, req, opts...) +} + +// UpdateTaxonomy updates a taxonomy. This method can update the taxonomy’s display name, +// description, and activated policy types. +func (c *PolicyTagManagerClient) UpdateTaxonomy(ctx context.Context, req *datacatalogpb.UpdateTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { + return c.internalClient.UpdateTaxonomy(ctx, req, opts...) +} + +// ListTaxonomies lists all taxonomies in a project in a particular location that the caller +// has permission to view. +func (c *PolicyTagManagerClient) ListTaxonomies(ctx context.Context, req *datacatalogpb.ListTaxonomiesRequest, opts ...gax.CallOption) *TaxonomyIterator { + return c.internalClient.ListTaxonomies(ctx, req, opts...) +} + +// GetTaxonomy gets a taxonomy. +func (c *PolicyTagManagerClient) GetTaxonomy(ctx context.Context, req *datacatalogpb.GetTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { + return c.internalClient.GetTaxonomy(ctx, req, opts...) +} + +// CreatePolicyTag creates a policy tag in a taxonomy. +func (c *PolicyTagManagerClient) CreatePolicyTag(ctx context.Context, req *datacatalogpb.CreatePolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { + return c.internalClient.CreatePolicyTag(ctx, req, opts...) +} + +// DeletePolicyTag deletes a policy tag. This method also deletes: +// +// all of its descendant policy tags, if any +// +// the policies associated with the policy tag and its descendants +// +// references from BigQuery table schema of the policy tag and its +// descendants. +func (c *PolicyTagManagerClient) DeletePolicyTag(ctx context.Context, req *datacatalogpb.DeletePolicyTagRequest, opts ...gax.CallOption) error { + return c.internalClient.DeletePolicyTag(ctx, req, opts...) +} + +// UpdatePolicyTag updates a policy tag. This method can update the policy tag’s display +// name, description, and parent policy tag. +func (c *PolicyTagManagerClient) UpdatePolicyTag(ctx context.Context, req *datacatalogpb.UpdatePolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { + return c.internalClient.UpdatePolicyTag(ctx, req, opts...) +} + +// ListPolicyTags lists all policy tags in a taxonomy. +func (c *PolicyTagManagerClient) ListPolicyTags(ctx context.Context, req *datacatalogpb.ListPolicyTagsRequest, opts ...gax.CallOption) *PolicyTagIterator { + return c.internalClient.ListPolicyTags(ctx, req, opts...) +} + +// GetPolicyTag gets a policy tag. +func (c *PolicyTagManagerClient) GetPolicyTag(ctx context.Context, req *datacatalogpb.GetPolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { + return c.internalClient.GetPolicyTag(ctx, req, opts...) +} + +// GetIamPolicy gets the IAM policy for a policy tag or a taxonomy. +func (c *PolicyTagManagerClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// SetIamPolicy sets the IAM policy for a policy tag or a taxonomy. +func (c *PolicyTagManagerClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns the permissions that a caller has on a specified policy tag or +// taxonomy. +func (c *PolicyTagManagerClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// policyTagManagerGRPCClient is a client for interacting with Google Cloud Data Catalog API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type policyTagManagerGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing PolicyTagManagerClient + CallOptions **PolicyTagManagerCallOptions + // The gRPC API client. policyTagManagerClient datacatalogpb.PolicyTagManagerClient - // The call options for this service. - CallOptions *PolicyTagManagerCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewPolicyTagManagerClient creates a new policy tag manager client. +// NewPolicyTagManagerClient creates a new policy tag manager client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Policy Tag Manager API service allows clients to manage their policy tags and // taxonomies. @@ -113,8 +252,7 @@ type PolicyTagManagerClient struct { // control policies. A taxonomy is a hierarchical grouping of policy tags that // classify data along a common axis. func NewPolicyTagManagerClient(ctx context.Context, opts ...option.ClientOption) (*PolicyTagManagerClient, error) { - clientOpts := defaultPolicyTagManagerClientOptions() - + clientOpts := defaultPolicyTagManagerGRPCClientOptions() if newPolicyTagManagerClientHook != nil { hookOpts, err := newPolicyTagManagerClientHook(ctx, clientHookParams{}) if err != nil { @@ -132,43 +270,44 @@ func NewPolicyTagManagerClient(ctx context.Context, opts ...option.ClientOption) if err != nil { return nil, err } - c := &PolicyTagManagerClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultPolicyTagManagerCallOptions(), + client := PolicyTagManagerClient{CallOptions: defaultPolicyTagManagerCallOptions()} + c := &policyTagManagerGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, policyTagManagerClient: datacatalogpb.NewPolicyTagManagerClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *PolicyTagManagerClient) Connection() *grpc.ClientConn { +func (c *policyTagManagerGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *PolicyTagManagerClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *PolicyTagManagerClient) setGoogleClientInfo(keyval ...string) { +func (c *policyTagManagerGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateTaxonomy creates a taxonomy in a specified project. The taxonomy is initially empty, -// i.e., does not contain policy tags. -func (c *PolicyTagManagerClient) CreateTaxonomy(ctx context.Context, req *datacatalogpb.CreateTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *policyTagManagerGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *policyTagManagerGRPCClient) CreateTaxonomy(ctx context.Context, req *datacatalogpb.CreateTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -176,7 +315,7 @@ func (c *PolicyTagManagerClient) CreateTaxonomy(ctx context.Context, req *dataca } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTaxonomy[0:len(c.CallOptions.CreateTaxonomy):len(c.CallOptions.CreateTaxonomy)], opts...) + opts = append((*c.CallOptions).CreateTaxonomy[0:len((*c.CallOptions).CreateTaxonomy):len((*c.CallOptions).CreateTaxonomy)], opts...) var resp *datacatalogpb.Taxonomy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -189,10 +328,7 @@ func (c *PolicyTagManagerClient) CreateTaxonomy(ctx context.Context, req *dataca return resp, nil } -// DeleteTaxonomy deletes a taxonomy. This method will also delete all policy tags in this -// taxonomy, their associated policies, and the policy tags references from -// BigQuery columns. -func (c *PolicyTagManagerClient) DeleteTaxonomy(ctx context.Context, req *datacatalogpb.DeleteTaxonomyRequest, opts ...gax.CallOption) error { +func (c *policyTagManagerGRPCClient) DeleteTaxonomy(ctx context.Context, req *datacatalogpb.DeleteTaxonomyRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -200,7 +336,7 @@ func (c *PolicyTagManagerClient) DeleteTaxonomy(ctx context.Context, req *dataca } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTaxonomy[0:len(c.CallOptions.DeleteTaxonomy):len(c.CallOptions.DeleteTaxonomy)], opts...) + opts = append((*c.CallOptions).DeleteTaxonomy[0:len((*c.CallOptions).DeleteTaxonomy):len((*c.CallOptions).DeleteTaxonomy)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.policyTagManagerClient.DeleteTaxonomy(ctx, req, settings.GRPC...) @@ -209,9 +345,7 @@ func (c *PolicyTagManagerClient) DeleteTaxonomy(ctx context.Context, req *dataca return err } -// UpdateTaxonomy updates a taxonomy. This method can update the taxonomy’s display name, -// description, and activated policy types. -func (c *PolicyTagManagerClient) UpdateTaxonomy(ctx context.Context, req *datacatalogpb.UpdateTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { +func (c *policyTagManagerGRPCClient) UpdateTaxonomy(ctx context.Context, req *datacatalogpb.UpdateTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -219,7 +353,7 @@ func (c *PolicyTagManagerClient) UpdateTaxonomy(ctx context.Context, req *dataca } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "taxonomy.name", url.QueryEscape(req.GetTaxonomy().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTaxonomy[0:len(c.CallOptions.UpdateTaxonomy):len(c.CallOptions.UpdateTaxonomy)], opts...) + opts = append((*c.CallOptions).UpdateTaxonomy[0:len((*c.CallOptions).UpdateTaxonomy):len((*c.CallOptions).UpdateTaxonomy)], opts...) var resp *datacatalogpb.Taxonomy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -232,12 +366,10 @@ func (c *PolicyTagManagerClient) UpdateTaxonomy(ctx context.Context, req *dataca return resp, nil } -// ListTaxonomies lists all taxonomies in a project in a particular location that the caller -// has permission to view. -func (c *PolicyTagManagerClient) ListTaxonomies(ctx context.Context, req *datacatalogpb.ListTaxonomiesRequest, opts ...gax.CallOption) *TaxonomyIterator { +func (c *policyTagManagerGRPCClient) ListTaxonomies(ctx context.Context, req *datacatalogpb.ListTaxonomiesRequest, opts ...gax.CallOption) *TaxonomyIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTaxonomies[0:len(c.CallOptions.ListTaxonomies):len(c.CallOptions.ListTaxonomies)], opts...) + opts = append((*c.CallOptions).ListTaxonomies[0:len((*c.CallOptions).ListTaxonomies):len((*c.CallOptions).ListTaxonomies)], opts...) it := &TaxonomyIterator{} req = proto.Clone(req).(*datacatalogpb.ListTaxonomiesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.Taxonomy, string, error) { @@ -274,8 +406,7 @@ func (c *PolicyTagManagerClient) ListTaxonomies(ctx context.Context, req *dataca return it } -// GetTaxonomy gets a taxonomy. -func (c *PolicyTagManagerClient) GetTaxonomy(ctx context.Context, req *datacatalogpb.GetTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { +func (c *policyTagManagerGRPCClient) GetTaxonomy(ctx context.Context, req *datacatalogpb.GetTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -283,7 +414,7 @@ func (c *PolicyTagManagerClient) GetTaxonomy(ctx context.Context, req *datacatal } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTaxonomy[0:len(c.CallOptions.GetTaxonomy):len(c.CallOptions.GetTaxonomy)], opts...) + opts = append((*c.CallOptions).GetTaxonomy[0:len((*c.CallOptions).GetTaxonomy):len((*c.CallOptions).GetTaxonomy)], opts...) var resp *datacatalogpb.Taxonomy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -296,8 +427,7 @@ func (c *PolicyTagManagerClient) GetTaxonomy(ctx context.Context, req *datacatal return resp, nil } -// CreatePolicyTag creates a policy tag in a taxonomy. -func (c *PolicyTagManagerClient) CreatePolicyTag(ctx context.Context, req *datacatalogpb.CreatePolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { +func (c *policyTagManagerGRPCClient) CreatePolicyTag(ctx context.Context, req *datacatalogpb.CreatePolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -305,7 +435,7 @@ func (c *PolicyTagManagerClient) CreatePolicyTag(ctx context.Context, req *datac } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreatePolicyTag[0:len(c.CallOptions.CreatePolicyTag):len(c.CallOptions.CreatePolicyTag)], opts...) + opts = append((*c.CallOptions).CreatePolicyTag[0:len((*c.CallOptions).CreatePolicyTag):len((*c.CallOptions).CreatePolicyTag)], opts...) var resp *datacatalogpb.PolicyTag err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -318,15 +448,7 @@ func (c *PolicyTagManagerClient) CreatePolicyTag(ctx context.Context, req *datac return resp, nil } -// DeletePolicyTag deletes a policy tag. This method also deletes: -// -// all of its descendant policy tags, if any -// -// the policies associated with the policy tag and its descendants -// -// references from BigQuery table schema of the policy tag and its -// descendants. -func (c *PolicyTagManagerClient) DeletePolicyTag(ctx context.Context, req *datacatalogpb.DeletePolicyTagRequest, opts ...gax.CallOption) error { +func (c *policyTagManagerGRPCClient) DeletePolicyTag(ctx context.Context, req *datacatalogpb.DeletePolicyTagRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -334,7 +456,7 @@ func (c *PolicyTagManagerClient) DeletePolicyTag(ctx context.Context, req *datac } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeletePolicyTag[0:len(c.CallOptions.DeletePolicyTag):len(c.CallOptions.DeletePolicyTag)], opts...) + opts = append((*c.CallOptions).DeletePolicyTag[0:len((*c.CallOptions).DeletePolicyTag):len((*c.CallOptions).DeletePolicyTag)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.policyTagManagerClient.DeletePolicyTag(ctx, req, settings.GRPC...) @@ -343,9 +465,7 @@ func (c *PolicyTagManagerClient) DeletePolicyTag(ctx context.Context, req *datac return err } -// UpdatePolicyTag updates a policy tag. This method can update the policy tag’s display -// name, description, and parent policy tag. -func (c *PolicyTagManagerClient) UpdatePolicyTag(ctx context.Context, req *datacatalogpb.UpdatePolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { +func (c *policyTagManagerGRPCClient) UpdatePolicyTag(ctx context.Context, req *datacatalogpb.UpdatePolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -353,7 +473,7 @@ func (c *PolicyTagManagerClient) UpdatePolicyTag(ctx context.Context, req *datac } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "policy_tag.name", url.QueryEscape(req.GetPolicyTag().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdatePolicyTag[0:len(c.CallOptions.UpdatePolicyTag):len(c.CallOptions.UpdatePolicyTag)], opts...) + opts = append((*c.CallOptions).UpdatePolicyTag[0:len((*c.CallOptions).UpdatePolicyTag):len((*c.CallOptions).UpdatePolicyTag)], opts...) var resp *datacatalogpb.PolicyTag err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -366,11 +486,10 @@ func (c *PolicyTagManagerClient) UpdatePolicyTag(ctx context.Context, req *datac return resp, nil } -// ListPolicyTags lists all policy tags in a taxonomy. -func (c *PolicyTagManagerClient) ListPolicyTags(ctx context.Context, req *datacatalogpb.ListPolicyTagsRequest, opts ...gax.CallOption) *PolicyTagIterator { +func (c *policyTagManagerGRPCClient) ListPolicyTags(ctx context.Context, req *datacatalogpb.ListPolicyTagsRequest, opts ...gax.CallOption) *PolicyTagIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListPolicyTags[0:len(c.CallOptions.ListPolicyTags):len(c.CallOptions.ListPolicyTags)], opts...) + opts = append((*c.CallOptions).ListPolicyTags[0:len((*c.CallOptions).ListPolicyTags):len((*c.CallOptions).ListPolicyTags)], opts...) it := &PolicyTagIterator{} req = proto.Clone(req).(*datacatalogpb.ListPolicyTagsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.PolicyTag, string, error) { @@ -407,8 +526,7 @@ func (c *PolicyTagManagerClient) ListPolicyTags(ctx context.Context, req *dataca return it } -// GetPolicyTag gets a policy tag. -func (c *PolicyTagManagerClient) GetPolicyTag(ctx context.Context, req *datacatalogpb.GetPolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { +func (c *policyTagManagerGRPCClient) GetPolicyTag(ctx context.Context, req *datacatalogpb.GetPolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -416,7 +534,7 @@ func (c *PolicyTagManagerClient) GetPolicyTag(ctx context.Context, req *datacata } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetPolicyTag[0:len(c.CallOptions.GetPolicyTag):len(c.CallOptions.GetPolicyTag)], opts...) + opts = append((*c.CallOptions).GetPolicyTag[0:len((*c.CallOptions).GetPolicyTag):len((*c.CallOptions).GetPolicyTag)], opts...) var resp *datacatalogpb.PolicyTag err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -429,8 +547,7 @@ func (c *PolicyTagManagerClient) GetPolicyTag(ctx context.Context, req *datacata return resp, nil } -// GetIamPolicy gets the IAM policy for a policy tag or a taxonomy. -func (c *PolicyTagManagerClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *policyTagManagerGRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -438,7 +555,7 @@ func (c *PolicyTagManagerClient) GetIamPolicy(ctx context.Context, req *iampb.Ge } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -451,8 +568,7 @@ func (c *PolicyTagManagerClient) GetIamPolicy(ctx context.Context, req *iampb.Ge return resp, nil } -// SetIamPolicy sets the IAM policy for a policy tag or a taxonomy. -func (c *PolicyTagManagerClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *policyTagManagerGRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -460,7 +576,7 @@ func (c *PolicyTagManagerClient) SetIamPolicy(ctx context.Context, req *iampb.Se } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -473,9 +589,7 @@ func (c *PolicyTagManagerClient) SetIamPolicy(ctx context.Context, req *iampb.Se return resp, nil } -// TestIamPermissions returns the permissions that a caller has on a specified policy tag or -// taxonomy. -func (c *PolicyTagManagerClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *policyTagManagerGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -483,7 +597,7 @@ func (c *PolicyTagManagerClient) TestIamPermissions(ctx context.Context, req *ia } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/datacatalog/apiv1/policy_tag_manager_client_example_test.go b/datacatalog/apiv1/policy_tag_manager_client_example_test.go index 3b26dcfb1769..45251e3a4fd5 100644 --- a/datacatalog/apiv1/policy_tag_manager_client_example_test.go +++ b/datacatalog/apiv1/policy_tag_manager_client_example_test.go @@ -31,18 +31,19 @@ func ExampleNewPolicyTagManagerClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExamplePolicyTagManagerClient_CreateTaxonomy() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateTaxonomyRequest{ // TODO: Fill request struct fields. @@ -61,6 +62,7 @@ func ExamplePolicyTagManagerClient_DeleteTaxonomy() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteTaxonomyRequest{ // TODO: Fill request struct fields. @@ -72,13 +74,12 @@ func ExamplePolicyTagManagerClient_DeleteTaxonomy() { } func ExamplePolicyTagManagerClient_UpdateTaxonomy() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateTaxonomyRequest{ // TODO: Fill request struct fields. @@ -92,14 +93,12 @@ func ExamplePolicyTagManagerClient_UpdateTaxonomy() { } func ExamplePolicyTagManagerClient_ListTaxonomies() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListTaxonomiesRequest{ // TODO: Fill request struct fields. @@ -119,13 +118,12 @@ func ExamplePolicyTagManagerClient_ListTaxonomies() { } func ExamplePolicyTagManagerClient_GetTaxonomy() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetTaxonomyRequest{ // TODO: Fill request struct fields. @@ -139,13 +137,12 @@ func ExamplePolicyTagManagerClient_GetTaxonomy() { } func ExamplePolicyTagManagerClient_CreatePolicyTag() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreatePolicyTagRequest{ // TODO: Fill request struct fields. @@ -164,6 +161,7 @@ func ExamplePolicyTagManagerClient_DeletePolicyTag() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeletePolicyTagRequest{ // TODO: Fill request struct fields. @@ -175,13 +173,12 @@ func ExamplePolicyTagManagerClient_DeletePolicyTag() { } func ExamplePolicyTagManagerClient_UpdatePolicyTag() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdatePolicyTagRequest{ // TODO: Fill request struct fields. @@ -195,14 +192,12 @@ func ExamplePolicyTagManagerClient_UpdatePolicyTag() { } func ExamplePolicyTagManagerClient_ListPolicyTags() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListPolicyTagsRequest{ // TODO: Fill request struct fields. @@ -222,13 +217,12 @@ func ExamplePolicyTagManagerClient_ListPolicyTags() { } func ExamplePolicyTagManagerClient_GetPolicyTag() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetPolicyTagRequest{ // TODO: Fill request struct fields. @@ -242,13 +236,12 @@ func ExamplePolicyTagManagerClient_GetPolicyTag() { } func ExamplePolicyTagManagerClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -262,13 +255,12 @@ func ExamplePolicyTagManagerClient_GetIamPolicy() { } func ExamplePolicyTagManagerClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -282,13 +274,12 @@ func ExamplePolicyTagManagerClient_SetIamPolicy() { } func ExamplePolicyTagManagerClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/datacatalog/apiv1/policy_tag_manager_serialization_client.go b/datacatalog/apiv1/policy_tag_manager_serialization_client.go index b1eba7d10f80..036cab2bf639 100644 --- a/datacatalog/apiv1/policy_tag_manager_serialization_client.go +++ b/datacatalog/apiv1/policy_tag_manager_serialization_client.go @@ -40,7 +40,7 @@ type PolicyTagManagerSerializationCallOptions struct { ExportTaxonomies []gax.CallOption } -func defaultPolicyTagManagerSerializationClientOptions() []option.ClientOption { +func defaultPolicyTagManagerSerializationGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("datacatalog.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("datacatalog.mtls.googleapis.com:443"), @@ -59,34 +59,102 @@ func defaultPolicyTagManagerSerializationCallOptions() *PolicyTagManagerSerializ } } +// internalPolicyTagManagerSerializationClient is an interface that defines the methods availaible from Google Cloud Data Catalog API. +type internalPolicyTagManagerSerializationClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ImportTaxonomies(context.Context, *datacatalogpb.ImportTaxonomiesRequest, ...gax.CallOption) (*datacatalogpb.ImportTaxonomiesResponse, error) + ExportTaxonomies(context.Context, *datacatalogpb.ExportTaxonomiesRequest, ...gax.CallOption) (*datacatalogpb.ExportTaxonomiesResponse, error) +} + // PolicyTagManagerSerializationClient is a client for interacting with Google Cloud Data Catalog API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Policy Tag Manager serialization API service allows clients to manipulate +// their policy tags and taxonomies in serialized format, where taxonomy is a +// hierarchical group of policy tags. type PolicyTagManagerSerializationClient struct { + // The internal transport-dependent client. + internalClient internalPolicyTagManagerSerializationClient + + // The call options for this service. + CallOptions *PolicyTagManagerSerializationCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *PolicyTagManagerSerializationClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *PolicyTagManagerSerializationClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *PolicyTagManagerSerializationClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ImportTaxonomies creates new taxonomies (including their policy tags) by importing from +// inlined source or cross-regional source. New taxonomies will be created in +// a given parent project. +// +// If using the cross-regional source, a new taxonomy is created by copying +// from a source in another region. +// +// If using the inlined source, this method provides a way to bulk create +// taxonomies and policy tags using nested proto structure. +func (c *PolicyTagManagerSerializationClient) ImportTaxonomies(ctx context.Context, req *datacatalogpb.ImportTaxonomiesRequest, opts ...gax.CallOption) (*datacatalogpb.ImportTaxonomiesResponse, error) { + return c.internalClient.ImportTaxonomies(ctx, req, opts...) +} + +// ExportTaxonomies exports taxonomies as the requested type and returns the taxonomies +// including their policy tags. The requested taxonomies must belong to one +// project. +// +// SerializedTaxonomy protos with nested policy tags that are generated by +// this method can be used as input for future ImportTaxonomies calls. +func (c *PolicyTagManagerSerializationClient) ExportTaxonomies(ctx context.Context, req *datacatalogpb.ExportTaxonomiesRequest, opts ...gax.CallOption) (*datacatalogpb.ExportTaxonomiesResponse, error) { + return c.internalClient.ExportTaxonomies(ctx, req, opts...) +} + +// policyTagManagerSerializationGRPCClient is a client for interacting with Google Cloud Data Catalog API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type policyTagManagerSerializationGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing PolicyTagManagerSerializationClient + CallOptions **PolicyTagManagerSerializationCallOptions + // The gRPC API client. policyTagManagerSerializationClient datacatalogpb.PolicyTagManagerSerializationClient - // The call options for this service. - CallOptions *PolicyTagManagerSerializationCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewPolicyTagManagerSerializationClient creates a new policy tag manager serialization client. +// NewPolicyTagManagerSerializationClient creates a new policy tag manager serialization client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Policy Tag Manager serialization API service allows clients to manipulate // their policy tags and taxonomies in serialized format, where taxonomy is a // hierarchical group of policy tags. func NewPolicyTagManagerSerializationClient(ctx context.Context, opts ...option.ClientOption) (*PolicyTagManagerSerializationClient, error) { - clientOpts := defaultPolicyTagManagerSerializationClientOptions() - + clientOpts := defaultPolicyTagManagerSerializationGRPCClientOptions() if newPolicyTagManagerSerializationClientHook != nil { hookOpts, err := newPolicyTagManagerSerializationClientHook(ctx, clientHookParams{}) if err != nil { @@ -104,50 +172,44 @@ func NewPolicyTagManagerSerializationClient(ctx context.Context, opts ...option. if err != nil { return nil, err } - c := &PolicyTagManagerSerializationClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultPolicyTagManagerSerializationCallOptions(), + client := PolicyTagManagerSerializationClient{CallOptions: defaultPolicyTagManagerSerializationCallOptions()} + c := &policyTagManagerSerializationGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, policyTagManagerSerializationClient: datacatalogpb.NewPolicyTagManagerSerializationClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *PolicyTagManagerSerializationClient) Connection() *grpc.ClientConn { +func (c *policyTagManagerSerializationGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *PolicyTagManagerSerializationClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *PolicyTagManagerSerializationClient) setGoogleClientInfo(keyval ...string) { +func (c *policyTagManagerSerializationGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ImportTaxonomies creates new taxonomies (including their policy tags) by importing from -// inlined source or cross-regional source. New taxonomies will be created in -// a given parent project. -// -// If using the cross-regional source, a new taxonomy is created by copying -// from a source in another region. -// -// If using the inlined source, this method provides a way to bulk create -// taxonomies and policy tags using nested proto structure. -func (c *PolicyTagManagerSerializationClient) ImportTaxonomies(ctx context.Context, req *datacatalogpb.ImportTaxonomiesRequest, opts ...gax.CallOption) (*datacatalogpb.ImportTaxonomiesResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *policyTagManagerSerializationGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *policyTagManagerSerializationGRPCClient) ImportTaxonomies(ctx context.Context, req *datacatalogpb.ImportTaxonomiesRequest, opts ...gax.CallOption) (*datacatalogpb.ImportTaxonomiesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -155,7 +217,7 @@ func (c *PolicyTagManagerSerializationClient) ImportTaxonomies(ctx context.Conte } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportTaxonomies[0:len(c.CallOptions.ImportTaxonomies):len(c.CallOptions.ImportTaxonomies)], opts...) + opts = append((*c.CallOptions).ImportTaxonomies[0:len((*c.CallOptions).ImportTaxonomies):len((*c.CallOptions).ImportTaxonomies)], opts...) var resp *datacatalogpb.ImportTaxonomiesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -168,13 +230,7 @@ func (c *PolicyTagManagerSerializationClient) ImportTaxonomies(ctx context.Conte return resp, nil } -// ExportTaxonomies exports taxonomies as the requested type and returns the taxonomies -// including their policy tags. The requested taxonomies must belong to one -// project. -// -// SerializedTaxonomy protos with nested policy tags that are generated by -// this method can be used as input for future ImportTaxonomies calls. -func (c *PolicyTagManagerSerializationClient) ExportTaxonomies(ctx context.Context, req *datacatalogpb.ExportTaxonomiesRequest, opts ...gax.CallOption) (*datacatalogpb.ExportTaxonomiesResponse, error) { +func (c *policyTagManagerSerializationGRPCClient) ExportTaxonomies(ctx context.Context, req *datacatalogpb.ExportTaxonomiesRequest, opts ...gax.CallOption) (*datacatalogpb.ExportTaxonomiesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -182,7 +238,7 @@ func (c *PolicyTagManagerSerializationClient) ExportTaxonomies(ctx context.Conte } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportTaxonomies[0:len(c.CallOptions.ExportTaxonomies):len(c.CallOptions.ExportTaxonomies)], opts...) + opts = append((*c.CallOptions).ExportTaxonomies[0:len((*c.CallOptions).ExportTaxonomies):len((*c.CallOptions).ExportTaxonomies)], opts...) var resp *datacatalogpb.ExportTaxonomiesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/datacatalog/apiv1/policy_tag_manager_serialization_client_example_test.go b/datacatalog/apiv1/policy_tag_manager_serialization_client_example_test.go index e371e330b4ba..33866bca5926 100644 --- a/datacatalog/apiv1/policy_tag_manager_serialization_client_example_test.go +++ b/datacatalog/apiv1/policy_tag_manager_serialization_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewPolicyTagManagerSerializationClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExamplePolicyTagManagerSerializationClient_ImportTaxonomies() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerSerializationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ImportTaxonomiesRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExamplePolicyTagManagerSerializationClient_ImportTaxonomies() { } func ExamplePolicyTagManagerSerializationClient_ExportTaxonomies() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerSerializationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ExportTaxonomiesRequest{ // TODO: Fill request struct fields. diff --git a/datacatalog/apiv1beta1/data_catalog_client.go b/datacatalog/apiv1beta1/data_catalog_client.go index 423172edf7ee..f1acf2d4fe93 100644 --- a/datacatalog/apiv1beta1/data_catalog_client.go +++ b/datacatalog/apiv1beta1/data_catalog_client.go @@ -69,7 +69,7 @@ type CallOptions struct { TestIamPermissions []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("datacatalog.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("datacatalog.mtls.googleapis.com:443"), @@ -223,33 +223,377 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Google Cloud Data Catalog API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + SearchCatalog(context.Context, *datacatalogpb.SearchCatalogRequest, ...gax.CallOption) *SearchCatalogResultIterator + CreateEntryGroup(context.Context, *datacatalogpb.CreateEntryGroupRequest, ...gax.CallOption) (*datacatalogpb.EntryGroup, error) + UpdateEntryGroup(context.Context, *datacatalogpb.UpdateEntryGroupRequest, ...gax.CallOption) (*datacatalogpb.EntryGroup, error) + GetEntryGroup(context.Context, *datacatalogpb.GetEntryGroupRequest, ...gax.CallOption) (*datacatalogpb.EntryGroup, error) + DeleteEntryGroup(context.Context, *datacatalogpb.DeleteEntryGroupRequest, ...gax.CallOption) error + ListEntryGroups(context.Context, *datacatalogpb.ListEntryGroupsRequest, ...gax.CallOption) *EntryGroupIterator + CreateEntry(context.Context, *datacatalogpb.CreateEntryRequest, ...gax.CallOption) (*datacatalogpb.Entry, error) + UpdateEntry(context.Context, *datacatalogpb.UpdateEntryRequest, ...gax.CallOption) (*datacatalogpb.Entry, error) + DeleteEntry(context.Context, *datacatalogpb.DeleteEntryRequest, ...gax.CallOption) error + GetEntry(context.Context, *datacatalogpb.GetEntryRequest, ...gax.CallOption) (*datacatalogpb.Entry, error) + LookupEntry(context.Context, *datacatalogpb.LookupEntryRequest, ...gax.CallOption) (*datacatalogpb.Entry, error) + ListEntries(context.Context, *datacatalogpb.ListEntriesRequest, ...gax.CallOption) *EntryIterator + CreateTagTemplate(context.Context, *datacatalogpb.CreateTagTemplateRequest, ...gax.CallOption) (*datacatalogpb.TagTemplate, error) + GetTagTemplate(context.Context, *datacatalogpb.GetTagTemplateRequest, ...gax.CallOption) (*datacatalogpb.TagTemplate, error) + UpdateTagTemplate(context.Context, *datacatalogpb.UpdateTagTemplateRequest, ...gax.CallOption) (*datacatalogpb.TagTemplate, error) + DeleteTagTemplate(context.Context, *datacatalogpb.DeleteTagTemplateRequest, ...gax.CallOption) error + CreateTagTemplateField(context.Context, *datacatalogpb.CreateTagTemplateFieldRequest, ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) + UpdateTagTemplateField(context.Context, *datacatalogpb.UpdateTagTemplateFieldRequest, ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) + RenameTagTemplateField(context.Context, *datacatalogpb.RenameTagTemplateFieldRequest, ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) + DeleteTagTemplateField(context.Context, *datacatalogpb.DeleteTagTemplateFieldRequest, ...gax.CallOption) error + CreateTag(context.Context, *datacatalogpb.CreateTagRequest, ...gax.CallOption) (*datacatalogpb.Tag, error) + UpdateTag(context.Context, *datacatalogpb.UpdateTagRequest, ...gax.CallOption) (*datacatalogpb.Tag, error) + DeleteTag(context.Context, *datacatalogpb.DeleteTagRequest, ...gax.CallOption) error + ListTags(context.Context, *datacatalogpb.ListTagsRequest, ...gax.CallOption) *TagIterator + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) +} + // Client is a client for interacting with Google Cloud Data Catalog API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Data Catalog API service allows clients to discover, understand, and manage +// their data. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// SearchCatalog searches Data Catalog for multiple resources like entries, tags that +// match a query. +// +// This is a custom method +// (https://cloud.google.com/apis/design/custom_methods (at https://cloud.google.com/apis/design/custom_methods)) and does not return +// the complete resource, only the resource identifier and high level +// fields. Clients can subsequentally call Get methods. +// +// Note that Data Catalog search queries do not guarantee full recall. Query +// results that match your query may not be returned, even in subsequent +// result pages. Also note that results returned (and not returned) can vary +// across repeated search queries. +// +// See Data Catalog Search +// Syntax (at https://cloud.google.com/data-catalog/docs/how-to/search-reference) +// for more information. +func (c *Client) SearchCatalog(ctx context.Context, req *datacatalogpb.SearchCatalogRequest, opts ...gax.CallOption) *SearchCatalogResultIterator { + return c.internalClient.SearchCatalog(ctx, req, opts...) +} + +// CreateEntryGroup a maximum of 10,000 entry groups may be created per organization across all +// locations. +// +// Users should enable the Data Catalog API in the project identified by +// the parent parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) CreateEntryGroup(ctx context.Context, req *datacatalogpb.CreateEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { + return c.internalClient.CreateEntryGroup(ctx, req, opts...) +} + +// UpdateEntryGroup updates an EntryGroup. The user should enable the Data Catalog API in the +// project identified by the entry_group.name parameter (see [Data Catalog +// Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) UpdateEntryGroup(ctx context.Context, req *datacatalogpb.UpdateEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { + return c.internalClient.UpdateEntryGroup(ctx, req, opts...) +} + +// GetEntryGroup gets an EntryGroup. +func (c *Client) GetEntryGroup(ctx context.Context, req *datacatalogpb.GetEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { + return c.internalClient.GetEntryGroup(ctx, req, opts...) +} + +// DeleteEntryGroup deletes an EntryGroup. Only entry groups that do not contain entries can be +// deleted. Users should enable the Data Catalog API in the project +// identified by the name parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) DeleteEntryGroup(ctx context.Context, req *datacatalogpb.DeleteEntryGroupRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteEntryGroup(ctx, req, opts...) +} + +// ListEntryGroups lists entry groups. +func (c *Client) ListEntryGroups(ctx context.Context, req *datacatalogpb.ListEntryGroupsRequest, opts ...gax.CallOption) *EntryGroupIterator { + return c.internalClient.ListEntryGroups(ctx, req, opts...) +} + +// CreateEntry creates an entry. Only entries of ‘FILESET’ type or user-specified type can +// be created. +// +// Users should enable the Data Catalog API in the project identified by +// the parent parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +// +// A maximum of 100,000 entries may be created per entry group. +func (c *Client) CreateEntry(ctx context.Context, req *datacatalogpb.CreateEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { + return c.internalClient.CreateEntry(ctx, req, opts...) +} + +// UpdateEntry updates an existing entry. +// Users should enable the Data Catalog API in the project identified by +// the entry.name parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) UpdateEntry(ctx context.Context, req *datacatalogpb.UpdateEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { + return c.internalClient.UpdateEntry(ctx, req, opts...) +} + +// DeleteEntry deletes an existing entry. Only entries created through +// CreateEntry +// method can be deleted. +// Users should enable the Data Catalog API in the project identified by +// the name parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) DeleteEntry(ctx context.Context, req *datacatalogpb.DeleteEntryRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteEntry(ctx, req, opts...) +} + +// GetEntry gets an entry. +func (c *Client) GetEntry(ctx context.Context, req *datacatalogpb.GetEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { + return c.internalClient.GetEntry(ctx, req, opts...) +} + +// LookupEntry get an entry by target resource name. This method allows clients to use +// the resource name from the source Google Cloud Platform service to get the +// Data Catalog Entry. +func (c *Client) LookupEntry(ctx context.Context, req *datacatalogpb.LookupEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { + return c.internalClient.LookupEntry(ctx, req, opts...) +} + +// ListEntries lists entries. +func (c *Client) ListEntries(ctx context.Context, req *datacatalogpb.ListEntriesRequest, opts ...gax.CallOption) *EntryIterator { + return c.internalClient.ListEntries(ctx, req, opts...) +} + +// CreateTagTemplate creates a tag template. The user should enable the Data Catalog API in +// the project identified by the parent parameter (see Data Catalog +// Resource +// Project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project) +// for more information). +func (c *Client) CreateTagTemplate(ctx context.Context, req *datacatalogpb.CreateTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { + return c.internalClient.CreateTagTemplate(ctx, req, opts...) +} + +// GetTagTemplate gets a tag template. +func (c *Client) GetTagTemplate(ctx context.Context, req *datacatalogpb.GetTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { + return c.internalClient.GetTagTemplate(ctx, req, opts...) +} + +// UpdateTagTemplate updates a tag template. This method cannot be used to update the fields of +// a template. The tag template fields are represented as separate resources +// and should be updated using their own create/update/delete methods. +// Users should enable the Data Catalog API in the project identified by +// the tag_template.name parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) UpdateTagTemplate(ctx context.Context, req *datacatalogpb.UpdateTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { + return c.internalClient.UpdateTagTemplate(ctx, req, opts...) +} + +// DeleteTagTemplate deletes a tag template and all tags using the template. +// Users should enable the Data Catalog API in the project identified by +// the name parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) DeleteTagTemplate(ctx context.Context, req *datacatalogpb.DeleteTagTemplateRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTagTemplate(ctx, req, opts...) +} + +// CreateTagTemplateField creates a field in a tag template. The user should enable the Data Catalog +// API in the project identified by the parent parameter (see +// Data Catalog Resource +// Project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project) +// for more information). +func (c *Client) CreateTagTemplateField(ctx context.Context, req *datacatalogpb.CreateTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { + return c.internalClient.CreateTagTemplateField(ctx, req, opts...) +} + +// UpdateTagTemplateField updates a field in a tag template. This method cannot be used to update the +// field type. Users should enable the Data Catalog API in the project +// identified by the name parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) UpdateTagTemplateField(ctx context.Context, req *datacatalogpb.UpdateTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { + return c.internalClient.UpdateTagTemplateField(ctx, req, opts...) +} + +// RenameTagTemplateField renames a field in a tag template. The user should enable the Data Catalog +// API in the project identified by the name parameter (see Data Catalog +// Resource +// Project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project) +// for more information). +func (c *Client) RenameTagTemplateField(ctx context.Context, req *datacatalogpb.RenameTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { + return c.internalClient.RenameTagTemplateField(ctx, req, opts...) +} + +// DeleteTagTemplateField deletes a field in a tag template and all uses of that field. +// Users should enable the Data Catalog API in the project identified by +// the name parameter (see [Data Catalog Resource Project] +// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for +// more information). +func (c *Client) DeleteTagTemplateField(ctx context.Context, req *datacatalogpb.DeleteTagTemplateFieldRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTagTemplateField(ctx, req, opts...) +} + +// CreateTag creates a tag on an Entry. +// Note: The project identified by the parent parameter for the +// tag (at https://cloud.google.com/data-catalog/docs/reference/rest/v1beta1/projects.locations.entryGroups.entries.tags/create#path-parameters) +// and the +// tag +// template (at https://cloud.google.com/data-catalog/docs/reference/rest/v1beta1/projects.locations.tagTemplates/create#path-parameters) +// used to create the tag must be from the same organization. +func (c *Client) CreateTag(ctx context.Context, req *datacatalogpb.CreateTagRequest, opts ...gax.CallOption) (*datacatalogpb.Tag, error) { + return c.internalClient.CreateTag(ctx, req, opts...) +} + +// UpdateTag updates an existing tag. +func (c *Client) UpdateTag(ctx context.Context, req *datacatalogpb.UpdateTagRequest, opts ...gax.CallOption) (*datacatalogpb.Tag, error) { + return c.internalClient.UpdateTag(ctx, req, opts...) +} + +// DeleteTag deletes a tag. +func (c *Client) DeleteTag(ctx context.Context, req *datacatalogpb.DeleteTagRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTag(ctx, req, opts...) +} + +// ListTags lists the tags on an Entry. +func (c *Client) ListTags(ctx context.Context, req *datacatalogpb.ListTagsRequest, opts ...gax.CallOption) *TagIterator { + return c.internalClient.ListTags(ctx, req, opts...) +} + +// SetIamPolicy sets the access control policy for a resource. Replaces any existing +// policy. +// Supported resources are: +// +// Tag templates. +// +// Entries. +// +// Entry groups. +// Note, this method cannot be used to manage policies for BigQuery, Pub/Sub +// and any external Google Cloud Platform resources synced to Data Catalog. +// +// Callers must have following Google IAM permission +// +// datacatalog.tagTemplates.setIamPolicy to set policies on tag +// templates. +// +// datacatalog.entries.setIamPolicy to set policies on entries. +// +// datacatalog.entryGroups.setIamPolicy to set policies on entry groups. +func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy for a resource. A NOT_FOUND error +// is returned if the resource does not exist. An empty policy is returned +// if the resource exists but does not have a policy set on it. +// +// Supported resources are: +// +// Tag templates. +// +// Entries. +// +// Entry groups. +// Note, this method cannot be used to manage policies for BigQuery, Pub/Sub +// and any external Google Cloud Platform resources synced to Data Catalog. +// +// Callers must have following Google IAM permission +// +// datacatalog.tagTemplates.getIamPolicy to get policies on tag +// templates. +// +// datacatalog.entries.getIamPolicy to get policies on entries. +// +// datacatalog.entryGroups.getIamPolicy to get policies on entry groups. +func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns the caller’s permissions on a resource. +// If the resource does not exist, an empty set of permissions is returned +// (We don’t return a NOT_FOUND error). +// +// Supported resources are: +// +// Tag templates. +// +// Entries. +// +// Entry groups. +// Note, this method cannot be used to manage policies for BigQuery, Pub/Sub +// and any external Google Cloud Platform resources synced to Data Catalog. +// +// A caller is not required to have Google IAM permission to make this +// request. +func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Google Cloud Data Catalog API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client datacatalogpb.DataCatalogClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new data catalog client. +// NewClient creates a new data catalog client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Data Catalog API service allows clients to discover, understand, and manage // their data. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -267,59 +611,46 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: datacatalogpb.NewDataCatalogClient(connPool), + client: datacatalogpb.NewDataCatalogClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// SearchCatalog searches Data Catalog for multiple resources like entries, tags that -// match a query. -// -// This is a custom method -// (https://cloud.google.com/apis/design/custom_methods (at https://cloud.google.com/apis/design/custom_methods)) and does not return -// the complete resource, only the resource identifier and high level -// fields. Clients can subsequentally call Get methods. -// -// Note that Data Catalog search queries do not guarantee full recall. Query -// results that match your query may not be returned, even in subsequent -// result pages. Also note that results returned (and not returned) can vary -// across repeated search queries. -// -// See Data Catalog Search -// Syntax (at https://cloud.google.com/data-catalog/docs/how-to/search-reference) -// for more information. -func (c *Client) SearchCatalog(ctx context.Context, req *datacatalogpb.SearchCatalogRequest, opts ...gax.CallOption) *SearchCatalogResultIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) SearchCatalog(ctx context.Context, req *datacatalogpb.SearchCatalogRequest, opts ...gax.CallOption) *SearchCatalogResultIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.SearchCatalog[0:len(c.CallOptions.SearchCatalog):len(c.CallOptions.SearchCatalog)], opts...) + opts = append((*c.CallOptions).SearchCatalog[0:len((*c.CallOptions).SearchCatalog):len((*c.CallOptions).SearchCatalog)], opts...) it := &SearchCatalogResultIterator{} req = proto.Clone(req).(*datacatalogpb.SearchCatalogRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.SearchCatalogResult, string, error) { @@ -356,14 +687,7 @@ func (c *Client) SearchCatalog(ctx context.Context, req *datacatalogpb.SearchCat return it } -// CreateEntryGroup a maximum of 10,000 entry groups may be created per organization across all -// locations. -// -// Users should enable the Data Catalog API in the project identified by -// the parent parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) CreateEntryGroup(ctx context.Context, req *datacatalogpb.CreateEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { +func (c *gRPCClient) CreateEntryGroup(ctx context.Context, req *datacatalogpb.CreateEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -371,7 +695,7 @@ func (c *Client) CreateEntryGroup(ctx context.Context, req *datacatalogpb.Create } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateEntryGroup[0:len(c.CallOptions.CreateEntryGroup):len(c.CallOptions.CreateEntryGroup)], opts...) + opts = append((*c.CallOptions).CreateEntryGroup[0:len((*c.CallOptions).CreateEntryGroup):len((*c.CallOptions).CreateEntryGroup)], opts...) var resp *datacatalogpb.EntryGroup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -384,12 +708,7 @@ func (c *Client) CreateEntryGroup(ctx context.Context, req *datacatalogpb.Create return resp, nil } -// UpdateEntryGroup updates an EntryGroup. The user should enable the Data Catalog API in the -// project identified by the entry_group.name parameter (see [Data Catalog -// Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) UpdateEntryGroup(ctx context.Context, req *datacatalogpb.UpdateEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { +func (c *gRPCClient) UpdateEntryGroup(ctx context.Context, req *datacatalogpb.UpdateEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -397,7 +716,7 @@ func (c *Client) UpdateEntryGroup(ctx context.Context, req *datacatalogpb.Update } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "entry_group.name", url.QueryEscape(req.GetEntryGroup().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateEntryGroup[0:len(c.CallOptions.UpdateEntryGroup):len(c.CallOptions.UpdateEntryGroup)], opts...) + opts = append((*c.CallOptions).UpdateEntryGroup[0:len((*c.CallOptions).UpdateEntryGroup):len((*c.CallOptions).UpdateEntryGroup)], opts...) var resp *datacatalogpb.EntryGroup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -410,8 +729,7 @@ func (c *Client) UpdateEntryGroup(ctx context.Context, req *datacatalogpb.Update return resp, nil } -// GetEntryGroup gets an EntryGroup. -func (c *Client) GetEntryGroup(ctx context.Context, req *datacatalogpb.GetEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { +func (c *gRPCClient) GetEntryGroup(ctx context.Context, req *datacatalogpb.GetEntryGroupRequest, opts ...gax.CallOption) (*datacatalogpb.EntryGroup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -419,7 +737,7 @@ func (c *Client) GetEntryGroup(ctx context.Context, req *datacatalogpb.GetEntryG } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEntryGroup[0:len(c.CallOptions.GetEntryGroup):len(c.CallOptions.GetEntryGroup)], opts...) + opts = append((*c.CallOptions).GetEntryGroup[0:len((*c.CallOptions).GetEntryGroup):len((*c.CallOptions).GetEntryGroup)], opts...) var resp *datacatalogpb.EntryGroup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -432,12 +750,7 @@ func (c *Client) GetEntryGroup(ctx context.Context, req *datacatalogpb.GetEntryG return resp, nil } -// DeleteEntryGroup deletes an EntryGroup. Only entry groups that do not contain entries can be -// deleted. Users should enable the Data Catalog API in the project -// identified by the name parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) DeleteEntryGroup(ctx context.Context, req *datacatalogpb.DeleteEntryGroupRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteEntryGroup(ctx context.Context, req *datacatalogpb.DeleteEntryGroupRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -445,7 +758,7 @@ func (c *Client) DeleteEntryGroup(ctx context.Context, req *datacatalogpb.Delete } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteEntryGroup[0:len(c.CallOptions.DeleteEntryGroup):len(c.CallOptions.DeleteEntryGroup)], opts...) + opts = append((*c.CallOptions).DeleteEntryGroup[0:len((*c.CallOptions).DeleteEntryGroup):len((*c.CallOptions).DeleteEntryGroup)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteEntryGroup(ctx, req, settings.GRPC...) @@ -454,11 +767,10 @@ func (c *Client) DeleteEntryGroup(ctx context.Context, req *datacatalogpb.Delete return err } -// ListEntryGroups lists entry groups. -func (c *Client) ListEntryGroups(ctx context.Context, req *datacatalogpb.ListEntryGroupsRequest, opts ...gax.CallOption) *EntryGroupIterator { +func (c *gRPCClient) ListEntryGroups(ctx context.Context, req *datacatalogpb.ListEntryGroupsRequest, opts ...gax.CallOption) *EntryGroupIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListEntryGroups[0:len(c.CallOptions.ListEntryGroups):len(c.CallOptions.ListEntryGroups)], opts...) + opts = append((*c.CallOptions).ListEntryGroups[0:len((*c.CallOptions).ListEntryGroups):len((*c.CallOptions).ListEntryGroups)], opts...) it := &EntryGroupIterator{} req = proto.Clone(req).(*datacatalogpb.ListEntryGroupsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.EntryGroup, string, error) { @@ -495,16 +807,7 @@ func (c *Client) ListEntryGroups(ctx context.Context, req *datacatalogpb.ListEnt return it } -// CreateEntry creates an entry. Only entries of ‘FILESET’ type or user-specified type can -// be created. -// -// Users should enable the Data Catalog API in the project identified by -// the parent parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -// -// A maximum of 100,000 entries may be created per entry group. -func (c *Client) CreateEntry(ctx context.Context, req *datacatalogpb.CreateEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { +func (c *gRPCClient) CreateEntry(ctx context.Context, req *datacatalogpb.CreateEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -512,7 +815,7 @@ func (c *Client) CreateEntry(ctx context.Context, req *datacatalogpb.CreateEntry } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateEntry[0:len(c.CallOptions.CreateEntry):len(c.CallOptions.CreateEntry)], opts...) + opts = append((*c.CallOptions).CreateEntry[0:len((*c.CallOptions).CreateEntry):len((*c.CallOptions).CreateEntry)], opts...) var resp *datacatalogpb.Entry err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -525,12 +828,7 @@ func (c *Client) CreateEntry(ctx context.Context, req *datacatalogpb.CreateEntry return resp, nil } -// UpdateEntry updates an existing entry. -// Users should enable the Data Catalog API in the project identified by -// the entry.name parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) UpdateEntry(ctx context.Context, req *datacatalogpb.UpdateEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { +func (c *gRPCClient) UpdateEntry(ctx context.Context, req *datacatalogpb.UpdateEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -538,7 +836,7 @@ func (c *Client) UpdateEntry(ctx context.Context, req *datacatalogpb.UpdateEntry } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "entry.name", url.QueryEscape(req.GetEntry().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateEntry[0:len(c.CallOptions.UpdateEntry):len(c.CallOptions.UpdateEntry)], opts...) + opts = append((*c.CallOptions).UpdateEntry[0:len((*c.CallOptions).UpdateEntry):len((*c.CallOptions).UpdateEntry)], opts...) var resp *datacatalogpb.Entry err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -551,14 +849,7 @@ func (c *Client) UpdateEntry(ctx context.Context, req *datacatalogpb.UpdateEntry return resp, nil } -// DeleteEntry deletes an existing entry. Only entries created through -// CreateEntry -// method can be deleted. -// Users should enable the Data Catalog API in the project identified by -// the name parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) DeleteEntry(ctx context.Context, req *datacatalogpb.DeleteEntryRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteEntry(ctx context.Context, req *datacatalogpb.DeleteEntryRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -566,7 +857,7 @@ func (c *Client) DeleteEntry(ctx context.Context, req *datacatalogpb.DeleteEntry } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteEntry[0:len(c.CallOptions.DeleteEntry):len(c.CallOptions.DeleteEntry)], opts...) + opts = append((*c.CallOptions).DeleteEntry[0:len((*c.CallOptions).DeleteEntry):len((*c.CallOptions).DeleteEntry)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteEntry(ctx, req, settings.GRPC...) @@ -575,8 +866,7 @@ func (c *Client) DeleteEntry(ctx context.Context, req *datacatalogpb.DeleteEntry return err } -// GetEntry gets an entry. -func (c *Client) GetEntry(ctx context.Context, req *datacatalogpb.GetEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { +func (c *gRPCClient) GetEntry(ctx context.Context, req *datacatalogpb.GetEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -584,7 +874,7 @@ func (c *Client) GetEntry(ctx context.Context, req *datacatalogpb.GetEntryReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEntry[0:len(c.CallOptions.GetEntry):len(c.CallOptions.GetEntry)], opts...) + opts = append((*c.CallOptions).GetEntry[0:len((*c.CallOptions).GetEntry):len((*c.CallOptions).GetEntry)], opts...) var resp *datacatalogpb.Entry err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -597,17 +887,14 @@ func (c *Client) GetEntry(ctx context.Context, req *datacatalogpb.GetEntryReques return resp, nil } -// LookupEntry get an entry by target resource name. This method allows clients to use -// the resource name from the source Google Cloud Platform service to get the -// Data Catalog Entry. -func (c *Client) LookupEntry(ctx context.Context, req *datacatalogpb.LookupEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { +func (c *gRPCClient) LookupEntry(ctx context.Context, req *datacatalogpb.LookupEntryRequest, opts ...gax.CallOption) (*datacatalogpb.Entry, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.LookupEntry[0:len(c.CallOptions.LookupEntry):len(c.CallOptions.LookupEntry)], opts...) + opts = append((*c.CallOptions).LookupEntry[0:len((*c.CallOptions).LookupEntry):len((*c.CallOptions).LookupEntry)], opts...) var resp *datacatalogpb.Entry err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -620,11 +907,10 @@ func (c *Client) LookupEntry(ctx context.Context, req *datacatalogpb.LookupEntry return resp, nil } -// ListEntries lists entries. -func (c *Client) ListEntries(ctx context.Context, req *datacatalogpb.ListEntriesRequest, opts ...gax.CallOption) *EntryIterator { +func (c *gRPCClient) ListEntries(ctx context.Context, req *datacatalogpb.ListEntriesRequest, opts ...gax.CallOption) *EntryIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListEntries[0:len(c.CallOptions.ListEntries):len(c.CallOptions.ListEntries)], opts...) + opts = append((*c.CallOptions).ListEntries[0:len((*c.CallOptions).ListEntries):len((*c.CallOptions).ListEntries)], opts...) it := &EntryIterator{} req = proto.Clone(req).(*datacatalogpb.ListEntriesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.Entry, string, error) { @@ -661,12 +947,7 @@ func (c *Client) ListEntries(ctx context.Context, req *datacatalogpb.ListEntries return it } -// CreateTagTemplate creates a tag template. The user should enable the Data Catalog API in -// the project identified by the parent parameter (see Data Catalog -// Resource -// Project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project) -// for more information). -func (c *Client) CreateTagTemplate(ctx context.Context, req *datacatalogpb.CreateTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { +func (c *gRPCClient) CreateTagTemplate(ctx context.Context, req *datacatalogpb.CreateTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -674,7 +955,7 @@ func (c *Client) CreateTagTemplate(ctx context.Context, req *datacatalogpb.Creat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTagTemplate[0:len(c.CallOptions.CreateTagTemplate):len(c.CallOptions.CreateTagTemplate)], opts...) + opts = append((*c.CallOptions).CreateTagTemplate[0:len((*c.CallOptions).CreateTagTemplate):len((*c.CallOptions).CreateTagTemplate)], opts...) var resp *datacatalogpb.TagTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -687,8 +968,7 @@ func (c *Client) CreateTagTemplate(ctx context.Context, req *datacatalogpb.Creat return resp, nil } -// GetTagTemplate gets a tag template. -func (c *Client) GetTagTemplate(ctx context.Context, req *datacatalogpb.GetTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { +func (c *gRPCClient) GetTagTemplate(ctx context.Context, req *datacatalogpb.GetTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -696,7 +976,7 @@ func (c *Client) GetTagTemplate(ctx context.Context, req *datacatalogpb.GetTagTe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTagTemplate[0:len(c.CallOptions.GetTagTemplate):len(c.CallOptions.GetTagTemplate)], opts...) + opts = append((*c.CallOptions).GetTagTemplate[0:len((*c.CallOptions).GetTagTemplate):len((*c.CallOptions).GetTagTemplate)], opts...) var resp *datacatalogpb.TagTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -709,14 +989,7 @@ func (c *Client) GetTagTemplate(ctx context.Context, req *datacatalogpb.GetTagTe return resp, nil } -// UpdateTagTemplate updates a tag template. This method cannot be used to update the fields of -// a template. The tag template fields are represented as separate resources -// and should be updated using their own create/update/delete methods. -// Users should enable the Data Catalog API in the project identified by -// the tag_template.name parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) UpdateTagTemplate(ctx context.Context, req *datacatalogpb.UpdateTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { +func (c *gRPCClient) UpdateTagTemplate(ctx context.Context, req *datacatalogpb.UpdateTagTemplateRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -724,7 +997,7 @@ func (c *Client) UpdateTagTemplate(ctx context.Context, req *datacatalogpb.Updat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "tag_template.name", url.QueryEscape(req.GetTagTemplate().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTagTemplate[0:len(c.CallOptions.UpdateTagTemplate):len(c.CallOptions.UpdateTagTemplate)], opts...) + opts = append((*c.CallOptions).UpdateTagTemplate[0:len((*c.CallOptions).UpdateTagTemplate):len((*c.CallOptions).UpdateTagTemplate)], opts...) var resp *datacatalogpb.TagTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -737,12 +1010,7 @@ func (c *Client) UpdateTagTemplate(ctx context.Context, req *datacatalogpb.Updat return resp, nil } -// DeleteTagTemplate deletes a tag template and all tags using the template. -// Users should enable the Data Catalog API in the project identified by -// the name parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) DeleteTagTemplate(ctx context.Context, req *datacatalogpb.DeleteTagTemplateRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteTagTemplate(ctx context.Context, req *datacatalogpb.DeleteTagTemplateRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -750,7 +1018,7 @@ func (c *Client) DeleteTagTemplate(ctx context.Context, req *datacatalogpb.Delet } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTagTemplate[0:len(c.CallOptions.DeleteTagTemplate):len(c.CallOptions.DeleteTagTemplate)], opts...) + opts = append((*c.CallOptions).DeleteTagTemplate[0:len((*c.CallOptions).DeleteTagTemplate):len((*c.CallOptions).DeleteTagTemplate)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteTagTemplate(ctx, req, settings.GRPC...) @@ -759,12 +1027,7 @@ func (c *Client) DeleteTagTemplate(ctx context.Context, req *datacatalogpb.Delet return err } -// CreateTagTemplateField creates a field in a tag template. The user should enable the Data Catalog -// API in the project identified by the parent parameter (see -// Data Catalog Resource -// Project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project) -// for more information). -func (c *Client) CreateTagTemplateField(ctx context.Context, req *datacatalogpb.CreateTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { +func (c *gRPCClient) CreateTagTemplateField(ctx context.Context, req *datacatalogpb.CreateTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -772,7 +1035,7 @@ func (c *Client) CreateTagTemplateField(ctx context.Context, req *datacatalogpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTagTemplateField[0:len(c.CallOptions.CreateTagTemplateField):len(c.CallOptions.CreateTagTemplateField)], opts...) + opts = append((*c.CallOptions).CreateTagTemplateField[0:len((*c.CallOptions).CreateTagTemplateField):len((*c.CallOptions).CreateTagTemplateField)], opts...) var resp *datacatalogpb.TagTemplateField err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -785,12 +1048,7 @@ func (c *Client) CreateTagTemplateField(ctx context.Context, req *datacatalogpb. return resp, nil } -// UpdateTagTemplateField updates a field in a tag template. This method cannot be used to update the -// field type. Users should enable the Data Catalog API in the project -// identified by the name parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) UpdateTagTemplateField(ctx context.Context, req *datacatalogpb.UpdateTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { +func (c *gRPCClient) UpdateTagTemplateField(ctx context.Context, req *datacatalogpb.UpdateTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -798,7 +1056,7 @@ func (c *Client) UpdateTagTemplateField(ctx context.Context, req *datacatalogpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTagTemplateField[0:len(c.CallOptions.UpdateTagTemplateField):len(c.CallOptions.UpdateTagTemplateField)], opts...) + opts = append((*c.CallOptions).UpdateTagTemplateField[0:len((*c.CallOptions).UpdateTagTemplateField):len((*c.CallOptions).UpdateTagTemplateField)], opts...) var resp *datacatalogpb.TagTemplateField err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -811,12 +1069,7 @@ func (c *Client) UpdateTagTemplateField(ctx context.Context, req *datacatalogpb. return resp, nil } -// RenameTagTemplateField renames a field in a tag template. The user should enable the Data Catalog -// API in the project identified by the name parameter (see Data Catalog -// Resource -// Project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project) -// for more information). -func (c *Client) RenameTagTemplateField(ctx context.Context, req *datacatalogpb.RenameTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { +func (c *gRPCClient) RenameTagTemplateField(ctx context.Context, req *datacatalogpb.RenameTagTemplateFieldRequest, opts ...gax.CallOption) (*datacatalogpb.TagTemplateField, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -824,7 +1077,7 @@ func (c *Client) RenameTagTemplateField(ctx context.Context, req *datacatalogpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RenameTagTemplateField[0:len(c.CallOptions.RenameTagTemplateField):len(c.CallOptions.RenameTagTemplateField)], opts...) + opts = append((*c.CallOptions).RenameTagTemplateField[0:len((*c.CallOptions).RenameTagTemplateField):len((*c.CallOptions).RenameTagTemplateField)], opts...) var resp *datacatalogpb.TagTemplateField err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -837,12 +1090,7 @@ func (c *Client) RenameTagTemplateField(ctx context.Context, req *datacatalogpb. return resp, nil } -// DeleteTagTemplateField deletes a field in a tag template and all uses of that field. -// Users should enable the Data Catalog API in the project identified by -// the name parameter (see [Data Catalog Resource Project] -// (https://cloud.google.com/data-catalog/docs/concepts/resource-project (at https://cloud.google.com/data-catalog/docs/concepts/resource-project)) for -// more information). -func (c *Client) DeleteTagTemplateField(ctx context.Context, req *datacatalogpb.DeleteTagTemplateFieldRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteTagTemplateField(ctx context.Context, req *datacatalogpb.DeleteTagTemplateFieldRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -850,7 +1098,7 @@ func (c *Client) DeleteTagTemplateField(ctx context.Context, req *datacatalogpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTagTemplateField[0:len(c.CallOptions.DeleteTagTemplateField):len(c.CallOptions.DeleteTagTemplateField)], opts...) + opts = append((*c.CallOptions).DeleteTagTemplateField[0:len((*c.CallOptions).DeleteTagTemplateField):len((*c.CallOptions).DeleteTagTemplateField)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteTagTemplateField(ctx, req, settings.GRPC...) @@ -859,14 +1107,7 @@ func (c *Client) DeleteTagTemplateField(ctx context.Context, req *datacatalogpb. return err } -// CreateTag creates a tag on an Entry. -// Note: The project identified by the parent parameter for the -// tag (at https://cloud.google.com/data-catalog/docs/reference/rest/v1beta1/projects.locations.entryGroups.entries.tags/create#path-parameters) -// and the -// tag -// template (at https://cloud.google.com/data-catalog/docs/reference/rest/v1beta1/projects.locations.tagTemplates/create#path-parameters) -// used to create the tag must be from the same organization. -func (c *Client) CreateTag(ctx context.Context, req *datacatalogpb.CreateTagRequest, opts ...gax.CallOption) (*datacatalogpb.Tag, error) { +func (c *gRPCClient) CreateTag(ctx context.Context, req *datacatalogpb.CreateTagRequest, opts ...gax.CallOption) (*datacatalogpb.Tag, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -874,7 +1115,7 @@ func (c *Client) CreateTag(ctx context.Context, req *datacatalogpb.CreateTagRequ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTag[0:len(c.CallOptions.CreateTag):len(c.CallOptions.CreateTag)], opts...) + opts = append((*c.CallOptions).CreateTag[0:len((*c.CallOptions).CreateTag):len((*c.CallOptions).CreateTag)], opts...) var resp *datacatalogpb.Tag err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -887,8 +1128,7 @@ func (c *Client) CreateTag(ctx context.Context, req *datacatalogpb.CreateTagRequ return resp, nil } -// UpdateTag updates an existing tag. -func (c *Client) UpdateTag(ctx context.Context, req *datacatalogpb.UpdateTagRequest, opts ...gax.CallOption) (*datacatalogpb.Tag, error) { +func (c *gRPCClient) UpdateTag(ctx context.Context, req *datacatalogpb.UpdateTagRequest, opts ...gax.CallOption) (*datacatalogpb.Tag, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -896,7 +1136,7 @@ func (c *Client) UpdateTag(ctx context.Context, req *datacatalogpb.UpdateTagRequ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "tag.name", url.QueryEscape(req.GetTag().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTag[0:len(c.CallOptions.UpdateTag):len(c.CallOptions.UpdateTag)], opts...) + opts = append((*c.CallOptions).UpdateTag[0:len((*c.CallOptions).UpdateTag):len((*c.CallOptions).UpdateTag)], opts...) var resp *datacatalogpb.Tag err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -909,8 +1149,7 @@ func (c *Client) UpdateTag(ctx context.Context, req *datacatalogpb.UpdateTagRequ return resp, nil } -// DeleteTag deletes a tag. -func (c *Client) DeleteTag(ctx context.Context, req *datacatalogpb.DeleteTagRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteTag(ctx context.Context, req *datacatalogpb.DeleteTagRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -918,7 +1157,7 @@ func (c *Client) DeleteTag(ctx context.Context, req *datacatalogpb.DeleteTagRequ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTag[0:len(c.CallOptions.DeleteTag):len(c.CallOptions.DeleteTag)], opts...) + opts = append((*c.CallOptions).DeleteTag[0:len((*c.CallOptions).DeleteTag):len((*c.CallOptions).DeleteTag)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteTag(ctx, req, settings.GRPC...) @@ -927,11 +1166,10 @@ func (c *Client) DeleteTag(ctx context.Context, req *datacatalogpb.DeleteTagRequ return err } -// ListTags lists the tags on an Entry. -func (c *Client) ListTags(ctx context.Context, req *datacatalogpb.ListTagsRequest, opts ...gax.CallOption) *TagIterator { +func (c *gRPCClient) ListTags(ctx context.Context, req *datacatalogpb.ListTagsRequest, opts ...gax.CallOption) *TagIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTags[0:len(c.CallOptions.ListTags):len(c.CallOptions.ListTags)], opts...) + opts = append((*c.CallOptions).ListTags[0:len((*c.CallOptions).ListTags):len((*c.CallOptions).ListTags)], opts...) it := &TagIterator{} req = proto.Clone(req).(*datacatalogpb.ListTagsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.Tag, string, error) { @@ -968,27 +1206,7 @@ func (c *Client) ListTags(ctx context.Context, req *datacatalogpb.ListTagsReques return it } -// SetIamPolicy sets the access control policy for a resource. Replaces any existing -// policy. -// Supported resources are: -// -// Tag templates. -// -// Entries. -// -// Entry groups. -// Note, this method cannot be used to manage policies for BigQuery, Pub/Sub -// and any external Google Cloud Platform resources synced to Data Catalog. -// -// Callers must have following Google IAM permission -// -// datacatalog.tagTemplates.setIamPolicy to set policies on tag -// templates. -// -// datacatalog.entries.setIamPolicy to set policies on entries. -// -// datacatalog.entryGroups.setIamPolicy to set policies on entry groups. -func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -996,7 +1214,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1009,29 +1227,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques return resp, nil } -// GetIamPolicy gets the access control policy for a resource. A NOT_FOUND error -// is returned if the resource does not exist. An empty policy is returned -// if the resource exists but does not have a policy set on it. -// -// Supported resources are: -// -// Tag templates. -// -// Entries. -// -// Entry groups. -// Note, this method cannot be used to manage policies for BigQuery, Pub/Sub -// and any external Google Cloud Platform resources synced to Data Catalog. -// -// Callers must have following Google IAM permission -// -// datacatalog.tagTemplates.getIamPolicy to get policies on tag -// templates. -// -// datacatalog.entries.getIamPolicy to get policies on entries. -// -// datacatalog.entryGroups.getIamPolicy to get policies on entry groups. -func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1039,7 +1235,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1052,23 +1248,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques return resp, nil } -// TestIamPermissions returns the caller’s permissions on a resource. -// If the resource does not exist, an empty set of permissions is returned -// (We don’t return a NOT_FOUND error). -// -// Supported resources are: -// -// Tag templates. -// -// Entries. -// -// Entry groups. -// Note, this method cannot be used to manage policies for BigQuery, Pub/Sub -// and any external Google Cloud Platform resources synced to Data Catalog. -// -// A caller is not required to have Google IAM permission to make this -// request. -func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *gRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1076,7 +1256,7 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/datacatalog/apiv1beta1/data_catalog_client_example_test.go b/datacatalog/apiv1beta1/data_catalog_client_example_test.go index 99aa2a5cbdfc..8f2c3b4d82f6 100644 --- a/datacatalog/apiv1beta1/data_catalog_client_example_test.go +++ b/datacatalog/apiv1beta1/data_catalog_client_example_test.go @@ -31,19 +31,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_SearchCatalog() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.SearchCatalogRequest{ // TODO: Fill request struct fields. @@ -63,13 +63,12 @@ func ExampleClient_SearchCatalog() { } func ExampleClient_CreateEntryGroup() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateEntryGroupRequest{ // TODO: Fill request struct fields. @@ -83,13 +82,12 @@ func ExampleClient_CreateEntryGroup() { } func ExampleClient_UpdateEntryGroup() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateEntryGroupRequest{ // TODO: Fill request struct fields. @@ -103,13 +101,12 @@ func ExampleClient_UpdateEntryGroup() { } func ExampleClient_GetEntryGroup() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetEntryGroupRequest{ // TODO: Fill request struct fields. @@ -128,6 +125,7 @@ func ExampleClient_DeleteEntryGroup() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteEntryGroupRequest{ // TODO: Fill request struct fields. @@ -139,14 +137,12 @@ func ExampleClient_DeleteEntryGroup() { } func ExampleClient_ListEntryGroups() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListEntryGroupsRequest{ // TODO: Fill request struct fields. @@ -166,13 +162,12 @@ func ExampleClient_ListEntryGroups() { } func ExampleClient_CreateEntry() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateEntryRequest{ // TODO: Fill request struct fields. @@ -186,13 +181,12 @@ func ExampleClient_CreateEntry() { } func ExampleClient_UpdateEntry() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateEntryRequest{ // TODO: Fill request struct fields. @@ -211,6 +205,7 @@ func ExampleClient_DeleteEntry() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteEntryRequest{ // TODO: Fill request struct fields. @@ -222,13 +217,12 @@ func ExampleClient_DeleteEntry() { } func ExampleClient_GetEntry() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetEntryRequest{ // TODO: Fill request struct fields. @@ -242,13 +236,12 @@ func ExampleClient_GetEntry() { } func ExampleClient_LookupEntry() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.LookupEntryRequest{ // TODO: Fill request struct fields. @@ -262,14 +255,12 @@ func ExampleClient_LookupEntry() { } func ExampleClient_ListEntries() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListEntriesRequest{ // TODO: Fill request struct fields. @@ -289,13 +280,12 @@ func ExampleClient_ListEntries() { } func ExampleClient_CreateTagTemplate() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateTagTemplateRequest{ // TODO: Fill request struct fields. @@ -309,13 +299,12 @@ func ExampleClient_CreateTagTemplate() { } func ExampleClient_GetTagTemplate() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetTagTemplateRequest{ // TODO: Fill request struct fields. @@ -329,13 +318,12 @@ func ExampleClient_GetTagTemplate() { } func ExampleClient_UpdateTagTemplate() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateTagTemplateRequest{ // TODO: Fill request struct fields. @@ -354,6 +342,7 @@ func ExampleClient_DeleteTagTemplate() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteTagTemplateRequest{ // TODO: Fill request struct fields. @@ -365,13 +354,12 @@ func ExampleClient_DeleteTagTemplate() { } func ExampleClient_CreateTagTemplateField() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateTagTemplateFieldRequest{ // TODO: Fill request struct fields. @@ -385,13 +373,12 @@ func ExampleClient_CreateTagTemplateField() { } func ExampleClient_UpdateTagTemplateField() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateTagTemplateFieldRequest{ // TODO: Fill request struct fields. @@ -405,13 +392,12 @@ func ExampleClient_UpdateTagTemplateField() { } func ExampleClient_RenameTagTemplateField() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.RenameTagTemplateFieldRequest{ // TODO: Fill request struct fields. @@ -430,6 +416,7 @@ func ExampleClient_DeleteTagTemplateField() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteTagTemplateFieldRequest{ // TODO: Fill request struct fields. @@ -441,13 +428,12 @@ func ExampleClient_DeleteTagTemplateField() { } func ExampleClient_CreateTag() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateTagRequest{ // TODO: Fill request struct fields. @@ -461,13 +447,12 @@ func ExampleClient_CreateTag() { } func ExampleClient_UpdateTag() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateTagRequest{ // TODO: Fill request struct fields. @@ -486,6 +471,7 @@ func ExampleClient_DeleteTag() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteTagRequest{ // TODO: Fill request struct fields. @@ -497,14 +483,12 @@ func ExampleClient_DeleteTag() { } func ExampleClient_ListTags() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListTagsRequest{ // TODO: Fill request struct fields. @@ -524,13 +508,12 @@ func ExampleClient_ListTags() { } func ExampleClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -544,13 +527,12 @@ func ExampleClient_SetIamPolicy() { } func ExampleClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -564,13 +546,12 @@ func ExampleClient_GetIamPolicy() { } func ExampleClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/datacatalog/apiv1beta1/doc.go b/datacatalog/apiv1beta1/doc.go index 9ba342c64f96..510352fdd353 100644 --- a/datacatalog/apiv1beta1/doc.go +++ b/datacatalog/apiv1beta1/doc.go @@ -20,6 +20,8 @@ // A fully managed and highly scalable data discovery and metadata management // service. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package datacatalog // import "cloud.google.com/go/datacatalog/apiv1beta1" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/datacatalog/apiv1beta1/policy_tag_manager_client.go b/datacatalog/apiv1beta1/policy_tag_manager_client.go index 26e25bcb625a..5ad5e36db15f 100644 --- a/datacatalog/apiv1beta1/policy_tag_manager_client.go +++ b/datacatalog/apiv1beta1/policy_tag_manager_client.go @@ -53,7 +53,7 @@ type PolicyTagManagerCallOptions struct { TestIamPermissions []gax.CallOption } -func defaultPolicyTagManagerClientOptions() []option.ClientOption { +func defaultPolicyTagManagerGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("datacatalog.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("datacatalog.mtls.googleapis.com:443"), @@ -83,33 +83,156 @@ func defaultPolicyTagManagerCallOptions() *PolicyTagManagerCallOptions { } } +// internalPolicyTagManagerClient is an interface that defines the methods availaible from Google Cloud Data Catalog API. +type internalPolicyTagManagerClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateTaxonomy(context.Context, *datacatalogpb.CreateTaxonomyRequest, ...gax.CallOption) (*datacatalogpb.Taxonomy, error) + DeleteTaxonomy(context.Context, *datacatalogpb.DeleteTaxonomyRequest, ...gax.CallOption) error + UpdateTaxonomy(context.Context, *datacatalogpb.UpdateTaxonomyRequest, ...gax.CallOption) (*datacatalogpb.Taxonomy, error) + ListTaxonomies(context.Context, *datacatalogpb.ListTaxonomiesRequest, ...gax.CallOption) *TaxonomyIterator + GetTaxonomy(context.Context, *datacatalogpb.GetTaxonomyRequest, ...gax.CallOption) (*datacatalogpb.Taxonomy, error) + CreatePolicyTag(context.Context, *datacatalogpb.CreatePolicyTagRequest, ...gax.CallOption) (*datacatalogpb.PolicyTag, error) + DeletePolicyTag(context.Context, *datacatalogpb.DeletePolicyTagRequest, ...gax.CallOption) error + UpdatePolicyTag(context.Context, *datacatalogpb.UpdatePolicyTagRequest, ...gax.CallOption) (*datacatalogpb.PolicyTag, error) + ListPolicyTags(context.Context, *datacatalogpb.ListPolicyTagsRequest, ...gax.CallOption) *PolicyTagIterator + GetPolicyTag(context.Context, *datacatalogpb.GetPolicyTagRequest, ...gax.CallOption) (*datacatalogpb.PolicyTag, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) +} + // PolicyTagManagerClient is a client for interacting with Google Cloud Data Catalog API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The policy tag manager API service allows clients to manage their taxonomies +// and policy tags. type PolicyTagManagerClient struct { + // The internal transport-dependent client. + internalClient internalPolicyTagManagerClient + + // The call options for this service. + CallOptions *PolicyTagManagerCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *PolicyTagManagerClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *PolicyTagManagerClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *PolicyTagManagerClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateTaxonomy creates a taxonomy in the specified project. +func (c *PolicyTagManagerClient) CreateTaxonomy(ctx context.Context, req *datacatalogpb.CreateTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { + return c.internalClient.CreateTaxonomy(ctx, req, opts...) +} + +// DeleteTaxonomy deletes a taxonomy. This operation will also delete all +// policy tags in this taxonomy along with their associated policies. +func (c *PolicyTagManagerClient) DeleteTaxonomy(ctx context.Context, req *datacatalogpb.DeleteTaxonomyRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTaxonomy(ctx, req, opts...) +} + +// UpdateTaxonomy updates a taxonomy. +func (c *PolicyTagManagerClient) UpdateTaxonomy(ctx context.Context, req *datacatalogpb.UpdateTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { + return c.internalClient.UpdateTaxonomy(ctx, req, opts...) +} + +// ListTaxonomies lists all taxonomies in a project in a particular location that the caller +// has permission to view. +func (c *PolicyTagManagerClient) ListTaxonomies(ctx context.Context, req *datacatalogpb.ListTaxonomiesRequest, opts ...gax.CallOption) *TaxonomyIterator { + return c.internalClient.ListTaxonomies(ctx, req, opts...) +} + +// GetTaxonomy gets a taxonomy. +func (c *PolicyTagManagerClient) GetTaxonomy(ctx context.Context, req *datacatalogpb.GetTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { + return c.internalClient.GetTaxonomy(ctx, req, opts...) +} + +// CreatePolicyTag creates a policy tag in the specified taxonomy. +func (c *PolicyTagManagerClient) CreatePolicyTag(ctx context.Context, req *datacatalogpb.CreatePolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { + return c.internalClient.CreatePolicyTag(ctx, req, opts...) +} + +// DeletePolicyTag deletes a policy tag. Also deletes all of its descendant policy tags. +func (c *PolicyTagManagerClient) DeletePolicyTag(ctx context.Context, req *datacatalogpb.DeletePolicyTagRequest, opts ...gax.CallOption) error { + return c.internalClient.DeletePolicyTag(ctx, req, opts...) +} + +// UpdatePolicyTag updates a policy tag. +func (c *PolicyTagManagerClient) UpdatePolicyTag(ctx context.Context, req *datacatalogpb.UpdatePolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { + return c.internalClient.UpdatePolicyTag(ctx, req, opts...) +} + +// ListPolicyTags lists all policy tags in a taxonomy. +func (c *PolicyTagManagerClient) ListPolicyTags(ctx context.Context, req *datacatalogpb.ListPolicyTagsRequest, opts ...gax.CallOption) *PolicyTagIterator { + return c.internalClient.ListPolicyTags(ctx, req, opts...) +} + +// GetPolicyTag gets a policy tag. +func (c *PolicyTagManagerClient) GetPolicyTag(ctx context.Context, req *datacatalogpb.GetPolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { + return c.internalClient.GetPolicyTag(ctx, req, opts...) +} + +// GetIamPolicy gets the IAM policy for a taxonomy or a policy tag. +func (c *PolicyTagManagerClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// SetIamPolicy sets the IAM policy for a taxonomy or a policy tag. +func (c *PolicyTagManagerClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns the permissions that a caller has on the specified taxonomy or +// policy tag. +func (c *PolicyTagManagerClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// policyTagManagerGRPCClient is a client for interacting with Google Cloud Data Catalog API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type policyTagManagerGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing PolicyTagManagerClient + CallOptions **PolicyTagManagerCallOptions + // The gRPC API client. policyTagManagerClient datacatalogpb.PolicyTagManagerClient - // The call options for this service. - CallOptions *PolicyTagManagerCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewPolicyTagManagerClient creates a new policy tag manager client. +// NewPolicyTagManagerClient creates a new policy tag manager client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The policy tag manager API service allows clients to manage their taxonomies // and policy tags. func NewPolicyTagManagerClient(ctx context.Context, opts ...option.ClientOption) (*PolicyTagManagerClient, error) { - clientOpts := defaultPolicyTagManagerClientOptions() - + clientOpts := defaultPolicyTagManagerGRPCClientOptions() if newPolicyTagManagerClientHook != nil { hookOpts, err := newPolicyTagManagerClientHook(ctx, clientHookParams{}) if err != nil { @@ -127,45 +250,47 @@ func NewPolicyTagManagerClient(ctx context.Context, opts ...option.ClientOption) if err != nil { return nil, err } - c := &PolicyTagManagerClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultPolicyTagManagerCallOptions(), + client := PolicyTagManagerClient{CallOptions: defaultPolicyTagManagerCallOptions()} + c := &policyTagManagerGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, policyTagManagerClient: datacatalogpb.NewPolicyTagManagerClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *PolicyTagManagerClient) Connection() *grpc.ClientConn { +func (c *policyTagManagerGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *PolicyTagManagerClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *PolicyTagManagerClient) setGoogleClientInfo(keyval ...string) { +func (c *policyTagManagerGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateTaxonomy creates a taxonomy in the specified project. -func (c *PolicyTagManagerClient) CreateTaxonomy(ctx context.Context, req *datacatalogpb.CreateTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *policyTagManagerGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *policyTagManagerGRPCClient) CreateTaxonomy(ctx context.Context, req *datacatalogpb.CreateTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTaxonomy[0:len(c.CallOptions.CreateTaxonomy):len(c.CallOptions.CreateTaxonomy)], opts...) + opts = append((*c.CallOptions).CreateTaxonomy[0:len((*c.CallOptions).CreateTaxonomy):len((*c.CallOptions).CreateTaxonomy)], opts...) var resp *datacatalogpb.Taxonomy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -178,12 +303,10 @@ func (c *PolicyTagManagerClient) CreateTaxonomy(ctx context.Context, req *dataca return resp, nil } -// DeleteTaxonomy deletes a taxonomy. This operation will also delete all -// policy tags in this taxonomy along with their associated policies. -func (c *PolicyTagManagerClient) DeleteTaxonomy(ctx context.Context, req *datacatalogpb.DeleteTaxonomyRequest, opts ...gax.CallOption) error { +func (c *policyTagManagerGRPCClient) DeleteTaxonomy(ctx context.Context, req *datacatalogpb.DeleteTaxonomyRequest, opts ...gax.CallOption) error { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTaxonomy[0:len(c.CallOptions.DeleteTaxonomy):len(c.CallOptions.DeleteTaxonomy)], opts...) + opts = append((*c.CallOptions).DeleteTaxonomy[0:len((*c.CallOptions).DeleteTaxonomy):len((*c.CallOptions).DeleteTaxonomy)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.policyTagManagerClient.DeleteTaxonomy(ctx, req, settings.GRPC...) @@ -192,11 +315,10 @@ func (c *PolicyTagManagerClient) DeleteTaxonomy(ctx context.Context, req *dataca return err } -// UpdateTaxonomy updates a taxonomy. -func (c *PolicyTagManagerClient) UpdateTaxonomy(ctx context.Context, req *datacatalogpb.UpdateTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { +func (c *policyTagManagerGRPCClient) UpdateTaxonomy(ctx context.Context, req *datacatalogpb.UpdateTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "taxonomy.name", url.QueryEscape(req.GetTaxonomy().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTaxonomy[0:len(c.CallOptions.UpdateTaxonomy):len(c.CallOptions.UpdateTaxonomy)], opts...) + opts = append((*c.CallOptions).UpdateTaxonomy[0:len((*c.CallOptions).UpdateTaxonomy):len((*c.CallOptions).UpdateTaxonomy)], opts...) var resp *datacatalogpb.Taxonomy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -209,12 +331,10 @@ func (c *PolicyTagManagerClient) UpdateTaxonomy(ctx context.Context, req *dataca return resp, nil } -// ListTaxonomies lists all taxonomies in a project in a particular location that the caller -// has permission to view. -func (c *PolicyTagManagerClient) ListTaxonomies(ctx context.Context, req *datacatalogpb.ListTaxonomiesRequest, opts ...gax.CallOption) *TaxonomyIterator { +func (c *policyTagManagerGRPCClient) ListTaxonomies(ctx context.Context, req *datacatalogpb.ListTaxonomiesRequest, opts ...gax.CallOption) *TaxonomyIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTaxonomies[0:len(c.CallOptions.ListTaxonomies):len(c.CallOptions.ListTaxonomies)], opts...) + opts = append((*c.CallOptions).ListTaxonomies[0:len((*c.CallOptions).ListTaxonomies):len((*c.CallOptions).ListTaxonomies)], opts...) it := &TaxonomyIterator{} req = proto.Clone(req).(*datacatalogpb.ListTaxonomiesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.Taxonomy, string, error) { @@ -251,11 +371,10 @@ func (c *PolicyTagManagerClient) ListTaxonomies(ctx context.Context, req *dataca return it } -// GetTaxonomy gets a taxonomy. -func (c *PolicyTagManagerClient) GetTaxonomy(ctx context.Context, req *datacatalogpb.GetTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { +func (c *policyTagManagerGRPCClient) GetTaxonomy(ctx context.Context, req *datacatalogpb.GetTaxonomyRequest, opts ...gax.CallOption) (*datacatalogpb.Taxonomy, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTaxonomy[0:len(c.CallOptions.GetTaxonomy):len(c.CallOptions.GetTaxonomy)], opts...) + opts = append((*c.CallOptions).GetTaxonomy[0:len((*c.CallOptions).GetTaxonomy):len((*c.CallOptions).GetTaxonomy)], opts...) var resp *datacatalogpb.Taxonomy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -268,11 +387,10 @@ func (c *PolicyTagManagerClient) GetTaxonomy(ctx context.Context, req *datacatal return resp, nil } -// CreatePolicyTag creates a policy tag in the specified taxonomy. -func (c *PolicyTagManagerClient) CreatePolicyTag(ctx context.Context, req *datacatalogpb.CreatePolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { +func (c *policyTagManagerGRPCClient) CreatePolicyTag(ctx context.Context, req *datacatalogpb.CreatePolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreatePolicyTag[0:len(c.CallOptions.CreatePolicyTag):len(c.CallOptions.CreatePolicyTag)], opts...) + opts = append((*c.CallOptions).CreatePolicyTag[0:len((*c.CallOptions).CreatePolicyTag):len((*c.CallOptions).CreatePolicyTag)], opts...) var resp *datacatalogpb.PolicyTag err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -285,11 +403,10 @@ func (c *PolicyTagManagerClient) CreatePolicyTag(ctx context.Context, req *datac return resp, nil } -// DeletePolicyTag deletes a policy tag. Also deletes all of its descendant policy tags. -func (c *PolicyTagManagerClient) DeletePolicyTag(ctx context.Context, req *datacatalogpb.DeletePolicyTagRequest, opts ...gax.CallOption) error { +func (c *policyTagManagerGRPCClient) DeletePolicyTag(ctx context.Context, req *datacatalogpb.DeletePolicyTagRequest, opts ...gax.CallOption) error { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeletePolicyTag[0:len(c.CallOptions.DeletePolicyTag):len(c.CallOptions.DeletePolicyTag)], opts...) + opts = append((*c.CallOptions).DeletePolicyTag[0:len((*c.CallOptions).DeletePolicyTag):len((*c.CallOptions).DeletePolicyTag)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.policyTagManagerClient.DeletePolicyTag(ctx, req, settings.GRPC...) @@ -298,11 +415,10 @@ func (c *PolicyTagManagerClient) DeletePolicyTag(ctx context.Context, req *datac return err } -// UpdatePolicyTag updates a policy tag. -func (c *PolicyTagManagerClient) UpdatePolicyTag(ctx context.Context, req *datacatalogpb.UpdatePolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { +func (c *policyTagManagerGRPCClient) UpdatePolicyTag(ctx context.Context, req *datacatalogpb.UpdatePolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "policy_tag.name", url.QueryEscape(req.GetPolicyTag().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdatePolicyTag[0:len(c.CallOptions.UpdatePolicyTag):len(c.CallOptions.UpdatePolicyTag)], opts...) + opts = append((*c.CallOptions).UpdatePolicyTag[0:len((*c.CallOptions).UpdatePolicyTag):len((*c.CallOptions).UpdatePolicyTag)], opts...) var resp *datacatalogpb.PolicyTag err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -315,11 +431,10 @@ func (c *PolicyTagManagerClient) UpdatePolicyTag(ctx context.Context, req *datac return resp, nil } -// ListPolicyTags lists all policy tags in a taxonomy. -func (c *PolicyTagManagerClient) ListPolicyTags(ctx context.Context, req *datacatalogpb.ListPolicyTagsRequest, opts ...gax.CallOption) *PolicyTagIterator { +func (c *policyTagManagerGRPCClient) ListPolicyTags(ctx context.Context, req *datacatalogpb.ListPolicyTagsRequest, opts ...gax.CallOption) *PolicyTagIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListPolicyTags[0:len(c.CallOptions.ListPolicyTags):len(c.CallOptions.ListPolicyTags)], opts...) + opts = append((*c.CallOptions).ListPolicyTags[0:len((*c.CallOptions).ListPolicyTags):len((*c.CallOptions).ListPolicyTags)], opts...) it := &PolicyTagIterator{} req = proto.Clone(req).(*datacatalogpb.ListPolicyTagsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datacatalogpb.PolicyTag, string, error) { @@ -356,11 +471,10 @@ func (c *PolicyTagManagerClient) ListPolicyTags(ctx context.Context, req *dataca return it } -// GetPolicyTag gets a policy tag. -func (c *PolicyTagManagerClient) GetPolicyTag(ctx context.Context, req *datacatalogpb.GetPolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { +func (c *policyTagManagerGRPCClient) GetPolicyTag(ctx context.Context, req *datacatalogpb.GetPolicyTagRequest, opts ...gax.CallOption) (*datacatalogpb.PolicyTag, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetPolicyTag[0:len(c.CallOptions.GetPolicyTag):len(c.CallOptions.GetPolicyTag)], opts...) + opts = append((*c.CallOptions).GetPolicyTag[0:len((*c.CallOptions).GetPolicyTag):len((*c.CallOptions).GetPolicyTag)], opts...) var resp *datacatalogpb.PolicyTag err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -373,11 +487,10 @@ func (c *PolicyTagManagerClient) GetPolicyTag(ctx context.Context, req *datacata return resp, nil } -// GetIamPolicy gets the IAM policy for a taxonomy or a policy tag. -func (c *PolicyTagManagerClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *policyTagManagerGRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -390,11 +503,10 @@ func (c *PolicyTagManagerClient) GetIamPolicy(ctx context.Context, req *iampb.Ge return resp, nil } -// SetIamPolicy sets the IAM policy for a taxonomy or a policy tag. -func (c *PolicyTagManagerClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *policyTagManagerGRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -407,12 +519,10 @@ func (c *PolicyTagManagerClient) SetIamPolicy(ctx context.Context, req *iampb.Se return resp, nil } -// TestIamPermissions returns the permissions that a caller has on the specified taxonomy or -// policy tag. -func (c *PolicyTagManagerClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *policyTagManagerGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/datacatalog/apiv1beta1/policy_tag_manager_client_example_test.go b/datacatalog/apiv1beta1/policy_tag_manager_client_example_test.go index 6342f5a674ee..0dcfef674f53 100644 --- a/datacatalog/apiv1beta1/policy_tag_manager_client_example_test.go +++ b/datacatalog/apiv1beta1/policy_tag_manager_client_example_test.go @@ -31,18 +31,19 @@ func ExampleNewPolicyTagManagerClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExamplePolicyTagManagerClient_CreateTaxonomy() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateTaxonomyRequest{ // TODO: Fill request struct fields. @@ -61,6 +62,7 @@ func ExamplePolicyTagManagerClient_DeleteTaxonomy() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteTaxonomyRequest{ // TODO: Fill request struct fields. @@ -72,13 +74,12 @@ func ExamplePolicyTagManagerClient_DeleteTaxonomy() { } func ExamplePolicyTagManagerClient_UpdateTaxonomy() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateTaxonomyRequest{ // TODO: Fill request struct fields. @@ -92,14 +93,12 @@ func ExamplePolicyTagManagerClient_UpdateTaxonomy() { } func ExamplePolicyTagManagerClient_ListTaxonomies() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListTaxonomiesRequest{ // TODO: Fill request struct fields. @@ -119,13 +118,12 @@ func ExamplePolicyTagManagerClient_ListTaxonomies() { } func ExamplePolicyTagManagerClient_GetTaxonomy() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetTaxonomyRequest{ // TODO: Fill request struct fields. @@ -139,13 +137,12 @@ func ExamplePolicyTagManagerClient_GetTaxonomy() { } func ExamplePolicyTagManagerClient_CreatePolicyTag() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreatePolicyTagRequest{ // TODO: Fill request struct fields. @@ -164,6 +161,7 @@ func ExamplePolicyTagManagerClient_DeletePolicyTag() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeletePolicyTagRequest{ // TODO: Fill request struct fields. @@ -175,13 +173,12 @@ func ExamplePolicyTagManagerClient_DeletePolicyTag() { } func ExamplePolicyTagManagerClient_UpdatePolicyTag() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdatePolicyTagRequest{ // TODO: Fill request struct fields. @@ -195,14 +192,12 @@ func ExamplePolicyTagManagerClient_UpdatePolicyTag() { } func ExamplePolicyTagManagerClient_ListPolicyTags() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListPolicyTagsRequest{ // TODO: Fill request struct fields. @@ -222,13 +217,12 @@ func ExamplePolicyTagManagerClient_ListPolicyTags() { } func ExamplePolicyTagManagerClient_GetPolicyTag() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetPolicyTagRequest{ // TODO: Fill request struct fields. @@ -242,13 +236,12 @@ func ExamplePolicyTagManagerClient_GetPolicyTag() { } func ExamplePolicyTagManagerClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -262,13 +255,12 @@ func ExamplePolicyTagManagerClient_GetIamPolicy() { } func ExamplePolicyTagManagerClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -282,13 +274,12 @@ func ExamplePolicyTagManagerClient_SetIamPolicy() { } func ExamplePolicyTagManagerClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/datacatalog/apiv1beta1/policy_tag_manager_serialization_client.go b/datacatalog/apiv1beta1/policy_tag_manager_serialization_client.go index ecc5bd57240c..d0ed65fca52c 100644 --- a/datacatalog/apiv1beta1/policy_tag_manager_serialization_client.go +++ b/datacatalog/apiv1beta1/policy_tag_manager_serialization_client.go @@ -39,7 +39,7 @@ type PolicyTagManagerSerializationCallOptions struct { ExportTaxonomies []gax.CallOption } -func defaultPolicyTagManagerSerializationClientOptions() []option.ClientOption { +func defaultPolicyTagManagerSerializationGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("datacatalog.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("datacatalog.mtls.googleapis.com:443"), @@ -58,33 +58,94 @@ func defaultPolicyTagManagerSerializationCallOptions() *PolicyTagManagerSerializ } } +// internalPolicyTagManagerSerializationClient is an interface that defines the methods availaible from Google Cloud Data Catalog API. +type internalPolicyTagManagerSerializationClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ImportTaxonomies(context.Context, *datacatalogpb.ImportTaxonomiesRequest, ...gax.CallOption) (*datacatalogpb.ImportTaxonomiesResponse, error) + ExportTaxonomies(context.Context, *datacatalogpb.ExportTaxonomiesRequest, ...gax.CallOption) (*datacatalogpb.ExportTaxonomiesResponse, error) +} + // PolicyTagManagerSerializationClient is a client for interacting with Google Cloud Data Catalog API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Policy tag manager serialization API service allows clients to manipulate +// their taxonomies and policy tags data with serialized format. type PolicyTagManagerSerializationClient struct { + // The internal transport-dependent client. + internalClient internalPolicyTagManagerSerializationClient + + // The call options for this service. + CallOptions *PolicyTagManagerSerializationCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *PolicyTagManagerSerializationClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *PolicyTagManagerSerializationClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *PolicyTagManagerSerializationClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ImportTaxonomies imports all taxonomies and their policy tags to a project as new +// taxonomies. +// +// This method provides a bulk taxonomy / policy tag creation using nested +// proto structure. +func (c *PolicyTagManagerSerializationClient) ImportTaxonomies(ctx context.Context, req *datacatalogpb.ImportTaxonomiesRequest, opts ...gax.CallOption) (*datacatalogpb.ImportTaxonomiesResponse, error) { + return c.internalClient.ImportTaxonomies(ctx, req, opts...) +} + +// ExportTaxonomies exports all taxonomies and their policy tags in a project. +// +// This method generates SerializedTaxonomy protos with nested policy tags +// that can be used as an input for future ImportTaxonomies calls. +func (c *PolicyTagManagerSerializationClient) ExportTaxonomies(ctx context.Context, req *datacatalogpb.ExportTaxonomiesRequest, opts ...gax.CallOption) (*datacatalogpb.ExportTaxonomiesResponse, error) { + return c.internalClient.ExportTaxonomies(ctx, req, opts...) +} + +// policyTagManagerSerializationGRPCClient is a client for interacting with Google Cloud Data Catalog API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type policyTagManagerSerializationGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing PolicyTagManagerSerializationClient + CallOptions **PolicyTagManagerSerializationCallOptions + // The gRPC API client. policyTagManagerSerializationClient datacatalogpb.PolicyTagManagerSerializationClient - // The call options for this service. - CallOptions *PolicyTagManagerSerializationCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewPolicyTagManagerSerializationClient creates a new policy tag manager serialization client. +// NewPolicyTagManagerSerializationClient creates a new policy tag manager serialization client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Policy tag manager serialization API service allows clients to manipulate // their taxonomies and policy tags data with serialized format. func NewPolicyTagManagerSerializationClient(ctx context.Context, opts ...option.ClientOption) (*PolicyTagManagerSerializationClient, error) { - clientOpts := defaultPolicyTagManagerSerializationClientOptions() - + clientOpts := defaultPolicyTagManagerSerializationGRPCClientOptions() if newPolicyTagManagerSerializationClientHook != nil { hookOpts, err := newPolicyTagManagerSerializationClientHook(ctx, clientHookParams{}) if err != nil { @@ -102,49 +163,47 @@ func NewPolicyTagManagerSerializationClient(ctx context.Context, opts ...option. if err != nil { return nil, err } - c := &PolicyTagManagerSerializationClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultPolicyTagManagerSerializationCallOptions(), + client := PolicyTagManagerSerializationClient{CallOptions: defaultPolicyTagManagerSerializationCallOptions()} + c := &policyTagManagerSerializationGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, policyTagManagerSerializationClient: datacatalogpb.NewPolicyTagManagerSerializationClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *PolicyTagManagerSerializationClient) Connection() *grpc.ClientConn { +func (c *policyTagManagerSerializationGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *PolicyTagManagerSerializationClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *PolicyTagManagerSerializationClient) setGoogleClientInfo(keyval ...string) { +func (c *policyTagManagerSerializationGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ImportTaxonomies imports all taxonomies and their policy tags to a project as new -// taxonomies. -// -// This method provides a bulk taxonomy / policy tag creation using nested -// proto structure. -func (c *PolicyTagManagerSerializationClient) ImportTaxonomies(ctx context.Context, req *datacatalogpb.ImportTaxonomiesRequest, opts ...gax.CallOption) (*datacatalogpb.ImportTaxonomiesResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *policyTagManagerSerializationGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *policyTagManagerSerializationGRPCClient) ImportTaxonomies(ctx context.Context, req *datacatalogpb.ImportTaxonomiesRequest, opts ...gax.CallOption) (*datacatalogpb.ImportTaxonomiesResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportTaxonomies[0:len(c.CallOptions.ImportTaxonomies):len(c.CallOptions.ImportTaxonomies)], opts...) + opts = append((*c.CallOptions).ImportTaxonomies[0:len((*c.CallOptions).ImportTaxonomies):len((*c.CallOptions).ImportTaxonomies)], opts...) var resp *datacatalogpb.ImportTaxonomiesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -157,14 +216,10 @@ func (c *PolicyTagManagerSerializationClient) ImportTaxonomies(ctx context.Conte return resp, nil } -// ExportTaxonomies exports all taxonomies and their policy tags in a project. -// -// This method generates SerializedTaxonomy protos with nested policy tags -// that can be used as an input for future ImportTaxonomies calls. -func (c *PolicyTagManagerSerializationClient) ExportTaxonomies(ctx context.Context, req *datacatalogpb.ExportTaxonomiesRequest, opts ...gax.CallOption) (*datacatalogpb.ExportTaxonomiesResponse, error) { +func (c *policyTagManagerSerializationGRPCClient) ExportTaxonomies(ctx context.Context, req *datacatalogpb.ExportTaxonomiesRequest, opts ...gax.CallOption) (*datacatalogpb.ExportTaxonomiesResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportTaxonomies[0:len(c.CallOptions.ExportTaxonomies):len(c.CallOptions.ExportTaxonomies)], opts...) + opts = append((*c.CallOptions).ExportTaxonomies[0:len((*c.CallOptions).ExportTaxonomies):len((*c.CallOptions).ExportTaxonomies)], opts...) var resp *datacatalogpb.ExportTaxonomiesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/datacatalog/apiv1beta1/policy_tag_manager_serialization_client_example_test.go b/datacatalog/apiv1beta1/policy_tag_manager_serialization_client_example_test.go index dc70ae549032..da468594670d 100644 --- a/datacatalog/apiv1beta1/policy_tag_manager_serialization_client_example_test.go +++ b/datacatalog/apiv1beta1/policy_tag_manager_serialization_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewPolicyTagManagerSerializationClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExamplePolicyTagManagerSerializationClient_ImportTaxonomies() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerSerializationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ImportTaxonomiesRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExamplePolicyTagManagerSerializationClient_ImportTaxonomies() { } func ExamplePolicyTagManagerSerializationClient_ExportTaxonomies() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerSerializationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ExportTaxonomiesRequest{ // TODO: Fill request struct fields. diff --git a/datalabeling/apiv1beta1/data_labeling_client.go b/datalabeling/apiv1beta1/data_labeling_client.go index 377489bb63e0..673628abc2e6 100644 --- a/datalabeling/apiv1beta1/data_labeling_client.go +++ b/datalabeling/apiv1beta1/data_labeling_client.go @@ -78,7 +78,7 @@ type CallOptions struct { ListEvaluationJobs []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("datalabeling.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("datalabeling.mtls.googleapis.com:443"), @@ -360,37 +360,349 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Data Labeling API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateDataset(context.Context, *datalabelingpb.CreateDatasetRequest, ...gax.CallOption) (*datalabelingpb.Dataset, error) + GetDataset(context.Context, *datalabelingpb.GetDatasetRequest, ...gax.CallOption) (*datalabelingpb.Dataset, error) + ListDatasets(context.Context, *datalabelingpb.ListDatasetsRequest, ...gax.CallOption) *DatasetIterator + DeleteDataset(context.Context, *datalabelingpb.DeleteDatasetRequest, ...gax.CallOption) error + ImportData(context.Context, *datalabelingpb.ImportDataRequest, ...gax.CallOption) (*ImportDataOperation, error) + ImportDataOperation(name string) *ImportDataOperation + ExportData(context.Context, *datalabelingpb.ExportDataRequest, ...gax.CallOption) (*ExportDataOperation, error) + ExportDataOperation(name string) *ExportDataOperation + GetDataItem(context.Context, *datalabelingpb.GetDataItemRequest, ...gax.CallOption) (*datalabelingpb.DataItem, error) + ListDataItems(context.Context, *datalabelingpb.ListDataItemsRequest, ...gax.CallOption) *DataItemIterator + GetAnnotatedDataset(context.Context, *datalabelingpb.GetAnnotatedDatasetRequest, ...gax.CallOption) (*datalabelingpb.AnnotatedDataset, error) + ListAnnotatedDatasets(context.Context, *datalabelingpb.ListAnnotatedDatasetsRequest, ...gax.CallOption) *AnnotatedDatasetIterator + DeleteAnnotatedDataset(context.Context, *datalabelingpb.DeleteAnnotatedDatasetRequest, ...gax.CallOption) error + LabelImage(context.Context, *datalabelingpb.LabelImageRequest, ...gax.CallOption) (*LabelImageOperation, error) + LabelImageOperation(name string) *LabelImageOperation + LabelVideo(context.Context, *datalabelingpb.LabelVideoRequest, ...gax.CallOption) (*LabelVideoOperation, error) + LabelVideoOperation(name string) *LabelVideoOperation + LabelText(context.Context, *datalabelingpb.LabelTextRequest, ...gax.CallOption) (*LabelTextOperation, error) + LabelTextOperation(name string) *LabelTextOperation + GetExample(context.Context, *datalabelingpb.GetExampleRequest, ...gax.CallOption) (*datalabelingpb.Example, error) + ListExamples(context.Context, *datalabelingpb.ListExamplesRequest, ...gax.CallOption) *ExampleIterator + CreateAnnotationSpecSet(context.Context, *datalabelingpb.CreateAnnotationSpecSetRequest, ...gax.CallOption) (*datalabelingpb.AnnotationSpecSet, error) + GetAnnotationSpecSet(context.Context, *datalabelingpb.GetAnnotationSpecSetRequest, ...gax.CallOption) (*datalabelingpb.AnnotationSpecSet, error) + ListAnnotationSpecSets(context.Context, *datalabelingpb.ListAnnotationSpecSetsRequest, ...gax.CallOption) *AnnotationSpecSetIterator + DeleteAnnotationSpecSet(context.Context, *datalabelingpb.DeleteAnnotationSpecSetRequest, ...gax.CallOption) error + CreateInstruction(context.Context, *datalabelingpb.CreateInstructionRequest, ...gax.CallOption) (*CreateInstructionOperation, error) + CreateInstructionOperation(name string) *CreateInstructionOperation + GetInstruction(context.Context, *datalabelingpb.GetInstructionRequest, ...gax.CallOption) (*datalabelingpb.Instruction, error) + ListInstructions(context.Context, *datalabelingpb.ListInstructionsRequest, ...gax.CallOption) *InstructionIterator + DeleteInstruction(context.Context, *datalabelingpb.DeleteInstructionRequest, ...gax.CallOption) error + GetEvaluation(context.Context, *datalabelingpb.GetEvaluationRequest, ...gax.CallOption) (*datalabelingpb.Evaluation, error) + SearchEvaluations(context.Context, *datalabelingpb.SearchEvaluationsRequest, ...gax.CallOption) *EvaluationIterator + SearchExampleComparisons(context.Context, *datalabelingpb.SearchExampleComparisonsRequest, ...gax.CallOption) *SearchExampleComparisonsResponse_ExampleComparisonIterator + CreateEvaluationJob(context.Context, *datalabelingpb.CreateEvaluationJobRequest, ...gax.CallOption) (*datalabelingpb.EvaluationJob, error) + UpdateEvaluationJob(context.Context, *datalabelingpb.UpdateEvaluationJobRequest, ...gax.CallOption) (*datalabelingpb.EvaluationJob, error) + GetEvaluationJob(context.Context, *datalabelingpb.GetEvaluationJobRequest, ...gax.CallOption) (*datalabelingpb.EvaluationJob, error) + PauseEvaluationJob(context.Context, *datalabelingpb.PauseEvaluationJobRequest, ...gax.CallOption) error + ResumeEvaluationJob(context.Context, *datalabelingpb.ResumeEvaluationJobRequest, ...gax.CallOption) error + DeleteEvaluationJob(context.Context, *datalabelingpb.DeleteEvaluationJobRequest, ...gax.CallOption) error + ListEvaluationJobs(context.Context, *datalabelingpb.ListEvaluationJobsRequest, ...gax.CallOption) *EvaluationJobIterator +} + // Client is a client for interacting with Data Labeling API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for the AI Platform Data Labeling API. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateDataset creates dataset. If success return a Dataset resource. +func (c *Client) CreateDataset(ctx context.Context, req *datalabelingpb.CreateDatasetRequest, opts ...gax.CallOption) (*datalabelingpb.Dataset, error) { + return c.internalClient.CreateDataset(ctx, req, opts...) +} + +// GetDataset gets dataset by resource name. +func (c *Client) GetDataset(ctx context.Context, req *datalabelingpb.GetDatasetRequest, opts ...gax.CallOption) (*datalabelingpb.Dataset, error) { + return c.internalClient.GetDataset(ctx, req, opts...) +} + +// ListDatasets lists datasets under a project. Pagination is supported. +func (c *Client) ListDatasets(ctx context.Context, req *datalabelingpb.ListDatasetsRequest, opts ...gax.CallOption) *DatasetIterator { + return c.internalClient.ListDatasets(ctx, req, opts...) +} + +// DeleteDataset deletes a dataset by resource name. +func (c *Client) DeleteDataset(ctx context.Context, req *datalabelingpb.DeleteDatasetRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteDataset(ctx, req, opts...) +} + +// ImportData imports data into dataset based on source locations defined in request. +// It can be called multiple times for the same dataset. Each dataset can +// only have one long running operation running on it. For example, no +// labeling task (also long running operation) can be started while +// importing is still ongoing. Vice versa. +func (c *Client) ImportData(ctx context.Context, req *datalabelingpb.ImportDataRequest, opts ...gax.CallOption) (*ImportDataOperation, error) { + return c.internalClient.ImportData(ctx, req, opts...) +} + +// ImportDataOperation returns a new ImportDataOperation from a given name. +// The name must be that of a previously created ImportDataOperation, possibly from a different process. +func (c *Client) ImportDataOperation(name string) *ImportDataOperation { + return c.internalClient.ImportDataOperation(name) +} + +// ExportData exports data and annotations from dataset. +func (c *Client) ExportData(ctx context.Context, req *datalabelingpb.ExportDataRequest, opts ...gax.CallOption) (*ExportDataOperation, error) { + return c.internalClient.ExportData(ctx, req, opts...) +} + +// ExportDataOperation returns a new ExportDataOperation from a given name. +// The name must be that of a previously created ExportDataOperation, possibly from a different process. +func (c *Client) ExportDataOperation(name string) *ExportDataOperation { + return c.internalClient.ExportDataOperation(name) +} + +// GetDataItem gets a data item in a dataset by resource name. This API can be +// called after data are imported into dataset. +func (c *Client) GetDataItem(ctx context.Context, req *datalabelingpb.GetDataItemRequest, opts ...gax.CallOption) (*datalabelingpb.DataItem, error) { + return c.internalClient.GetDataItem(ctx, req, opts...) +} + +// ListDataItems lists data items in a dataset. This API can be called after data +// are imported into dataset. Pagination is supported. +func (c *Client) ListDataItems(ctx context.Context, req *datalabelingpb.ListDataItemsRequest, opts ...gax.CallOption) *DataItemIterator { + return c.internalClient.ListDataItems(ctx, req, opts...) +} + +// GetAnnotatedDataset gets an annotated dataset by resource name. +func (c *Client) GetAnnotatedDataset(ctx context.Context, req *datalabelingpb.GetAnnotatedDatasetRequest, opts ...gax.CallOption) (*datalabelingpb.AnnotatedDataset, error) { + return c.internalClient.GetAnnotatedDataset(ctx, req, opts...) +} + +// ListAnnotatedDatasets lists annotated datasets for a dataset. Pagination is supported. +func (c *Client) ListAnnotatedDatasets(ctx context.Context, req *datalabelingpb.ListAnnotatedDatasetsRequest, opts ...gax.CallOption) *AnnotatedDatasetIterator { + return c.internalClient.ListAnnotatedDatasets(ctx, req, opts...) +} + +// DeleteAnnotatedDataset deletes an annotated dataset by resource name. +func (c *Client) DeleteAnnotatedDataset(ctx context.Context, req *datalabelingpb.DeleteAnnotatedDatasetRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteAnnotatedDataset(ctx, req, opts...) +} + +// LabelImage starts a labeling task for image. The type of image labeling task is +// configured by feature in the request. +func (c *Client) LabelImage(ctx context.Context, req *datalabelingpb.LabelImageRequest, opts ...gax.CallOption) (*LabelImageOperation, error) { + return c.internalClient.LabelImage(ctx, req, opts...) +} + +// LabelImageOperation returns a new LabelImageOperation from a given name. +// The name must be that of a previously created LabelImageOperation, possibly from a different process. +func (c *Client) LabelImageOperation(name string) *LabelImageOperation { + return c.internalClient.LabelImageOperation(name) +} + +// LabelVideo starts a labeling task for video. The type of video labeling task is +// configured by feature in the request. +func (c *Client) LabelVideo(ctx context.Context, req *datalabelingpb.LabelVideoRequest, opts ...gax.CallOption) (*LabelVideoOperation, error) { + return c.internalClient.LabelVideo(ctx, req, opts...) +} + +// LabelVideoOperation returns a new LabelVideoOperation from a given name. +// The name must be that of a previously created LabelVideoOperation, possibly from a different process. +func (c *Client) LabelVideoOperation(name string) *LabelVideoOperation { + return c.internalClient.LabelVideoOperation(name) +} + +// LabelText starts a labeling task for text. The type of text labeling task is +// configured by feature in the request. +func (c *Client) LabelText(ctx context.Context, req *datalabelingpb.LabelTextRequest, opts ...gax.CallOption) (*LabelTextOperation, error) { + return c.internalClient.LabelText(ctx, req, opts...) +} + +// LabelTextOperation returns a new LabelTextOperation from a given name. +// The name must be that of a previously created LabelTextOperation, possibly from a different process. +func (c *Client) LabelTextOperation(name string) *LabelTextOperation { + return c.internalClient.LabelTextOperation(name) +} + +// GetExample gets an example by resource name, including both data and annotation. +func (c *Client) GetExample(ctx context.Context, req *datalabelingpb.GetExampleRequest, opts ...gax.CallOption) (*datalabelingpb.Example, error) { + return c.internalClient.GetExample(ctx, req, opts...) +} + +// ListExamples lists examples in an annotated dataset. Pagination is supported. +func (c *Client) ListExamples(ctx context.Context, req *datalabelingpb.ListExamplesRequest, opts ...gax.CallOption) *ExampleIterator { + return c.internalClient.ListExamples(ctx, req, opts...) +} + +// CreateAnnotationSpecSet creates an annotation spec set by providing a set of labels. +func (c *Client) CreateAnnotationSpecSet(ctx context.Context, req *datalabelingpb.CreateAnnotationSpecSetRequest, opts ...gax.CallOption) (*datalabelingpb.AnnotationSpecSet, error) { + return c.internalClient.CreateAnnotationSpecSet(ctx, req, opts...) +} + +// GetAnnotationSpecSet gets an annotation spec set by resource name. +func (c *Client) GetAnnotationSpecSet(ctx context.Context, req *datalabelingpb.GetAnnotationSpecSetRequest, opts ...gax.CallOption) (*datalabelingpb.AnnotationSpecSet, error) { + return c.internalClient.GetAnnotationSpecSet(ctx, req, opts...) +} + +// ListAnnotationSpecSets lists annotation spec sets for a project. Pagination is supported. +func (c *Client) ListAnnotationSpecSets(ctx context.Context, req *datalabelingpb.ListAnnotationSpecSetsRequest, opts ...gax.CallOption) *AnnotationSpecSetIterator { + return c.internalClient.ListAnnotationSpecSets(ctx, req, opts...) +} + +// DeleteAnnotationSpecSet deletes an annotation spec set by resource name. +func (c *Client) DeleteAnnotationSpecSet(ctx context.Context, req *datalabelingpb.DeleteAnnotationSpecSetRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteAnnotationSpecSet(ctx, req, opts...) +} + +// CreateInstruction creates an instruction for how data should be labeled. +func (c *Client) CreateInstruction(ctx context.Context, req *datalabelingpb.CreateInstructionRequest, opts ...gax.CallOption) (*CreateInstructionOperation, error) { + return c.internalClient.CreateInstruction(ctx, req, opts...) +} + +// CreateInstructionOperation returns a new CreateInstructionOperation from a given name. +// The name must be that of a previously created CreateInstructionOperation, possibly from a different process. +func (c *Client) CreateInstructionOperation(name string) *CreateInstructionOperation { + return c.internalClient.CreateInstructionOperation(name) +} + +// GetInstruction gets an instruction by resource name. +func (c *Client) GetInstruction(ctx context.Context, req *datalabelingpb.GetInstructionRequest, opts ...gax.CallOption) (*datalabelingpb.Instruction, error) { + return c.internalClient.GetInstruction(ctx, req, opts...) +} + +// ListInstructions lists instructions for a project. Pagination is supported. +func (c *Client) ListInstructions(ctx context.Context, req *datalabelingpb.ListInstructionsRequest, opts ...gax.CallOption) *InstructionIterator { + return c.internalClient.ListInstructions(ctx, req, opts...) +} + +// DeleteInstruction deletes an instruction object by resource name. +func (c *Client) DeleteInstruction(ctx context.Context, req *datalabelingpb.DeleteInstructionRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteInstruction(ctx, req, opts...) +} + +// GetEvaluation gets an evaluation by resource name (to search, use +// projects.evaluations.search). +func (c *Client) GetEvaluation(ctx context.Context, req *datalabelingpb.GetEvaluationRequest, opts ...gax.CallOption) (*datalabelingpb.Evaluation, error) { + return c.internalClient.GetEvaluation(ctx, req, opts...) +} + +// SearchEvaluations searches evaluations within a project. +func (c *Client) SearchEvaluations(ctx context.Context, req *datalabelingpb.SearchEvaluationsRequest, opts ...gax.CallOption) *EvaluationIterator { + return c.internalClient.SearchEvaluations(ctx, req, opts...) +} + +// SearchExampleComparisons searches example comparisons from an evaluation. The return format is a +// list of example comparisons that show ground truth and prediction(s) for +// a single input. Search by providing an evaluation ID. +func (c *Client) SearchExampleComparisons(ctx context.Context, req *datalabelingpb.SearchExampleComparisonsRequest, opts ...gax.CallOption) *SearchExampleComparisonsResponse_ExampleComparisonIterator { + return c.internalClient.SearchExampleComparisons(ctx, req, opts...) +} + +// CreateEvaluationJob creates an evaluation job. +func (c *Client) CreateEvaluationJob(ctx context.Context, req *datalabelingpb.CreateEvaluationJobRequest, opts ...gax.CallOption) (*datalabelingpb.EvaluationJob, error) { + return c.internalClient.CreateEvaluationJob(ctx, req, opts...) +} + +// UpdateEvaluationJob updates an evaluation job. You can only update certain fields of the job’s +// EvaluationJobConfig: humanAnnotationConfig.instruction, +// exampleCount, and exampleSamplePercentage. +// +// If you want to change any other aspect of the evaluation job, you must +// delete the job and create a new one. +func (c *Client) UpdateEvaluationJob(ctx context.Context, req *datalabelingpb.UpdateEvaluationJobRequest, opts ...gax.CallOption) (*datalabelingpb.EvaluationJob, error) { + return c.internalClient.UpdateEvaluationJob(ctx, req, opts...) +} + +// GetEvaluationJob gets an evaluation job by resource name. +func (c *Client) GetEvaluationJob(ctx context.Context, req *datalabelingpb.GetEvaluationJobRequest, opts ...gax.CallOption) (*datalabelingpb.EvaluationJob, error) { + return c.internalClient.GetEvaluationJob(ctx, req, opts...) +} + +// PauseEvaluationJob pauses an evaluation job. Pausing an evaluation job that is already in a +// PAUSED state is a no-op. +func (c *Client) PauseEvaluationJob(ctx context.Context, req *datalabelingpb.PauseEvaluationJobRequest, opts ...gax.CallOption) error { + return c.internalClient.PauseEvaluationJob(ctx, req, opts...) +} + +// ResumeEvaluationJob resumes a paused evaluation job. A deleted evaluation job can’t be resumed. +// Resuming a running or scheduled evaluation job is a no-op. +func (c *Client) ResumeEvaluationJob(ctx context.Context, req *datalabelingpb.ResumeEvaluationJobRequest, opts ...gax.CallOption) error { + return c.internalClient.ResumeEvaluationJob(ctx, req, opts...) +} + +// DeleteEvaluationJob stops and deletes an evaluation job. +func (c *Client) DeleteEvaluationJob(ctx context.Context, req *datalabelingpb.DeleteEvaluationJobRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteEvaluationJob(ctx, req, opts...) +} + +// ListEvaluationJobs lists all evaluation jobs within a project with possible filters. +// Pagination is supported. +func (c *Client) ListEvaluationJobs(ctx context.Context, req *datalabelingpb.ListEvaluationJobsRequest, opts ...gax.CallOption) *EvaluationJobIterator { + return c.internalClient.ListEvaluationJobs(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Data Labeling API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client datalabelingpb.DataLabelingServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new data labeling service client. +// NewClient creates a new data labeling service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for the AI Platform Data Labeling API. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -408,16 +720,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: datalabelingpb.NewDataLabelingServiceClient(connPool), + client: datalabelingpb.NewDataLabelingServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -427,33 +742,33 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateDataset creates dataset. If success return a Dataset resource. -func (c *Client) CreateDataset(ctx context.Context, req *datalabelingpb.CreateDatasetRequest, opts ...gax.CallOption) (*datalabelingpb.Dataset, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateDataset(ctx context.Context, req *datalabelingpb.CreateDatasetRequest, opts ...gax.CallOption) (*datalabelingpb.Dataset, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -461,7 +776,7 @@ func (c *Client) CreateDataset(ctx context.Context, req *datalabelingpb.CreateDa } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateDataset[0:len(c.CallOptions.CreateDataset):len(c.CallOptions.CreateDataset)], opts...) + opts = append((*c.CallOptions).CreateDataset[0:len((*c.CallOptions).CreateDataset):len((*c.CallOptions).CreateDataset)], opts...) var resp *datalabelingpb.Dataset err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -474,8 +789,7 @@ func (c *Client) CreateDataset(ctx context.Context, req *datalabelingpb.CreateDa return resp, nil } -// GetDataset gets dataset by resource name. -func (c *Client) GetDataset(ctx context.Context, req *datalabelingpb.GetDatasetRequest, opts ...gax.CallOption) (*datalabelingpb.Dataset, error) { +func (c *gRPCClient) GetDataset(ctx context.Context, req *datalabelingpb.GetDatasetRequest, opts ...gax.CallOption) (*datalabelingpb.Dataset, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -483,7 +797,7 @@ func (c *Client) GetDataset(ctx context.Context, req *datalabelingpb.GetDatasetR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetDataset[0:len(c.CallOptions.GetDataset):len(c.CallOptions.GetDataset)], opts...) + opts = append((*c.CallOptions).GetDataset[0:len((*c.CallOptions).GetDataset):len((*c.CallOptions).GetDataset)], opts...) var resp *datalabelingpb.Dataset err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -496,11 +810,10 @@ func (c *Client) GetDataset(ctx context.Context, req *datalabelingpb.GetDatasetR return resp, nil } -// ListDatasets lists datasets under a project. Pagination is supported. -func (c *Client) ListDatasets(ctx context.Context, req *datalabelingpb.ListDatasetsRequest, opts ...gax.CallOption) *DatasetIterator { +func (c *gRPCClient) ListDatasets(ctx context.Context, req *datalabelingpb.ListDatasetsRequest, opts ...gax.CallOption) *DatasetIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDatasets[0:len(c.CallOptions.ListDatasets):len(c.CallOptions.ListDatasets)], opts...) + opts = append((*c.CallOptions).ListDatasets[0:len((*c.CallOptions).ListDatasets):len((*c.CallOptions).ListDatasets)], opts...) it := &DatasetIterator{} req = proto.Clone(req).(*datalabelingpb.ListDatasetsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datalabelingpb.Dataset, string, error) { @@ -537,8 +850,7 @@ func (c *Client) ListDatasets(ctx context.Context, req *datalabelingpb.ListDatas return it } -// DeleteDataset deletes a dataset by resource name. -func (c *Client) DeleteDataset(ctx context.Context, req *datalabelingpb.DeleteDatasetRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteDataset(ctx context.Context, req *datalabelingpb.DeleteDatasetRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -546,7 +858,7 @@ func (c *Client) DeleteDataset(ctx context.Context, req *datalabelingpb.DeleteDa } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteDataset[0:len(c.CallOptions.DeleteDataset):len(c.CallOptions.DeleteDataset)], opts...) + opts = append((*c.CallOptions).DeleteDataset[0:len((*c.CallOptions).DeleteDataset):len((*c.CallOptions).DeleteDataset)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteDataset(ctx, req, settings.GRPC...) @@ -555,12 +867,7 @@ func (c *Client) DeleteDataset(ctx context.Context, req *datalabelingpb.DeleteDa return err } -// ImportData imports data into dataset based on source locations defined in request. -// It can be called multiple times for the same dataset. Each dataset can -// only have one long running operation running on it. For example, no -// labeling task (also long running operation) can be started while -// importing is still ongoing. Vice versa. -func (c *Client) ImportData(ctx context.Context, req *datalabelingpb.ImportDataRequest, opts ...gax.CallOption) (*ImportDataOperation, error) { +func (c *gRPCClient) ImportData(ctx context.Context, req *datalabelingpb.ImportDataRequest, opts ...gax.CallOption) (*ImportDataOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -568,7 +875,7 @@ func (c *Client) ImportData(ctx context.Context, req *datalabelingpb.ImportDataR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportData[0:len(c.CallOptions.ImportData):len(c.CallOptions.ImportData)], opts...) + opts = append((*c.CallOptions).ImportData[0:len((*c.CallOptions).ImportData):len((*c.CallOptions).ImportData)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -579,12 +886,11 @@ func (c *Client) ImportData(ctx context.Context, req *datalabelingpb.ImportDataR return nil, err } return &ImportDataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ExportData exports data and annotations from dataset. -func (c *Client) ExportData(ctx context.Context, req *datalabelingpb.ExportDataRequest, opts ...gax.CallOption) (*ExportDataOperation, error) { +func (c *gRPCClient) ExportData(ctx context.Context, req *datalabelingpb.ExportDataRequest, opts ...gax.CallOption) (*ExportDataOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -592,7 +898,7 @@ func (c *Client) ExportData(ctx context.Context, req *datalabelingpb.ExportDataR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportData[0:len(c.CallOptions.ExportData):len(c.CallOptions.ExportData)], opts...) + opts = append((*c.CallOptions).ExportData[0:len((*c.CallOptions).ExportData):len((*c.CallOptions).ExportData)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -603,13 +909,11 @@ func (c *Client) ExportData(ctx context.Context, req *datalabelingpb.ExportDataR return nil, err } return &ExportDataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetDataItem gets a data item in a dataset by resource name. This API can be -// called after data are imported into dataset. -func (c *Client) GetDataItem(ctx context.Context, req *datalabelingpb.GetDataItemRequest, opts ...gax.CallOption) (*datalabelingpb.DataItem, error) { +func (c *gRPCClient) GetDataItem(ctx context.Context, req *datalabelingpb.GetDataItemRequest, opts ...gax.CallOption) (*datalabelingpb.DataItem, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -617,7 +921,7 @@ func (c *Client) GetDataItem(ctx context.Context, req *datalabelingpb.GetDataIte } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetDataItem[0:len(c.CallOptions.GetDataItem):len(c.CallOptions.GetDataItem)], opts...) + opts = append((*c.CallOptions).GetDataItem[0:len((*c.CallOptions).GetDataItem):len((*c.CallOptions).GetDataItem)], opts...) var resp *datalabelingpb.DataItem err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -630,12 +934,10 @@ func (c *Client) GetDataItem(ctx context.Context, req *datalabelingpb.GetDataIte return resp, nil } -// ListDataItems lists data items in a dataset. This API can be called after data -// are imported into dataset. Pagination is supported. -func (c *Client) ListDataItems(ctx context.Context, req *datalabelingpb.ListDataItemsRequest, opts ...gax.CallOption) *DataItemIterator { +func (c *gRPCClient) ListDataItems(ctx context.Context, req *datalabelingpb.ListDataItemsRequest, opts ...gax.CallOption) *DataItemIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDataItems[0:len(c.CallOptions.ListDataItems):len(c.CallOptions.ListDataItems)], opts...) + opts = append((*c.CallOptions).ListDataItems[0:len((*c.CallOptions).ListDataItems):len((*c.CallOptions).ListDataItems)], opts...) it := &DataItemIterator{} req = proto.Clone(req).(*datalabelingpb.ListDataItemsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datalabelingpb.DataItem, string, error) { @@ -672,8 +974,7 @@ func (c *Client) ListDataItems(ctx context.Context, req *datalabelingpb.ListData return it } -// GetAnnotatedDataset gets an annotated dataset by resource name. -func (c *Client) GetAnnotatedDataset(ctx context.Context, req *datalabelingpb.GetAnnotatedDatasetRequest, opts ...gax.CallOption) (*datalabelingpb.AnnotatedDataset, error) { +func (c *gRPCClient) GetAnnotatedDataset(ctx context.Context, req *datalabelingpb.GetAnnotatedDatasetRequest, opts ...gax.CallOption) (*datalabelingpb.AnnotatedDataset, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -681,7 +982,7 @@ func (c *Client) GetAnnotatedDataset(ctx context.Context, req *datalabelingpb.Ge } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetAnnotatedDataset[0:len(c.CallOptions.GetAnnotatedDataset):len(c.CallOptions.GetAnnotatedDataset)], opts...) + opts = append((*c.CallOptions).GetAnnotatedDataset[0:len((*c.CallOptions).GetAnnotatedDataset):len((*c.CallOptions).GetAnnotatedDataset)], opts...) var resp *datalabelingpb.AnnotatedDataset err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -694,11 +995,10 @@ func (c *Client) GetAnnotatedDataset(ctx context.Context, req *datalabelingpb.Ge return resp, nil } -// ListAnnotatedDatasets lists annotated datasets for a dataset. Pagination is supported. -func (c *Client) ListAnnotatedDatasets(ctx context.Context, req *datalabelingpb.ListAnnotatedDatasetsRequest, opts ...gax.CallOption) *AnnotatedDatasetIterator { +func (c *gRPCClient) ListAnnotatedDatasets(ctx context.Context, req *datalabelingpb.ListAnnotatedDatasetsRequest, opts ...gax.CallOption) *AnnotatedDatasetIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAnnotatedDatasets[0:len(c.CallOptions.ListAnnotatedDatasets):len(c.CallOptions.ListAnnotatedDatasets)], opts...) + opts = append((*c.CallOptions).ListAnnotatedDatasets[0:len((*c.CallOptions).ListAnnotatedDatasets):len((*c.CallOptions).ListAnnotatedDatasets)], opts...) it := &AnnotatedDatasetIterator{} req = proto.Clone(req).(*datalabelingpb.ListAnnotatedDatasetsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datalabelingpb.AnnotatedDataset, string, error) { @@ -735,11 +1035,10 @@ func (c *Client) ListAnnotatedDatasets(ctx context.Context, req *datalabelingpb. return it } -// DeleteAnnotatedDataset deletes an annotated dataset by resource name. -func (c *Client) DeleteAnnotatedDataset(ctx context.Context, req *datalabelingpb.DeleteAnnotatedDatasetRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteAnnotatedDataset(ctx context.Context, req *datalabelingpb.DeleteAnnotatedDatasetRequest, opts ...gax.CallOption) error { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteAnnotatedDataset[0:len(c.CallOptions.DeleteAnnotatedDataset):len(c.CallOptions.DeleteAnnotatedDataset)], opts...) + opts = append((*c.CallOptions).DeleteAnnotatedDataset[0:len((*c.CallOptions).DeleteAnnotatedDataset):len((*c.CallOptions).DeleteAnnotatedDataset)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteAnnotatedDataset(ctx, req, settings.GRPC...) @@ -748,9 +1047,7 @@ func (c *Client) DeleteAnnotatedDataset(ctx context.Context, req *datalabelingpb return err } -// LabelImage starts a labeling task for image. The type of image labeling task is -// configured by feature in the request. -func (c *Client) LabelImage(ctx context.Context, req *datalabelingpb.LabelImageRequest, opts ...gax.CallOption) (*LabelImageOperation, error) { +func (c *gRPCClient) LabelImage(ctx context.Context, req *datalabelingpb.LabelImageRequest, opts ...gax.CallOption) (*LabelImageOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -758,7 +1055,7 @@ func (c *Client) LabelImage(ctx context.Context, req *datalabelingpb.LabelImageR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.LabelImage[0:len(c.CallOptions.LabelImage):len(c.CallOptions.LabelImage)], opts...) + opts = append((*c.CallOptions).LabelImage[0:len((*c.CallOptions).LabelImage):len((*c.CallOptions).LabelImage)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -769,13 +1066,11 @@ func (c *Client) LabelImage(ctx context.Context, req *datalabelingpb.LabelImageR return nil, err } return &LabelImageOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// LabelVideo starts a labeling task for video. The type of video labeling task is -// configured by feature in the request. -func (c *Client) LabelVideo(ctx context.Context, req *datalabelingpb.LabelVideoRequest, opts ...gax.CallOption) (*LabelVideoOperation, error) { +func (c *gRPCClient) LabelVideo(ctx context.Context, req *datalabelingpb.LabelVideoRequest, opts ...gax.CallOption) (*LabelVideoOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -783,7 +1078,7 @@ func (c *Client) LabelVideo(ctx context.Context, req *datalabelingpb.LabelVideoR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.LabelVideo[0:len(c.CallOptions.LabelVideo):len(c.CallOptions.LabelVideo)], opts...) + opts = append((*c.CallOptions).LabelVideo[0:len((*c.CallOptions).LabelVideo):len((*c.CallOptions).LabelVideo)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -794,13 +1089,11 @@ func (c *Client) LabelVideo(ctx context.Context, req *datalabelingpb.LabelVideoR return nil, err } return &LabelVideoOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// LabelText starts a labeling task for text. The type of text labeling task is -// configured by feature in the request. -func (c *Client) LabelText(ctx context.Context, req *datalabelingpb.LabelTextRequest, opts ...gax.CallOption) (*LabelTextOperation, error) { +func (c *gRPCClient) LabelText(ctx context.Context, req *datalabelingpb.LabelTextRequest, opts ...gax.CallOption) (*LabelTextOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -808,7 +1101,7 @@ func (c *Client) LabelText(ctx context.Context, req *datalabelingpb.LabelTextReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.LabelText[0:len(c.CallOptions.LabelText):len(c.CallOptions.LabelText)], opts...) + opts = append((*c.CallOptions).LabelText[0:len((*c.CallOptions).LabelText):len((*c.CallOptions).LabelText)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -819,12 +1112,11 @@ func (c *Client) LabelText(ctx context.Context, req *datalabelingpb.LabelTextReq return nil, err } return &LabelTextOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetExample gets an example by resource name, including both data and annotation. -func (c *Client) GetExample(ctx context.Context, req *datalabelingpb.GetExampleRequest, opts ...gax.CallOption) (*datalabelingpb.Example, error) { +func (c *gRPCClient) GetExample(ctx context.Context, req *datalabelingpb.GetExampleRequest, opts ...gax.CallOption) (*datalabelingpb.Example, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -832,7 +1124,7 @@ func (c *Client) GetExample(ctx context.Context, req *datalabelingpb.GetExampleR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetExample[0:len(c.CallOptions.GetExample):len(c.CallOptions.GetExample)], opts...) + opts = append((*c.CallOptions).GetExample[0:len((*c.CallOptions).GetExample):len((*c.CallOptions).GetExample)], opts...) var resp *datalabelingpb.Example err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -845,11 +1137,10 @@ func (c *Client) GetExample(ctx context.Context, req *datalabelingpb.GetExampleR return resp, nil } -// ListExamples lists examples in an annotated dataset. Pagination is supported. -func (c *Client) ListExamples(ctx context.Context, req *datalabelingpb.ListExamplesRequest, opts ...gax.CallOption) *ExampleIterator { +func (c *gRPCClient) ListExamples(ctx context.Context, req *datalabelingpb.ListExamplesRequest, opts ...gax.CallOption) *ExampleIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListExamples[0:len(c.CallOptions.ListExamples):len(c.CallOptions.ListExamples)], opts...) + opts = append((*c.CallOptions).ListExamples[0:len((*c.CallOptions).ListExamples):len((*c.CallOptions).ListExamples)], opts...) it := &ExampleIterator{} req = proto.Clone(req).(*datalabelingpb.ListExamplesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datalabelingpb.Example, string, error) { @@ -886,8 +1177,7 @@ func (c *Client) ListExamples(ctx context.Context, req *datalabelingpb.ListExamp return it } -// CreateAnnotationSpecSet creates an annotation spec set by providing a set of labels. -func (c *Client) CreateAnnotationSpecSet(ctx context.Context, req *datalabelingpb.CreateAnnotationSpecSetRequest, opts ...gax.CallOption) (*datalabelingpb.AnnotationSpecSet, error) { +func (c *gRPCClient) CreateAnnotationSpecSet(ctx context.Context, req *datalabelingpb.CreateAnnotationSpecSetRequest, opts ...gax.CallOption) (*datalabelingpb.AnnotationSpecSet, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -895,7 +1185,7 @@ func (c *Client) CreateAnnotationSpecSet(ctx context.Context, req *datalabelingp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateAnnotationSpecSet[0:len(c.CallOptions.CreateAnnotationSpecSet):len(c.CallOptions.CreateAnnotationSpecSet)], opts...) + opts = append((*c.CallOptions).CreateAnnotationSpecSet[0:len((*c.CallOptions).CreateAnnotationSpecSet):len((*c.CallOptions).CreateAnnotationSpecSet)], opts...) var resp *datalabelingpb.AnnotationSpecSet err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -908,8 +1198,7 @@ func (c *Client) CreateAnnotationSpecSet(ctx context.Context, req *datalabelingp return resp, nil } -// GetAnnotationSpecSet gets an annotation spec set by resource name. -func (c *Client) GetAnnotationSpecSet(ctx context.Context, req *datalabelingpb.GetAnnotationSpecSetRequest, opts ...gax.CallOption) (*datalabelingpb.AnnotationSpecSet, error) { +func (c *gRPCClient) GetAnnotationSpecSet(ctx context.Context, req *datalabelingpb.GetAnnotationSpecSetRequest, opts ...gax.CallOption) (*datalabelingpb.AnnotationSpecSet, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -917,7 +1206,7 @@ func (c *Client) GetAnnotationSpecSet(ctx context.Context, req *datalabelingpb.G } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetAnnotationSpecSet[0:len(c.CallOptions.GetAnnotationSpecSet):len(c.CallOptions.GetAnnotationSpecSet)], opts...) + opts = append((*c.CallOptions).GetAnnotationSpecSet[0:len((*c.CallOptions).GetAnnotationSpecSet):len((*c.CallOptions).GetAnnotationSpecSet)], opts...) var resp *datalabelingpb.AnnotationSpecSet err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -930,11 +1219,10 @@ func (c *Client) GetAnnotationSpecSet(ctx context.Context, req *datalabelingpb.G return resp, nil } -// ListAnnotationSpecSets lists annotation spec sets for a project. Pagination is supported. -func (c *Client) ListAnnotationSpecSets(ctx context.Context, req *datalabelingpb.ListAnnotationSpecSetsRequest, opts ...gax.CallOption) *AnnotationSpecSetIterator { +func (c *gRPCClient) ListAnnotationSpecSets(ctx context.Context, req *datalabelingpb.ListAnnotationSpecSetsRequest, opts ...gax.CallOption) *AnnotationSpecSetIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAnnotationSpecSets[0:len(c.CallOptions.ListAnnotationSpecSets):len(c.CallOptions.ListAnnotationSpecSets)], opts...) + opts = append((*c.CallOptions).ListAnnotationSpecSets[0:len((*c.CallOptions).ListAnnotationSpecSets):len((*c.CallOptions).ListAnnotationSpecSets)], opts...) it := &AnnotationSpecSetIterator{} req = proto.Clone(req).(*datalabelingpb.ListAnnotationSpecSetsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datalabelingpb.AnnotationSpecSet, string, error) { @@ -971,8 +1259,7 @@ func (c *Client) ListAnnotationSpecSets(ctx context.Context, req *datalabelingpb return it } -// DeleteAnnotationSpecSet deletes an annotation spec set by resource name. -func (c *Client) DeleteAnnotationSpecSet(ctx context.Context, req *datalabelingpb.DeleteAnnotationSpecSetRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteAnnotationSpecSet(ctx context.Context, req *datalabelingpb.DeleteAnnotationSpecSetRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -980,7 +1267,7 @@ func (c *Client) DeleteAnnotationSpecSet(ctx context.Context, req *datalabelingp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteAnnotationSpecSet[0:len(c.CallOptions.DeleteAnnotationSpecSet):len(c.CallOptions.DeleteAnnotationSpecSet)], opts...) + opts = append((*c.CallOptions).DeleteAnnotationSpecSet[0:len((*c.CallOptions).DeleteAnnotationSpecSet):len((*c.CallOptions).DeleteAnnotationSpecSet)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteAnnotationSpecSet(ctx, req, settings.GRPC...) @@ -989,8 +1276,7 @@ func (c *Client) DeleteAnnotationSpecSet(ctx context.Context, req *datalabelingp return err } -// CreateInstruction creates an instruction for how data should be labeled. -func (c *Client) CreateInstruction(ctx context.Context, req *datalabelingpb.CreateInstructionRequest, opts ...gax.CallOption) (*CreateInstructionOperation, error) { +func (c *gRPCClient) CreateInstruction(ctx context.Context, req *datalabelingpb.CreateInstructionRequest, opts ...gax.CallOption) (*CreateInstructionOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -998,7 +1284,7 @@ func (c *Client) CreateInstruction(ctx context.Context, req *datalabelingpb.Crea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateInstruction[0:len(c.CallOptions.CreateInstruction):len(c.CallOptions.CreateInstruction)], opts...) + opts = append((*c.CallOptions).CreateInstruction[0:len((*c.CallOptions).CreateInstruction):len((*c.CallOptions).CreateInstruction)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1009,12 +1295,11 @@ func (c *Client) CreateInstruction(ctx context.Context, req *datalabelingpb.Crea return nil, err } return &CreateInstructionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetInstruction gets an instruction by resource name. -func (c *Client) GetInstruction(ctx context.Context, req *datalabelingpb.GetInstructionRequest, opts ...gax.CallOption) (*datalabelingpb.Instruction, error) { +func (c *gRPCClient) GetInstruction(ctx context.Context, req *datalabelingpb.GetInstructionRequest, opts ...gax.CallOption) (*datalabelingpb.Instruction, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -1022,7 +1307,7 @@ func (c *Client) GetInstruction(ctx context.Context, req *datalabelingpb.GetInst } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetInstruction[0:len(c.CallOptions.GetInstruction):len(c.CallOptions.GetInstruction)], opts...) + opts = append((*c.CallOptions).GetInstruction[0:len((*c.CallOptions).GetInstruction):len((*c.CallOptions).GetInstruction)], opts...) var resp *datalabelingpb.Instruction err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1035,11 +1320,10 @@ func (c *Client) GetInstruction(ctx context.Context, req *datalabelingpb.GetInst return resp, nil } -// ListInstructions lists instructions for a project. Pagination is supported. -func (c *Client) ListInstructions(ctx context.Context, req *datalabelingpb.ListInstructionsRequest, opts ...gax.CallOption) *InstructionIterator { +func (c *gRPCClient) ListInstructions(ctx context.Context, req *datalabelingpb.ListInstructionsRequest, opts ...gax.CallOption) *InstructionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListInstructions[0:len(c.CallOptions.ListInstructions):len(c.CallOptions.ListInstructions)], opts...) + opts = append((*c.CallOptions).ListInstructions[0:len((*c.CallOptions).ListInstructions):len((*c.CallOptions).ListInstructions)], opts...) it := &InstructionIterator{} req = proto.Clone(req).(*datalabelingpb.ListInstructionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datalabelingpb.Instruction, string, error) { @@ -1076,8 +1360,7 @@ func (c *Client) ListInstructions(ctx context.Context, req *datalabelingpb.ListI return it } -// DeleteInstruction deletes an instruction object by resource name. -func (c *Client) DeleteInstruction(ctx context.Context, req *datalabelingpb.DeleteInstructionRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteInstruction(ctx context.Context, req *datalabelingpb.DeleteInstructionRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -1085,7 +1368,7 @@ func (c *Client) DeleteInstruction(ctx context.Context, req *datalabelingpb.Dele } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteInstruction[0:len(c.CallOptions.DeleteInstruction):len(c.CallOptions.DeleteInstruction)], opts...) + opts = append((*c.CallOptions).DeleteInstruction[0:len((*c.CallOptions).DeleteInstruction):len((*c.CallOptions).DeleteInstruction)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteInstruction(ctx, req, settings.GRPC...) @@ -1094,9 +1377,7 @@ func (c *Client) DeleteInstruction(ctx context.Context, req *datalabelingpb.Dele return err } -// GetEvaluation gets an evaluation by resource name (to search, use -// projects.evaluations.search). -func (c *Client) GetEvaluation(ctx context.Context, req *datalabelingpb.GetEvaluationRequest, opts ...gax.CallOption) (*datalabelingpb.Evaluation, error) { +func (c *gRPCClient) GetEvaluation(ctx context.Context, req *datalabelingpb.GetEvaluationRequest, opts ...gax.CallOption) (*datalabelingpb.Evaluation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -1104,7 +1385,7 @@ func (c *Client) GetEvaluation(ctx context.Context, req *datalabelingpb.GetEvalu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEvaluation[0:len(c.CallOptions.GetEvaluation):len(c.CallOptions.GetEvaluation)], opts...) + opts = append((*c.CallOptions).GetEvaluation[0:len((*c.CallOptions).GetEvaluation):len((*c.CallOptions).GetEvaluation)], opts...) var resp *datalabelingpb.Evaluation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1117,11 +1398,10 @@ func (c *Client) GetEvaluation(ctx context.Context, req *datalabelingpb.GetEvalu return resp, nil } -// SearchEvaluations searches evaluations within a project. -func (c *Client) SearchEvaluations(ctx context.Context, req *datalabelingpb.SearchEvaluationsRequest, opts ...gax.CallOption) *EvaluationIterator { +func (c *gRPCClient) SearchEvaluations(ctx context.Context, req *datalabelingpb.SearchEvaluationsRequest, opts ...gax.CallOption) *EvaluationIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SearchEvaluations[0:len(c.CallOptions.SearchEvaluations):len(c.CallOptions.SearchEvaluations)], opts...) + opts = append((*c.CallOptions).SearchEvaluations[0:len((*c.CallOptions).SearchEvaluations):len((*c.CallOptions).SearchEvaluations)], opts...) it := &EvaluationIterator{} req = proto.Clone(req).(*datalabelingpb.SearchEvaluationsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datalabelingpb.Evaluation, string, error) { @@ -1158,13 +1438,10 @@ func (c *Client) SearchEvaluations(ctx context.Context, req *datalabelingpb.Sear return it } -// SearchExampleComparisons searches example comparisons from an evaluation. The return format is a -// list of example comparisons that show ground truth and prediction(s) for -// a single input. Search by providing an evaluation ID. -func (c *Client) SearchExampleComparisons(ctx context.Context, req *datalabelingpb.SearchExampleComparisonsRequest, opts ...gax.CallOption) *SearchExampleComparisonsResponse_ExampleComparisonIterator { +func (c *gRPCClient) SearchExampleComparisons(ctx context.Context, req *datalabelingpb.SearchExampleComparisonsRequest, opts ...gax.CallOption) *SearchExampleComparisonsResponse_ExampleComparisonIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SearchExampleComparisons[0:len(c.CallOptions.SearchExampleComparisons):len(c.CallOptions.SearchExampleComparisons)], opts...) + opts = append((*c.CallOptions).SearchExampleComparisons[0:len((*c.CallOptions).SearchExampleComparisons):len((*c.CallOptions).SearchExampleComparisons)], opts...) it := &SearchExampleComparisonsResponse_ExampleComparisonIterator{} req = proto.Clone(req).(*datalabelingpb.SearchExampleComparisonsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datalabelingpb.SearchExampleComparisonsResponse_ExampleComparison, string, error) { @@ -1201,8 +1478,7 @@ func (c *Client) SearchExampleComparisons(ctx context.Context, req *datalabeling return it } -// CreateEvaluationJob creates an evaluation job. -func (c *Client) CreateEvaluationJob(ctx context.Context, req *datalabelingpb.CreateEvaluationJobRequest, opts ...gax.CallOption) (*datalabelingpb.EvaluationJob, error) { +func (c *gRPCClient) CreateEvaluationJob(ctx context.Context, req *datalabelingpb.CreateEvaluationJobRequest, opts ...gax.CallOption) (*datalabelingpb.EvaluationJob, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -1210,7 +1486,7 @@ func (c *Client) CreateEvaluationJob(ctx context.Context, req *datalabelingpb.Cr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateEvaluationJob[0:len(c.CallOptions.CreateEvaluationJob):len(c.CallOptions.CreateEvaluationJob)], opts...) + opts = append((*c.CallOptions).CreateEvaluationJob[0:len((*c.CallOptions).CreateEvaluationJob):len((*c.CallOptions).CreateEvaluationJob)], opts...) var resp *datalabelingpb.EvaluationJob err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1223,13 +1499,7 @@ func (c *Client) CreateEvaluationJob(ctx context.Context, req *datalabelingpb.Cr return resp, nil } -// UpdateEvaluationJob updates an evaluation job. You can only update certain fields of the job’s -// EvaluationJobConfig: humanAnnotationConfig.instruction, -// exampleCount, and exampleSamplePercentage. -// -// If you want to change any other aspect of the evaluation job, you must -// delete the job and create a new one. -func (c *Client) UpdateEvaluationJob(ctx context.Context, req *datalabelingpb.UpdateEvaluationJobRequest, opts ...gax.CallOption) (*datalabelingpb.EvaluationJob, error) { +func (c *gRPCClient) UpdateEvaluationJob(ctx context.Context, req *datalabelingpb.UpdateEvaluationJobRequest, opts ...gax.CallOption) (*datalabelingpb.EvaluationJob, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -1237,7 +1507,7 @@ func (c *Client) UpdateEvaluationJob(ctx context.Context, req *datalabelingpb.Up } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "evaluation_job.name", url.QueryEscape(req.GetEvaluationJob().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateEvaluationJob[0:len(c.CallOptions.UpdateEvaluationJob):len(c.CallOptions.UpdateEvaluationJob)], opts...) + opts = append((*c.CallOptions).UpdateEvaluationJob[0:len((*c.CallOptions).UpdateEvaluationJob):len((*c.CallOptions).UpdateEvaluationJob)], opts...) var resp *datalabelingpb.EvaluationJob err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1250,8 +1520,7 @@ func (c *Client) UpdateEvaluationJob(ctx context.Context, req *datalabelingpb.Up return resp, nil } -// GetEvaluationJob gets an evaluation job by resource name. -func (c *Client) GetEvaluationJob(ctx context.Context, req *datalabelingpb.GetEvaluationJobRequest, opts ...gax.CallOption) (*datalabelingpb.EvaluationJob, error) { +func (c *gRPCClient) GetEvaluationJob(ctx context.Context, req *datalabelingpb.GetEvaluationJobRequest, opts ...gax.CallOption) (*datalabelingpb.EvaluationJob, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -1259,7 +1528,7 @@ func (c *Client) GetEvaluationJob(ctx context.Context, req *datalabelingpb.GetEv } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEvaluationJob[0:len(c.CallOptions.GetEvaluationJob):len(c.CallOptions.GetEvaluationJob)], opts...) + opts = append((*c.CallOptions).GetEvaluationJob[0:len((*c.CallOptions).GetEvaluationJob):len((*c.CallOptions).GetEvaluationJob)], opts...) var resp *datalabelingpb.EvaluationJob err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1272,9 +1541,7 @@ func (c *Client) GetEvaluationJob(ctx context.Context, req *datalabelingpb.GetEv return resp, nil } -// PauseEvaluationJob pauses an evaluation job. Pausing an evaluation job that is already in a -// PAUSED state is a no-op. -func (c *Client) PauseEvaluationJob(ctx context.Context, req *datalabelingpb.PauseEvaluationJobRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) PauseEvaluationJob(ctx context.Context, req *datalabelingpb.PauseEvaluationJobRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -1282,7 +1549,7 @@ func (c *Client) PauseEvaluationJob(ctx context.Context, req *datalabelingpb.Pau } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PauseEvaluationJob[0:len(c.CallOptions.PauseEvaluationJob):len(c.CallOptions.PauseEvaluationJob)], opts...) + opts = append((*c.CallOptions).PauseEvaluationJob[0:len((*c.CallOptions).PauseEvaluationJob):len((*c.CallOptions).PauseEvaluationJob)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.PauseEvaluationJob(ctx, req, settings.GRPC...) @@ -1291,9 +1558,7 @@ func (c *Client) PauseEvaluationJob(ctx context.Context, req *datalabelingpb.Pau return err } -// ResumeEvaluationJob resumes a paused evaluation job. A deleted evaluation job can’t be resumed. -// Resuming a running or scheduled evaluation job is a no-op. -func (c *Client) ResumeEvaluationJob(ctx context.Context, req *datalabelingpb.ResumeEvaluationJobRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) ResumeEvaluationJob(ctx context.Context, req *datalabelingpb.ResumeEvaluationJobRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -1301,7 +1566,7 @@ func (c *Client) ResumeEvaluationJob(ctx context.Context, req *datalabelingpb.Re } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ResumeEvaluationJob[0:len(c.CallOptions.ResumeEvaluationJob):len(c.CallOptions.ResumeEvaluationJob)], opts...) + opts = append((*c.CallOptions).ResumeEvaluationJob[0:len((*c.CallOptions).ResumeEvaluationJob):len((*c.CallOptions).ResumeEvaluationJob)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.ResumeEvaluationJob(ctx, req, settings.GRPC...) @@ -1310,8 +1575,7 @@ func (c *Client) ResumeEvaluationJob(ctx context.Context, req *datalabelingpb.Re return err } -// DeleteEvaluationJob stops and deletes an evaluation job. -func (c *Client) DeleteEvaluationJob(ctx context.Context, req *datalabelingpb.DeleteEvaluationJobRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteEvaluationJob(ctx context.Context, req *datalabelingpb.DeleteEvaluationJobRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -1319,7 +1583,7 @@ func (c *Client) DeleteEvaluationJob(ctx context.Context, req *datalabelingpb.De } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteEvaluationJob[0:len(c.CallOptions.DeleteEvaluationJob):len(c.CallOptions.DeleteEvaluationJob)], opts...) + opts = append((*c.CallOptions).DeleteEvaluationJob[0:len((*c.CallOptions).DeleteEvaluationJob):len((*c.CallOptions).DeleteEvaluationJob)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteEvaluationJob(ctx, req, settings.GRPC...) @@ -1328,12 +1592,10 @@ func (c *Client) DeleteEvaluationJob(ctx context.Context, req *datalabelingpb.De return err } -// ListEvaluationJobs lists all evaluation jobs within a project with possible filters. -// Pagination is supported. -func (c *Client) ListEvaluationJobs(ctx context.Context, req *datalabelingpb.ListEvaluationJobsRequest, opts ...gax.CallOption) *EvaluationJobIterator { +func (c *gRPCClient) ListEvaluationJobs(ctx context.Context, req *datalabelingpb.ListEvaluationJobsRequest, opts ...gax.CallOption) *EvaluationJobIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListEvaluationJobs[0:len(c.CallOptions.ListEvaluationJobs):len(c.CallOptions.ListEvaluationJobs)], opts...) + opts = append((*c.CallOptions).ListEvaluationJobs[0:len((*c.CallOptions).ListEvaluationJobs):len((*c.CallOptions).ListEvaluationJobs)], opts...) it := &EvaluationJobIterator{} req = proto.Clone(req).(*datalabelingpb.ListEvaluationJobsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*datalabelingpb.EvaluationJob, string, error) { @@ -1377,9 +1639,9 @@ type CreateInstructionOperation struct { // CreateInstructionOperation returns a new CreateInstructionOperation from a given name. // The name must be that of a previously created CreateInstructionOperation, possibly from a different process. -func (c *Client) CreateInstructionOperation(name string) *CreateInstructionOperation { +func (c *gRPCClient) CreateInstructionOperation(name string) *CreateInstructionOperation { return &CreateInstructionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1446,9 +1708,9 @@ type ExportDataOperation struct { // ExportDataOperation returns a new ExportDataOperation from a given name. // The name must be that of a previously created ExportDataOperation, possibly from a different process. -func (c *Client) ExportDataOperation(name string) *ExportDataOperation { +func (c *gRPCClient) ExportDataOperation(name string) *ExportDataOperation { return &ExportDataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1515,9 +1777,9 @@ type ImportDataOperation struct { // ImportDataOperation returns a new ImportDataOperation from a given name. // The name must be that of a previously created ImportDataOperation, possibly from a different process. -func (c *Client) ImportDataOperation(name string) *ImportDataOperation { +func (c *gRPCClient) ImportDataOperation(name string) *ImportDataOperation { return &ImportDataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1584,9 +1846,9 @@ type LabelImageOperation struct { // LabelImageOperation returns a new LabelImageOperation from a given name. // The name must be that of a previously created LabelImageOperation, possibly from a different process. -func (c *Client) LabelImageOperation(name string) *LabelImageOperation { +func (c *gRPCClient) LabelImageOperation(name string) *LabelImageOperation { return &LabelImageOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1653,9 +1915,9 @@ type LabelTextOperation struct { // LabelTextOperation returns a new LabelTextOperation from a given name. // The name must be that of a previously created LabelTextOperation, possibly from a different process. -func (c *Client) LabelTextOperation(name string) *LabelTextOperation { +func (c *gRPCClient) LabelTextOperation(name string) *LabelTextOperation { return &LabelTextOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1722,9 +1984,9 @@ type LabelVideoOperation struct { // LabelVideoOperation returns a new LabelVideoOperation from a given name. // The name must be that of a previously created LabelVideoOperation, possibly from a different process. -func (c *Client) LabelVideoOperation(name string) *LabelVideoOperation { +func (c *gRPCClient) LabelVideoOperation(name string) *LabelVideoOperation { return &LabelVideoOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/datalabeling/apiv1beta1/data_labeling_client_example_test.go b/datalabeling/apiv1beta1/data_labeling_client_example_test.go index d751242ff7ea..6132b6bcb22f 100644 --- a/datalabeling/apiv1beta1/data_labeling_client_example_test.go +++ b/datalabeling/apiv1beta1/data_labeling_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateDataset() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.CreateDatasetRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleClient_CreateDataset() { } func ExampleClient_GetDataset() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.GetDatasetRequest{ // TODO: Fill request struct fields. @@ -75,14 +75,12 @@ func ExampleClient_GetDataset() { } func ExampleClient_ListDatasets() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ListDatasetsRequest{ // TODO: Fill request struct fields. @@ -107,6 +105,7 @@ func ExampleClient_DeleteDataset() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.DeleteDatasetRequest{ // TODO: Fill request struct fields. @@ -118,13 +117,12 @@ func ExampleClient_DeleteDataset() { } func ExampleClient_ImportData() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ImportDataRequest{ // TODO: Fill request struct fields. @@ -143,13 +141,12 @@ func ExampleClient_ImportData() { } func ExampleClient_ExportData() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ExportDataRequest{ // TODO: Fill request struct fields. @@ -168,13 +165,12 @@ func ExampleClient_ExportData() { } func ExampleClient_GetDataItem() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.GetDataItemRequest{ // TODO: Fill request struct fields. @@ -188,14 +184,12 @@ func ExampleClient_GetDataItem() { } func ExampleClient_ListDataItems() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ListDataItemsRequest{ // TODO: Fill request struct fields. @@ -215,13 +209,12 @@ func ExampleClient_ListDataItems() { } func ExampleClient_GetAnnotatedDataset() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.GetAnnotatedDatasetRequest{ // TODO: Fill request struct fields. @@ -235,14 +228,12 @@ func ExampleClient_GetAnnotatedDataset() { } func ExampleClient_ListAnnotatedDatasets() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ListAnnotatedDatasetsRequest{ // TODO: Fill request struct fields. @@ -267,6 +258,7 @@ func ExampleClient_DeleteAnnotatedDataset() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.DeleteAnnotatedDatasetRequest{ // TODO: Fill request struct fields. @@ -278,13 +270,12 @@ func ExampleClient_DeleteAnnotatedDataset() { } func ExampleClient_LabelImage() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.LabelImageRequest{ // TODO: Fill request struct fields. @@ -303,13 +294,12 @@ func ExampleClient_LabelImage() { } func ExampleClient_LabelVideo() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.LabelVideoRequest{ // TODO: Fill request struct fields. @@ -328,13 +318,12 @@ func ExampleClient_LabelVideo() { } func ExampleClient_LabelText() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.LabelTextRequest{ // TODO: Fill request struct fields. @@ -353,13 +342,12 @@ func ExampleClient_LabelText() { } func ExampleClient_GetExample() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.GetExampleRequest{ // TODO: Fill request struct fields. @@ -373,14 +361,12 @@ func ExampleClient_GetExample() { } func ExampleClient_ListExamples() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ListExamplesRequest{ // TODO: Fill request struct fields. @@ -400,13 +386,12 @@ func ExampleClient_ListExamples() { } func ExampleClient_CreateAnnotationSpecSet() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.CreateAnnotationSpecSetRequest{ // TODO: Fill request struct fields. @@ -420,13 +405,12 @@ func ExampleClient_CreateAnnotationSpecSet() { } func ExampleClient_GetAnnotationSpecSet() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.GetAnnotationSpecSetRequest{ // TODO: Fill request struct fields. @@ -440,14 +424,12 @@ func ExampleClient_GetAnnotationSpecSet() { } func ExampleClient_ListAnnotationSpecSets() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ListAnnotationSpecSetsRequest{ // TODO: Fill request struct fields. @@ -472,6 +454,7 @@ func ExampleClient_DeleteAnnotationSpecSet() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.DeleteAnnotationSpecSetRequest{ // TODO: Fill request struct fields. @@ -483,13 +466,12 @@ func ExampleClient_DeleteAnnotationSpecSet() { } func ExampleClient_CreateInstruction() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.CreateInstructionRequest{ // TODO: Fill request struct fields. @@ -508,13 +490,12 @@ func ExampleClient_CreateInstruction() { } func ExampleClient_GetInstruction() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.GetInstructionRequest{ // TODO: Fill request struct fields. @@ -528,14 +509,12 @@ func ExampleClient_GetInstruction() { } func ExampleClient_ListInstructions() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ListInstructionsRequest{ // TODO: Fill request struct fields. @@ -560,6 +539,7 @@ func ExampleClient_DeleteInstruction() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.DeleteInstructionRequest{ // TODO: Fill request struct fields. @@ -571,13 +551,12 @@ func ExampleClient_DeleteInstruction() { } func ExampleClient_GetEvaluation() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.GetEvaluationRequest{ // TODO: Fill request struct fields. @@ -591,14 +570,12 @@ func ExampleClient_GetEvaluation() { } func ExampleClient_SearchEvaluations() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.SearchEvaluationsRequest{ // TODO: Fill request struct fields. @@ -618,14 +595,12 @@ func ExampleClient_SearchEvaluations() { } func ExampleClient_SearchExampleComparisons() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.SearchExampleComparisonsRequest{ // TODO: Fill request struct fields. @@ -645,13 +620,12 @@ func ExampleClient_SearchExampleComparisons() { } func ExampleClient_CreateEvaluationJob() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.CreateEvaluationJobRequest{ // TODO: Fill request struct fields. @@ -665,13 +639,12 @@ func ExampleClient_CreateEvaluationJob() { } func ExampleClient_UpdateEvaluationJob() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.UpdateEvaluationJobRequest{ // TODO: Fill request struct fields. @@ -685,13 +658,12 @@ func ExampleClient_UpdateEvaluationJob() { } func ExampleClient_GetEvaluationJob() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.GetEvaluationJobRequest{ // TODO: Fill request struct fields. @@ -710,6 +682,7 @@ func ExampleClient_PauseEvaluationJob() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.PauseEvaluationJobRequest{ // TODO: Fill request struct fields. @@ -726,6 +699,7 @@ func ExampleClient_ResumeEvaluationJob() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ResumeEvaluationJobRequest{ // TODO: Fill request struct fields. @@ -742,6 +716,7 @@ func ExampleClient_DeleteEvaluationJob() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.DeleteEvaluationJobRequest{ // TODO: Fill request struct fields. @@ -753,14 +728,12 @@ func ExampleClient_DeleteEvaluationJob() { } func ExampleClient_ListEvaluationJobs() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ListEvaluationJobsRequest{ // TODO: Fill request struct fields. diff --git a/datalabeling/apiv1beta1/doc.go b/datalabeling/apiv1beta1/doc.go index cb30f0af0ac6..bef90b03e50d 100644 --- a/datalabeling/apiv1beta1/doc.go +++ b/datalabeling/apiv1beta1/doc.go @@ -19,6 +19,8 @@ // // Public API for Google Cloud AI Data Labeling Service. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -28,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package datalabeling // import "cloud.google.com/go/datalabeling/apiv1beta1" import ( @@ -48,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/dataproc/apiv1/autoscaling_policy_client.go b/dataproc/apiv1/autoscaling_policy_client.go index 71972d05f593..d0d2b0db85a8 100644 --- a/dataproc/apiv1/autoscaling_policy_client.go +++ b/dataproc/apiv1/autoscaling_policy_client.go @@ -46,7 +46,7 @@ type AutoscalingPolicyCallOptions struct { DeleteAutoscalingPolicy []gax.CallOption } -func defaultAutoscalingPolicyClientOptions() []option.ClientOption { +func defaultAutoscalingPolicyGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dataproc.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dataproc.mtls.googleapis.com:443"), @@ -101,33 +101,109 @@ func defaultAutoscalingPolicyCallOptions() *AutoscalingPolicyCallOptions { } } +// internalAutoscalingPolicyClient is an interface that defines the methods availaible from Cloud Dataproc API. +type internalAutoscalingPolicyClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateAutoscalingPolicy(context.Context, *dataprocpb.CreateAutoscalingPolicyRequest, ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) + UpdateAutoscalingPolicy(context.Context, *dataprocpb.UpdateAutoscalingPolicyRequest, ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) + GetAutoscalingPolicy(context.Context, *dataprocpb.GetAutoscalingPolicyRequest, ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) + ListAutoscalingPolicies(context.Context, *dataprocpb.ListAutoscalingPoliciesRequest, ...gax.CallOption) *AutoscalingPolicyIterator + DeleteAutoscalingPolicy(context.Context, *dataprocpb.DeleteAutoscalingPolicyRequest, ...gax.CallOption) error +} + // AutoscalingPolicyClient is a client for interacting with Cloud Dataproc API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The API interface for managing autoscaling policies in the +// Dataproc API. type AutoscalingPolicyClient struct { + // The internal transport-dependent client. + internalClient internalAutoscalingPolicyClient + + // The call options for this service. + CallOptions *AutoscalingPolicyCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *AutoscalingPolicyClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *AutoscalingPolicyClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *AutoscalingPolicyClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateAutoscalingPolicy creates new autoscaling policy. +func (c *AutoscalingPolicyClient) CreateAutoscalingPolicy(ctx context.Context, req *dataprocpb.CreateAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { + return c.internalClient.CreateAutoscalingPolicy(ctx, req, opts...) +} + +// UpdateAutoscalingPolicy updates (replaces) autoscaling policy. +// +// Disabled check for update_mask, because all updates will be full +// replacements. +func (c *AutoscalingPolicyClient) UpdateAutoscalingPolicy(ctx context.Context, req *dataprocpb.UpdateAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { + return c.internalClient.UpdateAutoscalingPolicy(ctx, req, opts...) +} + +// GetAutoscalingPolicy retrieves autoscaling policy. +func (c *AutoscalingPolicyClient) GetAutoscalingPolicy(ctx context.Context, req *dataprocpb.GetAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { + return c.internalClient.GetAutoscalingPolicy(ctx, req, opts...) +} + +// ListAutoscalingPolicies lists autoscaling policies in the project. +func (c *AutoscalingPolicyClient) ListAutoscalingPolicies(ctx context.Context, req *dataprocpb.ListAutoscalingPoliciesRequest, opts ...gax.CallOption) *AutoscalingPolicyIterator { + return c.internalClient.ListAutoscalingPolicies(ctx, req, opts...) +} + +// DeleteAutoscalingPolicy deletes an autoscaling policy. It is an error to delete an autoscaling +// policy that is in use by one or more clusters. +func (c *AutoscalingPolicyClient) DeleteAutoscalingPolicy(ctx context.Context, req *dataprocpb.DeleteAutoscalingPolicyRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteAutoscalingPolicy(ctx, req, opts...) +} + +// autoscalingPolicyGRPCClient is a client for interacting with Cloud Dataproc API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type autoscalingPolicyGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing AutoscalingPolicyClient + CallOptions **AutoscalingPolicyCallOptions + // The gRPC API client. autoscalingPolicyClient dataprocpb.AutoscalingPolicyServiceClient - // The call options for this service. - CallOptions *AutoscalingPolicyCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewAutoscalingPolicyClient creates a new autoscaling policy service client. +// NewAutoscalingPolicyClient creates a new autoscaling policy service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The API interface for managing autoscaling policies in the // Dataproc API. func NewAutoscalingPolicyClient(ctx context.Context, opts ...option.ClientOption) (*AutoscalingPolicyClient, error) { - clientOpts := defaultAutoscalingPolicyClientOptions() - + clientOpts := defaultAutoscalingPolicyGRPCClientOptions() if newAutoscalingPolicyClientHook != nil { hookOpts, err := newAutoscalingPolicyClientHook(ctx, clientHookParams{}) if err != nil { @@ -145,42 +221,44 @@ func NewAutoscalingPolicyClient(ctx context.Context, opts ...option.ClientOption if err != nil { return nil, err } - c := &AutoscalingPolicyClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultAutoscalingPolicyCallOptions(), + client := AutoscalingPolicyClient{CallOptions: defaultAutoscalingPolicyCallOptions()} + c := &autoscalingPolicyGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, autoscalingPolicyClient: dataprocpb.NewAutoscalingPolicyServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *AutoscalingPolicyClient) Connection() *grpc.ClientConn { +func (c *autoscalingPolicyGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *AutoscalingPolicyClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *AutoscalingPolicyClient) setGoogleClientInfo(keyval ...string) { +func (c *autoscalingPolicyGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateAutoscalingPolicy creates new autoscaling policy. -func (c *AutoscalingPolicyClient) CreateAutoscalingPolicy(ctx context.Context, req *dataprocpb.CreateAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *autoscalingPolicyGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *autoscalingPolicyGRPCClient) CreateAutoscalingPolicy(ctx context.Context, req *dataprocpb.CreateAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -188,7 +266,7 @@ func (c *AutoscalingPolicyClient) CreateAutoscalingPolicy(ctx context.Context, r } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateAutoscalingPolicy[0:len(c.CallOptions.CreateAutoscalingPolicy):len(c.CallOptions.CreateAutoscalingPolicy)], opts...) + opts = append((*c.CallOptions).CreateAutoscalingPolicy[0:len((*c.CallOptions).CreateAutoscalingPolicy):len((*c.CallOptions).CreateAutoscalingPolicy)], opts...) var resp *dataprocpb.AutoscalingPolicy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -201,11 +279,7 @@ func (c *AutoscalingPolicyClient) CreateAutoscalingPolicy(ctx context.Context, r return resp, nil } -// UpdateAutoscalingPolicy updates (replaces) autoscaling policy. -// -// Disabled check for update_mask, because all updates will be full -// replacements. -func (c *AutoscalingPolicyClient) UpdateAutoscalingPolicy(ctx context.Context, req *dataprocpb.UpdateAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { +func (c *autoscalingPolicyGRPCClient) UpdateAutoscalingPolicy(ctx context.Context, req *dataprocpb.UpdateAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -213,7 +287,7 @@ func (c *AutoscalingPolicyClient) UpdateAutoscalingPolicy(ctx context.Context, r } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "policy.name", url.QueryEscape(req.GetPolicy().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateAutoscalingPolicy[0:len(c.CallOptions.UpdateAutoscalingPolicy):len(c.CallOptions.UpdateAutoscalingPolicy)], opts...) + opts = append((*c.CallOptions).UpdateAutoscalingPolicy[0:len((*c.CallOptions).UpdateAutoscalingPolicy):len((*c.CallOptions).UpdateAutoscalingPolicy)], opts...) var resp *dataprocpb.AutoscalingPolicy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -226,8 +300,7 @@ func (c *AutoscalingPolicyClient) UpdateAutoscalingPolicy(ctx context.Context, r return resp, nil } -// GetAutoscalingPolicy retrieves autoscaling policy. -func (c *AutoscalingPolicyClient) GetAutoscalingPolicy(ctx context.Context, req *dataprocpb.GetAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { +func (c *autoscalingPolicyGRPCClient) GetAutoscalingPolicy(ctx context.Context, req *dataprocpb.GetAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -235,7 +308,7 @@ func (c *AutoscalingPolicyClient) GetAutoscalingPolicy(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetAutoscalingPolicy[0:len(c.CallOptions.GetAutoscalingPolicy):len(c.CallOptions.GetAutoscalingPolicy)], opts...) + opts = append((*c.CallOptions).GetAutoscalingPolicy[0:len((*c.CallOptions).GetAutoscalingPolicy):len((*c.CallOptions).GetAutoscalingPolicy)], opts...) var resp *dataprocpb.AutoscalingPolicy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -248,11 +321,10 @@ func (c *AutoscalingPolicyClient) GetAutoscalingPolicy(ctx context.Context, req return resp, nil } -// ListAutoscalingPolicies lists autoscaling policies in the project. -func (c *AutoscalingPolicyClient) ListAutoscalingPolicies(ctx context.Context, req *dataprocpb.ListAutoscalingPoliciesRequest, opts ...gax.CallOption) *AutoscalingPolicyIterator { +func (c *autoscalingPolicyGRPCClient) ListAutoscalingPolicies(ctx context.Context, req *dataprocpb.ListAutoscalingPoliciesRequest, opts ...gax.CallOption) *AutoscalingPolicyIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAutoscalingPolicies[0:len(c.CallOptions.ListAutoscalingPolicies):len(c.CallOptions.ListAutoscalingPolicies)], opts...) + opts = append((*c.CallOptions).ListAutoscalingPolicies[0:len((*c.CallOptions).ListAutoscalingPolicies):len((*c.CallOptions).ListAutoscalingPolicies)], opts...) it := &AutoscalingPolicyIterator{} req = proto.Clone(req).(*dataprocpb.ListAutoscalingPoliciesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dataprocpb.AutoscalingPolicy, string, error) { @@ -289,9 +361,7 @@ func (c *AutoscalingPolicyClient) ListAutoscalingPolicies(ctx context.Context, r return it } -// DeleteAutoscalingPolicy deletes an autoscaling policy. It is an error to delete an autoscaling -// policy that is in use by one or more clusters. -func (c *AutoscalingPolicyClient) DeleteAutoscalingPolicy(ctx context.Context, req *dataprocpb.DeleteAutoscalingPolicyRequest, opts ...gax.CallOption) error { +func (c *autoscalingPolicyGRPCClient) DeleteAutoscalingPolicy(ctx context.Context, req *dataprocpb.DeleteAutoscalingPolicyRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -299,7 +369,7 @@ func (c *AutoscalingPolicyClient) DeleteAutoscalingPolicy(ctx context.Context, r } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteAutoscalingPolicy[0:len(c.CallOptions.DeleteAutoscalingPolicy):len(c.CallOptions.DeleteAutoscalingPolicy)], opts...) + opts = append((*c.CallOptions).DeleteAutoscalingPolicy[0:len((*c.CallOptions).DeleteAutoscalingPolicy):len((*c.CallOptions).DeleteAutoscalingPolicy)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.autoscalingPolicyClient.DeleteAutoscalingPolicy(ctx, req, settings.GRPC...) diff --git a/dataproc/apiv1/autoscaling_policy_client_example_test.go b/dataproc/apiv1/autoscaling_policy_client_example_test.go index 1fbd06dbf80e..967f7af8992e 100644 --- a/dataproc/apiv1/autoscaling_policy_client_example_test.go +++ b/dataproc/apiv1/autoscaling_policy_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewAutoscalingPolicyClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleAutoscalingPolicyClient_CreateAutoscalingPolicy() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewAutoscalingPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.CreateAutoscalingPolicyRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleAutoscalingPolicyClient_CreateAutoscalingPolicy() { } func ExampleAutoscalingPolicyClient_UpdateAutoscalingPolicy() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewAutoscalingPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.UpdateAutoscalingPolicyRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleAutoscalingPolicyClient_UpdateAutoscalingPolicy() { } func ExampleAutoscalingPolicyClient_GetAutoscalingPolicy() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewAutoscalingPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.GetAutoscalingPolicyRequest{ // TODO: Fill request struct fields. @@ -95,14 +94,12 @@ func ExampleAutoscalingPolicyClient_GetAutoscalingPolicy() { } func ExampleAutoscalingPolicyClient_ListAutoscalingPolicies() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dataproc.NewAutoscalingPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.ListAutoscalingPoliciesRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleAutoscalingPolicyClient_DeleteAutoscalingPolicy() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DeleteAutoscalingPolicyRequest{ // TODO: Fill request struct fields. diff --git a/dataproc/apiv1/cluster_controller_client.go b/dataproc/apiv1/cluster_controller_client.go index b8775d4ebe61..98614ae43125 100644 --- a/dataproc/apiv1/cluster_controller_client.go +++ b/dataproc/apiv1/cluster_controller_client.go @@ -52,7 +52,7 @@ type ClusterControllerCallOptions struct { DiagnoseCluster []gax.CallOption } -func defaultClusterControllerClientOptions() []option.ClientOption { +func defaultClusterControllerGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dataproc.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dataproc.mtls.googleapis.com:443"), @@ -141,38 +141,187 @@ func defaultClusterControllerCallOptions() *ClusterControllerCallOptions { } } +// internalClusterControllerClient is an interface that defines the methods availaible from Cloud Dataproc API. +type internalClusterControllerClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateCluster(context.Context, *dataprocpb.CreateClusterRequest, ...gax.CallOption) (*CreateClusterOperation, error) + CreateClusterOperation(name string) *CreateClusterOperation + UpdateCluster(context.Context, *dataprocpb.UpdateClusterRequest, ...gax.CallOption) (*UpdateClusterOperation, error) + UpdateClusterOperation(name string) *UpdateClusterOperation + StopCluster(context.Context, *dataprocpb.StopClusterRequest, ...gax.CallOption) (*StopClusterOperation, error) + StopClusterOperation(name string) *StopClusterOperation + StartCluster(context.Context, *dataprocpb.StartClusterRequest, ...gax.CallOption) (*StartClusterOperation, error) + StartClusterOperation(name string) *StartClusterOperation + DeleteCluster(context.Context, *dataprocpb.DeleteClusterRequest, ...gax.CallOption) (*DeleteClusterOperation, error) + DeleteClusterOperation(name string) *DeleteClusterOperation + GetCluster(context.Context, *dataprocpb.GetClusterRequest, ...gax.CallOption) (*dataprocpb.Cluster, error) + ListClusters(context.Context, *dataprocpb.ListClustersRequest, ...gax.CallOption) *ClusterIterator + DiagnoseCluster(context.Context, *dataprocpb.DiagnoseClusterRequest, ...gax.CallOption) (*DiagnoseClusterOperation, error) + DiagnoseClusterOperation(name string) *DiagnoseClusterOperation +} + // ClusterControllerClient is a client for interacting with Cloud Dataproc API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The ClusterControllerService provides methods to manage clusters +// of Compute Engine instances. type ClusterControllerClient struct { + // The internal transport-dependent client. + internalClient internalClusterControllerClient + + // The call options for this service. + CallOptions *ClusterControllerCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ClusterControllerClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ClusterControllerClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ClusterControllerClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateCluster creates a cluster in a project. The returned +// Operation.metadata will be +// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata). +func (c *ClusterControllerClient) CreateCluster(ctx context.Context, req *dataprocpb.CreateClusterRequest, opts ...gax.CallOption) (*CreateClusterOperation, error) { + return c.internalClient.CreateCluster(ctx, req, opts...) +} + +// CreateClusterOperation returns a new CreateClusterOperation from a given name. +// The name must be that of a previously created CreateClusterOperation, possibly from a different process. +func (c *ClusterControllerClient) CreateClusterOperation(name string) *CreateClusterOperation { + return c.internalClient.CreateClusterOperation(name) +} + +// UpdateCluster updates a cluster in a project. The returned +// Operation.metadata will be +// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata). +func (c *ClusterControllerClient) UpdateCluster(ctx context.Context, req *dataprocpb.UpdateClusterRequest, opts ...gax.CallOption) (*UpdateClusterOperation, error) { + return c.internalClient.UpdateCluster(ctx, req, opts...) +} + +// UpdateClusterOperation returns a new UpdateClusterOperation from a given name. +// The name must be that of a previously created UpdateClusterOperation, possibly from a different process. +func (c *ClusterControllerClient) UpdateClusterOperation(name string) *UpdateClusterOperation { + return c.internalClient.UpdateClusterOperation(name) +} + +// StopCluster stops a cluster in a project. +func (c *ClusterControllerClient) StopCluster(ctx context.Context, req *dataprocpb.StopClusterRequest, opts ...gax.CallOption) (*StopClusterOperation, error) { + return c.internalClient.StopCluster(ctx, req, opts...) +} + +// StopClusterOperation returns a new StopClusterOperation from a given name. +// The name must be that of a previously created StopClusterOperation, possibly from a different process. +func (c *ClusterControllerClient) StopClusterOperation(name string) *StopClusterOperation { + return c.internalClient.StopClusterOperation(name) +} + +// StartCluster starts a cluster in a project. +func (c *ClusterControllerClient) StartCluster(ctx context.Context, req *dataprocpb.StartClusterRequest, opts ...gax.CallOption) (*StartClusterOperation, error) { + return c.internalClient.StartCluster(ctx, req, opts...) +} + +// StartClusterOperation returns a new StartClusterOperation from a given name. +// The name must be that of a previously created StartClusterOperation, possibly from a different process. +func (c *ClusterControllerClient) StartClusterOperation(name string) *StartClusterOperation { + return c.internalClient.StartClusterOperation(name) +} + +// DeleteCluster deletes a cluster in a project. The returned +// Operation.metadata will be +// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata). +func (c *ClusterControllerClient) DeleteCluster(ctx context.Context, req *dataprocpb.DeleteClusterRequest, opts ...gax.CallOption) (*DeleteClusterOperation, error) { + return c.internalClient.DeleteCluster(ctx, req, opts...) +} + +// DeleteClusterOperation returns a new DeleteClusterOperation from a given name. +// The name must be that of a previously created DeleteClusterOperation, possibly from a different process. +func (c *ClusterControllerClient) DeleteClusterOperation(name string) *DeleteClusterOperation { + return c.internalClient.DeleteClusterOperation(name) +} + +// GetCluster gets the resource representation for a cluster in a project. +func (c *ClusterControllerClient) GetCluster(ctx context.Context, req *dataprocpb.GetClusterRequest, opts ...gax.CallOption) (*dataprocpb.Cluster, error) { + return c.internalClient.GetCluster(ctx, req, opts...) +} + +// ListClusters lists all regions/{region}/clusters in a project alphabetically. +func (c *ClusterControllerClient) ListClusters(ctx context.Context, req *dataprocpb.ListClustersRequest, opts ...gax.CallOption) *ClusterIterator { + return c.internalClient.ListClusters(ctx, req, opts...) +} + +// DiagnoseCluster gets cluster diagnostic information. The returned +// Operation.metadata will be +// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata). +// After the operation completes, +// Operation.response +// contains +// DiagnoseClusterResults (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#diagnoseclusterresults). +func (c *ClusterControllerClient) DiagnoseCluster(ctx context.Context, req *dataprocpb.DiagnoseClusterRequest, opts ...gax.CallOption) (*DiagnoseClusterOperation, error) { + return c.internalClient.DiagnoseCluster(ctx, req, opts...) +} + +// DiagnoseClusterOperation returns a new DiagnoseClusterOperation from a given name. +// The name must be that of a previously created DiagnoseClusterOperation, possibly from a different process. +func (c *ClusterControllerClient) DiagnoseClusterOperation(name string) *DiagnoseClusterOperation { + return c.internalClient.DiagnoseClusterOperation(name) +} + +// clusterControllerGRPCClient is a client for interacting with Cloud Dataproc API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type clusterControllerGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ClusterControllerClient + CallOptions **ClusterControllerCallOptions + // The gRPC API client. clusterControllerClient dataprocpb.ClusterControllerClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *ClusterControllerCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClusterControllerClient creates a new cluster controller client. +// NewClusterControllerClient creates a new cluster controller client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The ClusterControllerService provides methods to manage clusters // of Compute Engine instances. func NewClusterControllerClient(ctx context.Context, opts ...option.ClientOption) (*ClusterControllerClient, error) { - clientOpts := defaultClusterControllerClientOptions() - + clientOpts := defaultClusterControllerGRPCClientOptions() if newClusterControllerClientHook != nil { hookOpts, err := newClusterControllerClientHook(ctx, clientHookParams{}) if err != nil { @@ -190,16 +339,19 @@ func NewClusterControllerClient(ctx context.Context, opts ...option.ClientOption if err != nil { return nil, err } - c := &ClusterControllerClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultClusterControllerCallOptions(), + client := ClusterControllerClient{CallOptions: defaultClusterControllerCallOptions()} + c := &clusterControllerGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, clusterControllerClient: dataprocpb.NewClusterControllerClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -209,35 +361,33 @@ func NewClusterControllerClient(ctx context.Context, opts ...option.ClientOption // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ClusterControllerClient) Connection() *grpc.ClientConn { +func (c *clusterControllerGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ClusterControllerClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ClusterControllerClient) setGoogleClientInfo(keyval ...string) { +func (c *clusterControllerGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateCluster creates a cluster in a project. The returned -// Operation.metadata will be -// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata). -func (c *ClusterControllerClient) CreateCluster(ctx context.Context, req *dataprocpb.CreateClusterRequest, opts ...gax.CallOption) (*CreateClusterOperation, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *clusterControllerGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *clusterControllerGRPCClient) CreateCluster(ctx context.Context, req *dataprocpb.CreateClusterRequest, opts ...gax.CallOption) (*CreateClusterOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -245,7 +395,7 @@ func (c *ClusterControllerClient) CreateCluster(ctx context.Context, req *datapr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCluster[0:len(c.CallOptions.CreateCluster):len(c.CallOptions.CreateCluster)], opts...) + opts = append((*c.CallOptions).CreateCluster[0:len((*c.CallOptions).CreateCluster):len((*c.CallOptions).CreateCluster)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -256,14 +406,11 @@ func (c *ClusterControllerClient) CreateCluster(ctx context.Context, req *datapr return nil, err } return &CreateClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateCluster updates a cluster in a project. The returned -// Operation.metadata will be -// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata). -func (c *ClusterControllerClient) UpdateCluster(ctx context.Context, req *dataprocpb.UpdateClusterRequest, opts ...gax.CallOption) (*UpdateClusterOperation, error) { +func (c *clusterControllerGRPCClient) UpdateCluster(ctx context.Context, req *dataprocpb.UpdateClusterRequest, opts ...gax.CallOption) (*UpdateClusterOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -271,7 +418,7 @@ func (c *ClusterControllerClient) UpdateCluster(ctx context.Context, req *datapr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "cluster_name", url.QueryEscape(req.GetClusterName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCluster[0:len(c.CallOptions.UpdateCluster):len(c.CallOptions.UpdateCluster)], opts...) + opts = append((*c.CallOptions).UpdateCluster[0:len((*c.CallOptions).UpdateCluster):len((*c.CallOptions).UpdateCluster)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -282,15 +429,14 @@ func (c *ClusterControllerClient) UpdateCluster(ctx context.Context, req *datapr return nil, err } return &UpdateClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// StopCluster stops a cluster in a project. -func (c *ClusterControllerClient) StopCluster(ctx context.Context, req *dataprocpb.StopClusterRequest, opts ...gax.CallOption) (*StopClusterOperation, error) { +func (c *clusterControllerGRPCClient) StopCluster(ctx context.Context, req *dataprocpb.StopClusterRequest, opts ...gax.CallOption) (*StopClusterOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "cluster_name", url.QueryEscape(req.GetClusterName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.StopCluster[0:len(c.CallOptions.StopCluster):len(c.CallOptions.StopCluster)], opts...) + opts = append((*c.CallOptions).StopCluster[0:len((*c.CallOptions).StopCluster):len((*c.CallOptions).StopCluster)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -301,15 +447,14 @@ func (c *ClusterControllerClient) StopCluster(ctx context.Context, req *dataproc return nil, err } return &StopClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// StartCluster starts a cluster in a project. -func (c *ClusterControllerClient) StartCluster(ctx context.Context, req *dataprocpb.StartClusterRequest, opts ...gax.CallOption) (*StartClusterOperation, error) { +func (c *clusterControllerGRPCClient) StartCluster(ctx context.Context, req *dataprocpb.StartClusterRequest, opts ...gax.CallOption) (*StartClusterOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "cluster_name", url.QueryEscape(req.GetClusterName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.StartCluster[0:len(c.CallOptions.StartCluster):len(c.CallOptions.StartCluster)], opts...) + opts = append((*c.CallOptions).StartCluster[0:len((*c.CallOptions).StartCluster):len((*c.CallOptions).StartCluster)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -320,14 +465,11 @@ func (c *ClusterControllerClient) StartCluster(ctx context.Context, req *datapro return nil, err } return &StartClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteCluster deletes a cluster in a project. The returned -// Operation.metadata will be -// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata). -func (c *ClusterControllerClient) DeleteCluster(ctx context.Context, req *dataprocpb.DeleteClusterRequest, opts ...gax.CallOption) (*DeleteClusterOperation, error) { +func (c *clusterControllerGRPCClient) DeleteCluster(ctx context.Context, req *dataprocpb.DeleteClusterRequest, opts ...gax.CallOption) (*DeleteClusterOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -335,7 +477,7 @@ func (c *ClusterControllerClient) DeleteCluster(ctx context.Context, req *datapr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "cluster_name", url.QueryEscape(req.GetClusterName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteCluster[0:len(c.CallOptions.DeleteCluster):len(c.CallOptions.DeleteCluster)], opts...) + opts = append((*c.CallOptions).DeleteCluster[0:len((*c.CallOptions).DeleteCluster):len((*c.CallOptions).DeleteCluster)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -346,12 +488,11 @@ func (c *ClusterControllerClient) DeleteCluster(ctx context.Context, req *datapr return nil, err } return &DeleteClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetCluster gets the resource representation for a cluster in a project. -func (c *ClusterControllerClient) GetCluster(ctx context.Context, req *dataprocpb.GetClusterRequest, opts ...gax.CallOption) (*dataprocpb.Cluster, error) { +func (c *clusterControllerGRPCClient) GetCluster(ctx context.Context, req *dataprocpb.GetClusterRequest, opts ...gax.CallOption) (*dataprocpb.Cluster, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -359,7 +500,7 @@ func (c *ClusterControllerClient) GetCluster(ctx context.Context, req *dataprocp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "cluster_name", url.QueryEscape(req.GetClusterName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCluster[0:len(c.CallOptions.GetCluster):len(c.CallOptions.GetCluster)], opts...) + opts = append((*c.CallOptions).GetCluster[0:len((*c.CallOptions).GetCluster):len((*c.CallOptions).GetCluster)], opts...) var resp *dataprocpb.Cluster err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -372,11 +513,10 @@ func (c *ClusterControllerClient) GetCluster(ctx context.Context, req *dataprocp return resp, nil } -// ListClusters lists all regions/{region}/clusters in a project alphabetically. -func (c *ClusterControllerClient) ListClusters(ctx context.Context, req *dataprocpb.ListClustersRequest, opts ...gax.CallOption) *ClusterIterator { +func (c *clusterControllerGRPCClient) ListClusters(ctx context.Context, req *dataprocpb.ListClustersRequest, opts ...gax.CallOption) *ClusterIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListClusters[0:len(c.CallOptions.ListClusters):len(c.CallOptions.ListClusters)], opts...) + opts = append((*c.CallOptions).ListClusters[0:len((*c.CallOptions).ListClusters):len((*c.CallOptions).ListClusters)], opts...) it := &ClusterIterator{} req = proto.Clone(req).(*dataprocpb.ListClustersRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dataprocpb.Cluster, string, error) { @@ -413,14 +553,7 @@ func (c *ClusterControllerClient) ListClusters(ctx context.Context, req *datapro return it } -// DiagnoseCluster gets cluster diagnostic information. The returned -// Operation.metadata will be -// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#clusteroperationmetadata). -// After the operation completes, -// Operation.response -// contains -// DiagnoseClusterResults (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#diagnoseclusterresults). -func (c *ClusterControllerClient) DiagnoseCluster(ctx context.Context, req *dataprocpb.DiagnoseClusterRequest, opts ...gax.CallOption) (*DiagnoseClusterOperation, error) { +func (c *clusterControllerGRPCClient) DiagnoseCluster(ctx context.Context, req *dataprocpb.DiagnoseClusterRequest, opts ...gax.CallOption) (*DiagnoseClusterOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -428,7 +561,7 @@ func (c *ClusterControllerClient) DiagnoseCluster(ctx context.Context, req *data } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "cluster_name", url.QueryEscape(req.GetClusterName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DiagnoseCluster[0:len(c.CallOptions.DiagnoseCluster):len(c.CallOptions.DiagnoseCluster)], opts...) + opts = append((*c.CallOptions).DiagnoseCluster[0:len((*c.CallOptions).DiagnoseCluster):len((*c.CallOptions).DiagnoseCluster)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -439,7 +572,7 @@ func (c *ClusterControllerClient) DiagnoseCluster(ctx context.Context, req *data return nil, err } return &DiagnoseClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -450,9 +583,9 @@ type CreateClusterOperation struct { // CreateClusterOperation returns a new CreateClusterOperation from a given name. // The name must be that of a previously created CreateClusterOperation, possibly from a different process. -func (c *ClusterControllerClient) CreateClusterOperation(name string) *CreateClusterOperation { +func (c *clusterControllerGRPCClient) CreateClusterOperation(name string) *CreateClusterOperation { return &CreateClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -519,9 +652,9 @@ type DeleteClusterOperation struct { // DeleteClusterOperation returns a new DeleteClusterOperation from a given name. // The name must be that of a previously created DeleteClusterOperation, possibly from a different process. -func (c *ClusterControllerClient) DeleteClusterOperation(name string) *DeleteClusterOperation { +func (c *clusterControllerGRPCClient) DeleteClusterOperation(name string) *DeleteClusterOperation { return &DeleteClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -577,9 +710,9 @@ type DiagnoseClusterOperation struct { // DiagnoseClusterOperation returns a new DiagnoseClusterOperation from a given name. // The name must be that of a previously created DiagnoseClusterOperation, possibly from a different process. -func (c *ClusterControllerClient) DiagnoseClusterOperation(name string) *DiagnoseClusterOperation { +func (c *clusterControllerGRPCClient) DiagnoseClusterOperation(name string) *DiagnoseClusterOperation { return &DiagnoseClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -646,9 +779,9 @@ type StartClusterOperation struct { // StartClusterOperation returns a new StartClusterOperation from a given name. // The name must be that of a previously created StartClusterOperation, possibly from a different process. -func (c *ClusterControllerClient) StartClusterOperation(name string) *StartClusterOperation { +func (c *clusterControllerGRPCClient) StartClusterOperation(name string) *StartClusterOperation { return &StartClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -715,9 +848,9 @@ type StopClusterOperation struct { // StopClusterOperation returns a new StopClusterOperation from a given name. // The name must be that of a previously created StopClusterOperation, possibly from a different process. -func (c *ClusterControllerClient) StopClusterOperation(name string) *StopClusterOperation { +func (c *clusterControllerGRPCClient) StopClusterOperation(name string) *StopClusterOperation { return &StopClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -784,9 +917,9 @@ type UpdateClusterOperation struct { // UpdateClusterOperation returns a new UpdateClusterOperation from a given name. // The name must be that of a previously created UpdateClusterOperation, possibly from a different process. -func (c *ClusterControllerClient) UpdateClusterOperation(name string) *UpdateClusterOperation { +func (c *clusterControllerGRPCClient) UpdateClusterOperation(name string) *UpdateClusterOperation { return &UpdateClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dataproc/apiv1/cluster_controller_client_example_test.go b/dataproc/apiv1/cluster_controller_client_example_test.go index 690c574ac6d7..2ffbfa3601fe 100644 --- a/dataproc/apiv1/cluster_controller_client_example_test.go +++ b/dataproc/apiv1/cluster_controller_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClusterControllerClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClusterControllerClient_CreateCluster() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.CreateClusterRequest{ // TODO: Fill request struct fields. @@ -60,13 +61,12 @@ func ExampleClusterControllerClient_CreateCluster() { } func ExampleClusterControllerClient_UpdateCluster() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.UpdateClusterRequest{ // TODO: Fill request struct fields. @@ -85,13 +85,12 @@ func ExampleClusterControllerClient_UpdateCluster() { } func ExampleClusterControllerClient_StopCluster() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.StopClusterRequest{ // TODO: Fill request struct fields. @@ -110,13 +109,12 @@ func ExampleClusterControllerClient_StopCluster() { } func ExampleClusterControllerClient_StartCluster() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.StartClusterRequest{ // TODO: Fill request struct fields. @@ -135,13 +133,12 @@ func ExampleClusterControllerClient_StartCluster() { } func ExampleClusterControllerClient_DeleteCluster() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DeleteClusterRequest{ // TODO: Fill request struct fields. @@ -158,13 +155,12 @@ func ExampleClusterControllerClient_DeleteCluster() { } func ExampleClusterControllerClient_GetCluster() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.GetClusterRequest{ // TODO: Fill request struct fields. @@ -178,14 +174,12 @@ func ExampleClusterControllerClient_GetCluster() { } func ExampleClusterControllerClient_ListClusters() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.ListClustersRequest{ // TODO: Fill request struct fields. @@ -205,13 +199,12 @@ func ExampleClusterControllerClient_ListClusters() { } func ExampleClusterControllerClient_DiagnoseCluster() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DiagnoseClusterRequest{ // TODO: Fill request struct fields. diff --git a/dataproc/apiv1/doc.go b/dataproc/apiv1/doc.go index c7ca6e383dba..80882089b771 100644 --- a/dataproc/apiv1/doc.go +++ b/dataproc/apiv1/doc.go @@ -28,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package dataproc // import "cloud.google.com/go/dataproc/apiv1" import ( @@ -48,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/dataproc/apiv1/job_controller_client.go b/dataproc/apiv1/job_controller_client.go index 20060f40c4e0..57ed726c00a2 100644 --- a/dataproc/apiv1/job_controller_client.go +++ b/dataproc/apiv1/job_controller_client.go @@ -51,7 +51,7 @@ type JobControllerCallOptions struct { DeleteJob []gax.CallOption } -func defaultJobControllerClientOptions() []option.ClientOption { +func defaultJobControllerGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dataproc.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dataproc.mtls.googleapis.com:443"), @@ -151,37 +151,137 @@ func defaultJobControllerCallOptions() *JobControllerCallOptions { } } +// internalJobControllerClient is an interface that defines the methods availaible from Cloud Dataproc API. +type internalJobControllerClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + SubmitJob(context.Context, *dataprocpb.SubmitJobRequest, ...gax.CallOption) (*dataprocpb.Job, error) + SubmitJobAsOperation(context.Context, *dataprocpb.SubmitJobRequest, ...gax.CallOption) (*SubmitJobAsOperationOperation, error) + SubmitJobAsOperationOperation(name string) *SubmitJobAsOperationOperation + GetJob(context.Context, *dataprocpb.GetJobRequest, ...gax.CallOption) (*dataprocpb.Job, error) + ListJobs(context.Context, *dataprocpb.ListJobsRequest, ...gax.CallOption) *JobIterator + UpdateJob(context.Context, *dataprocpb.UpdateJobRequest, ...gax.CallOption) (*dataprocpb.Job, error) + CancelJob(context.Context, *dataprocpb.CancelJobRequest, ...gax.CallOption) (*dataprocpb.Job, error) + DeleteJob(context.Context, *dataprocpb.DeleteJobRequest, ...gax.CallOption) error +} + // JobControllerClient is a client for interacting with Cloud Dataproc API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The JobController provides methods to manage jobs. type JobControllerClient struct { + // The internal transport-dependent client. + internalClient internalJobControllerClient + + // The call options for this service. + CallOptions *JobControllerCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *JobControllerClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *JobControllerClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *JobControllerClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// SubmitJob submits a job to a cluster. +func (c *JobControllerClient) SubmitJob(ctx context.Context, req *dataprocpb.SubmitJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { + return c.internalClient.SubmitJob(ctx, req, opts...) +} + +// SubmitJobAsOperation submits job to a cluster. +func (c *JobControllerClient) SubmitJobAsOperation(ctx context.Context, req *dataprocpb.SubmitJobRequest, opts ...gax.CallOption) (*SubmitJobAsOperationOperation, error) { + return c.internalClient.SubmitJobAsOperation(ctx, req, opts...) +} + +// SubmitJobAsOperationOperation returns a new SubmitJobAsOperationOperation from a given name. +// The name must be that of a previously created SubmitJobAsOperationOperation, possibly from a different process. +func (c *JobControllerClient) SubmitJobAsOperationOperation(name string) *SubmitJobAsOperationOperation { + return c.internalClient.SubmitJobAsOperationOperation(name) +} + +// GetJob gets the resource representation for a job in a project. +func (c *JobControllerClient) GetJob(ctx context.Context, req *dataprocpb.GetJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { + return c.internalClient.GetJob(ctx, req, opts...) +} + +// ListJobs lists regions/{region}/jobs in a project. +func (c *JobControllerClient) ListJobs(ctx context.Context, req *dataprocpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { + return c.internalClient.ListJobs(ctx, req, opts...) +} + +// UpdateJob updates a job in a project. +func (c *JobControllerClient) UpdateJob(ctx context.Context, req *dataprocpb.UpdateJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { + return c.internalClient.UpdateJob(ctx, req, opts...) +} + +// CancelJob starts a job cancellation request. To access the job resource +// after cancellation, call +// regions/{region}/jobs.list (at https://cloud.google.com/dataproc/docs/reference/rest/v1/projects.regions.jobs/list) +// or +// regions/{region}/jobs.get (at https://cloud.google.com/dataproc/docs/reference/rest/v1/projects.regions.jobs/get). +func (c *JobControllerClient) CancelJob(ctx context.Context, req *dataprocpb.CancelJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { + return c.internalClient.CancelJob(ctx, req, opts...) +} + +// DeleteJob deletes the job from the project. If the job is active, the delete fails, +// and the response returns FAILED_PRECONDITION. +func (c *JobControllerClient) DeleteJob(ctx context.Context, req *dataprocpb.DeleteJobRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteJob(ctx, req, opts...) +} + +// jobControllerGRPCClient is a client for interacting with Cloud Dataproc API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type jobControllerGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing JobControllerClient + CallOptions **JobControllerCallOptions + // The gRPC API client. jobControllerClient dataprocpb.JobControllerClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *JobControllerCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewJobControllerClient creates a new job controller client. +// NewJobControllerClient creates a new job controller client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The JobController provides methods to manage jobs. func NewJobControllerClient(ctx context.Context, opts ...option.ClientOption) (*JobControllerClient, error) { - clientOpts := defaultJobControllerClientOptions() - + clientOpts := defaultJobControllerGRPCClientOptions() if newJobControllerClientHook != nil { hookOpts, err := newJobControllerClientHook(ctx, clientHookParams{}) if err != nil { @@ -199,16 +299,19 @@ func NewJobControllerClient(ctx context.Context, opts ...option.ClientOption) (* if err != nil { return nil, err } - c := &JobControllerClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultJobControllerCallOptions(), + client := JobControllerClient{CallOptions: defaultJobControllerCallOptions()} + c := &jobControllerGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, jobControllerClient: dataprocpb.NewJobControllerClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -218,33 +321,33 @@ func NewJobControllerClient(ctx context.Context, opts ...option.ClientOption) (* // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *JobControllerClient) Connection() *grpc.ClientConn { +func (c *jobControllerGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *JobControllerClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *JobControllerClient) setGoogleClientInfo(keyval ...string) { +func (c *jobControllerGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// SubmitJob submits a job to a cluster. -func (c *JobControllerClient) SubmitJob(ctx context.Context, req *dataprocpb.SubmitJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *jobControllerGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *jobControllerGRPCClient) SubmitJob(ctx context.Context, req *dataprocpb.SubmitJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 900000*time.Millisecond) defer cancel() @@ -252,7 +355,7 @@ func (c *JobControllerClient) SubmitJob(ctx context.Context, req *dataprocpb.Sub } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SubmitJob[0:len(c.CallOptions.SubmitJob):len(c.CallOptions.SubmitJob)], opts...) + opts = append((*c.CallOptions).SubmitJob[0:len((*c.CallOptions).SubmitJob):len((*c.CallOptions).SubmitJob)], opts...) var resp *dataprocpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -265,8 +368,7 @@ func (c *JobControllerClient) SubmitJob(ctx context.Context, req *dataprocpb.Sub return resp, nil } -// SubmitJobAsOperation submits job to a cluster. -func (c *JobControllerClient) SubmitJobAsOperation(ctx context.Context, req *dataprocpb.SubmitJobRequest, opts ...gax.CallOption) (*SubmitJobAsOperationOperation, error) { +func (c *jobControllerGRPCClient) SubmitJobAsOperation(ctx context.Context, req *dataprocpb.SubmitJobRequest, opts ...gax.CallOption) (*SubmitJobAsOperationOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 900000*time.Millisecond) defer cancel() @@ -274,7 +376,7 @@ func (c *JobControllerClient) SubmitJobAsOperation(ctx context.Context, req *dat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SubmitJobAsOperation[0:len(c.CallOptions.SubmitJobAsOperation):len(c.CallOptions.SubmitJobAsOperation)], opts...) + opts = append((*c.CallOptions).SubmitJobAsOperation[0:len((*c.CallOptions).SubmitJobAsOperation):len((*c.CallOptions).SubmitJobAsOperation)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -285,12 +387,11 @@ func (c *JobControllerClient) SubmitJobAsOperation(ctx context.Context, req *dat return nil, err } return &SubmitJobAsOperationOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetJob gets the resource representation for a job in a project. -func (c *JobControllerClient) GetJob(ctx context.Context, req *dataprocpb.GetJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { +func (c *jobControllerGRPCClient) GetJob(ctx context.Context, req *dataprocpb.GetJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 900000*time.Millisecond) defer cancel() @@ -298,7 +399,7 @@ func (c *JobControllerClient) GetJob(ctx context.Context, req *dataprocpb.GetJob } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "job_id", url.QueryEscape(req.GetJobId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetJob[0:len(c.CallOptions.GetJob):len(c.CallOptions.GetJob)], opts...) + opts = append((*c.CallOptions).GetJob[0:len((*c.CallOptions).GetJob):len((*c.CallOptions).GetJob)], opts...) var resp *dataprocpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -311,11 +412,10 @@ func (c *JobControllerClient) GetJob(ctx context.Context, req *dataprocpb.GetJob return resp, nil } -// ListJobs lists regions/{region}/jobs in a project. -func (c *JobControllerClient) ListJobs(ctx context.Context, req *dataprocpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { +func (c *jobControllerGRPCClient) ListJobs(ctx context.Context, req *dataprocpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListJobs[0:len(c.CallOptions.ListJobs):len(c.CallOptions.ListJobs)], opts...) + opts = append((*c.CallOptions).ListJobs[0:len((*c.CallOptions).ListJobs):len((*c.CallOptions).ListJobs)], opts...) it := &JobIterator{} req = proto.Clone(req).(*dataprocpb.ListJobsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dataprocpb.Job, string, error) { @@ -352,8 +452,7 @@ func (c *JobControllerClient) ListJobs(ctx context.Context, req *dataprocpb.List return it } -// UpdateJob updates a job in a project. -func (c *JobControllerClient) UpdateJob(ctx context.Context, req *dataprocpb.UpdateJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { +func (c *jobControllerGRPCClient) UpdateJob(ctx context.Context, req *dataprocpb.UpdateJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 900000*time.Millisecond) defer cancel() @@ -361,7 +460,7 @@ func (c *JobControllerClient) UpdateJob(ctx context.Context, req *dataprocpb.Upd } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "job_id", url.QueryEscape(req.GetJobId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateJob[0:len(c.CallOptions.UpdateJob):len(c.CallOptions.UpdateJob)], opts...) + opts = append((*c.CallOptions).UpdateJob[0:len((*c.CallOptions).UpdateJob):len((*c.CallOptions).UpdateJob)], opts...) var resp *dataprocpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -374,12 +473,7 @@ func (c *JobControllerClient) UpdateJob(ctx context.Context, req *dataprocpb.Upd return resp, nil } -// CancelJob starts a job cancellation request. To access the job resource -// after cancellation, call -// regions/{region}/jobs.list (at https://cloud.google.com/dataproc/docs/reference/rest/v1/projects.regions.jobs/list) -// or -// regions/{region}/jobs.get (at https://cloud.google.com/dataproc/docs/reference/rest/v1/projects.regions.jobs/get). -func (c *JobControllerClient) CancelJob(ctx context.Context, req *dataprocpb.CancelJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { +func (c *jobControllerGRPCClient) CancelJob(ctx context.Context, req *dataprocpb.CancelJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 900000*time.Millisecond) defer cancel() @@ -387,7 +481,7 @@ func (c *JobControllerClient) CancelJob(ctx context.Context, req *dataprocpb.Can } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "job_id", url.QueryEscape(req.GetJobId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CancelJob[0:len(c.CallOptions.CancelJob):len(c.CallOptions.CancelJob)], opts...) + opts = append((*c.CallOptions).CancelJob[0:len((*c.CallOptions).CancelJob):len((*c.CallOptions).CancelJob)], opts...) var resp *dataprocpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -400,9 +494,7 @@ func (c *JobControllerClient) CancelJob(ctx context.Context, req *dataprocpb.Can return resp, nil } -// DeleteJob deletes the job from the project. If the job is active, the delete fails, -// and the response returns FAILED_PRECONDITION. -func (c *JobControllerClient) DeleteJob(ctx context.Context, req *dataprocpb.DeleteJobRequest, opts ...gax.CallOption) error { +func (c *jobControllerGRPCClient) DeleteJob(ctx context.Context, req *dataprocpb.DeleteJobRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 900000*time.Millisecond) defer cancel() @@ -410,7 +502,7 @@ func (c *JobControllerClient) DeleteJob(ctx context.Context, req *dataprocpb.Del } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "job_id", url.QueryEscape(req.GetJobId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteJob[0:len(c.CallOptions.DeleteJob):len(c.CallOptions.DeleteJob)], opts...) + opts = append((*c.CallOptions).DeleteJob[0:len((*c.CallOptions).DeleteJob):len((*c.CallOptions).DeleteJob)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.jobControllerClient.DeleteJob(ctx, req, settings.GRPC...) @@ -426,9 +518,9 @@ type SubmitJobAsOperationOperation struct { // SubmitJobAsOperationOperation returns a new SubmitJobAsOperationOperation from a given name. // The name must be that of a previously created SubmitJobAsOperationOperation, possibly from a different process. -func (c *JobControllerClient) SubmitJobAsOperationOperation(name string) *SubmitJobAsOperationOperation { +func (c *jobControllerGRPCClient) SubmitJobAsOperationOperation(name string) *SubmitJobAsOperationOperation { return &SubmitJobAsOperationOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dataproc/apiv1/job_controller_client_example_test.go b/dataproc/apiv1/job_controller_client_example_test.go index b3eba96f963a..73b94a04e212 100644 --- a/dataproc/apiv1/job_controller_client_example_test.go +++ b/dataproc/apiv1/job_controller_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewJobControllerClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleJobControllerClient_SubmitJob() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.SubmitJobRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleJobControllerClient_SubmitJob() { } func ExampleJobControllerClient_SubmitJobAsOperation() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.SubmitJobRequest{ // TODO: Fill request struct fields. @@ -80,13 +80,12 @@ func ExampleJobControllerClient_SubmitJobAsOperation() { } func ExampleJobControllerClient_GetJob() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.GetJobRequest{ // TODO: Fill request struct fields. @@ -100,14 +99,12 @@ func ExampleJobControllerClient_GetJob() { } func ExampleJobControllerClient_ListJobs() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.ListJobsRequest{ // TODO: Fill request struct fields. @@ -127,13 +124,12 @@ func ExampleJobControllerClient_ListJobs() { } func ExampleJobControllerClient_UpdateJob() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.UpdateJobRequest{ // TODO: Fill request struct fields. @@ -147,13 +143,12 @@ func ExampleJobControllerClient_UpdateJob() { } func ExampleJobControllerClient_CancelJob() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.CancelJobRequest{ // TODO: Fill request struct fields. @@ -172,6 +167,7 @@ func ExampleJobControllerClient_DeleteJob() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DeleteJobRequest{ // TODO: Fill request struct fields. diff --git a/dataproc/apiv1/workflow_template_client.go b/dataproc/apiv1/workflow_template_client.go index ce0c3eedbd89..c56e3659221f 100644 --- a/dataproc/apiv1/workflow_template_client.go +++ b/dataproc/apiv1/workflow_template_client.go @@ -51,7 +51,7 @@ type WorkflowTemplateCallOptions struct { DeleteWorkflowTemplate []gax.CallOption } -func defaultWorkflowTemplateClientOptions() []option.ClientOption { +func defaultWorkflowTemplateGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dataproc.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dataproc.mtls.googleapis.com:443"), @@ -149,38 +149,188 @@ func defaultWorkflowTemplateCallOptions() *WorkflowTemplateCallOptions { } } +// internalWorkflowTemplateClient is an interface that defines the methods availaible from Cloud Dataproc API. +type internalWorkflowTemplateClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateWorkflowTemplate(context.Context, *dataprocpb.CreateWorkflowTemplateRequest, ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) + GetWorkflowTemplate(context.Context, *dataprocpb.GetWorkflowTemplateRequest, ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) + InstantiateWorkflowTemplate(context.Context, *dataprocpb.InstantiateWorkflowTemplateRequest, ...gax.CallOption) (*InstantiateWorkflowTemplateOperation, error) + InstantiateWorkflowTemplateOperation(name string) *InstantiateWorkflowTemplateOperation + InstantiateInlineWorkflowTemplate(context.Context, *dataprocpb.InstantiateInlineWorkflowTemplateRequest, ...gax.CallOption) (*InstantiateInlineWorkflowTemplateOperation, error) + InstantiateInlineWorkflowTemplateOperation(name string) *InstantiateInlineWorkflowTemplateOperation + UpdateWorkflowTemplate(context.Context, *dataprocpb.UpdateWorkflowTemplateRequest, ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) + ListWorkflowTemplates(context.Context, *dataprocpb.ListWorkflowTemplatesRequest, ...gax.CallOption) *WorkflowTemplateIterator + DeleteWorkflowTemplate(context.Context, *dataprocpb.DeleteWorkflowTemplateRequest, ...gax.CallOption) error +} + // WorkflowTemplateClient is a client for interacting with Cloud Dataproc API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The API interface for managing Workflow Templates in the +// Dataproc API. type WorkflowTemplateClient struct { + // The internal transport-dependent client. + internalClient internalWorkflowTemplateClient + + // The call options for this service. + CallOptions *WorkflowTemplateCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *WorkflowTemplateClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *WorkflowTemplateClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *WorkflowTemplateClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateWorkflowTemplate creates new workflow template. +func (c *WorkflowTemplateClient) CreateWorkflowTemplate(ctx context.Context, req *dataprocpb.CreateWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { + return c.internalClient.CreateWorkflowTemplate(ctx, req, opts...) +} + +// GetWorkflowTemplate retrieves the latest workflow template. +// +// Can retrieve previously instantiated template by specifying optional +// version parameter. +func (c *WorkflowTemplateClient) GetWorkflowTemplate(ctx context.Context, req *dataprocpb.GetWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { + return c.internalClient.GetWorkflowTemplate(ctx, req, opts...) +} + +// InstantiateWorkflowTemplate instantiates a template and begins execution. +// +// The returned Operation can be used to track execution of +// workflow by polling +// operations.get. +// The Operation will complete when entire workflow is finished. +// +// The running workflow can be aborted via +// operations.cancel. +// This will cause any inflight jobs to be cancelled and workflow-owned +// clusters to be deleted. +// +// The Operation.metadata will be +// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#workflowmetadata). +// Also see Using +// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/concepts/workflows/debugging#using_workflowmetadata). +// +// On successful completion, +// Operation.response will be +// Empty. +func (c *WorkflowTemplateClient) InstantiateWorkflowTemplate(ctx context.Context, req *dataprocpb.InstantiateWorkflowTemplateRequest, opts ...gax.CallOption) (*InstantiateWorkflowTemplateOperation, error) { + return c.internalClient.InstantiateWorkflowTemplate(ctx, req, opts...) +} + +// InstantiateWorkflowTemplateOperation returns a new InstantiateWorkflowTemplateOperation from a given name. +// The name must be that of a previously created InstantiateWorkflowTemplateOperation, possibly from a different process. +func (c *WorkflowTemplateClient) InstantiateWorkflowTemplateOperation(name string) *InstantiateWorkflowTemplateOperation { + return c.internalClient.InstantiateWorkflowTemplateOperation(name) +} + +// InstantiateInlineWorkflowTemplate instantiates a template and begins execution. +// +// This method is equivalent to executing the sequence +// CreateWorkflowTemplate, +// InstantiateWorkflowTemplate, +// DeleteWorkflowTemplate. +// +// The returned Operation can be used to track execution of +// workflow by polling +// operations.get. +// The Operation will complete when entire workflow is finished. +// +// The running workflow can be aborted via +// operations.cancel. +// This will cause any inflight jobs to be cancelled and workflow-owned +// clusters to be deleted. +// +// The Operation.metadata will be +// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#workflowmetadata). +// Also see Using +// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/concepts/workflows/debugging#using_workflowmetadata). +// +// On successful completion, +// Operation.response will be +// Empty. +func (c *WorkflowTemplateClient) InstantiateInlineWorkflowTemplate(ctx context.Context, req *dataprocpb.InstantiateInlineWorkflowTemplateRequest, opts ...gax.CallOption) (*InstantiateInlineWorkflowTemplateOperation, error) { + return c.internalClient.InstantiateInlineWorkflowTemplate(ctx, req, opts...) +} + +// InstantiateInlineWorkflowTemplateOperation returns a new InstantiateInlineWorkflowTemplateOperation from a given name. +// The name must be that of a previously created InstantiateInlineWorkflowTemplateOperation, possibly from a different process. +func (c *WorkflowTemplateClient) InstantiateInlineWorkflowTemplateOperation(name string) *InstantiateInlineWorkflowTemplateOperation { + return c.internalClient.InstantiateInlineWorkflowTemplateOperation(name) +} + +// UpdateWorkflowTemplate updates (replaces) workflow template. The updated template +// must contain version that matches the current server version. +func (c *WorkflowTemplateClient) UpdateWorkflowTemplate(ctx context.Context, req *dataprocpb.UpdateWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { + return c.internalClient.UpdateWorkflowTemplate(ctx, req, opts...) +} + +// ListWorkflowTemplates lists workflows that match the specified filter in the request. +func (c *WorkflowTemplateClient) ListWorkflowTemplates(ctx context.Context, req *dataprocpb.ListWorkflowTemplatesRequest, opts ...gax.CallOption) *WorkflowTemplateIterator { + return c.internalClient.ListWorkflowTemplates(ctx, req, opts...) +} + +// DeleteWorkflowTemplate deletes a workflow template. It does not cancel in-progress workflows. +func (c *WorkflowTemplateClient) DeleteWorkflowTemplate(ctx context.Context, req *dataprocpb.DeleteWorkflowTemplateRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteWorkflowTemplate(ctx, req, opts...) +} + +// workflowTemplateGRPCClient is a client for interacting with Cloud Dataproc API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type workflowTemplateGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing WorkflowTemplateClient + CallOptions **WorkflowTemplateCallOptions + // The gRPC API client. workflowTemplateClient dataprocpb.WorkflowTemplateServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *WorkflowTemplateCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewWorkflowTemplateClient creates a new workflow template service client. +// NewWorkflowTemplateClient creates a new workflow template service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The API interface for managing Workflow Templates in the // Dataproc API. func NewWorkflowTemplateClient(ctx context.Context, opts ...option.ClientOption) (*WorkflowTemplateClient, error) { - clientOpts := defaultWorkflowTemplateClientOptions() - + clientOpts := defaultWorkflowTemplateGRPCClientOptions() if newWorkflowTemplateClientHook != nil { hookOpts, err := newWorkflowTemplateClientHook(ctx, clientHookParams{}) if err != nil { @@ -198,16 +348,19 @@ func NewWorkflowTemplateClient(ctx context.Context, opts ...option.ClientOption) if err != nil { return nil, err } - c := &WorkflowTemplateClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultWorkflowTemplateCallOptions(), + client := WorkflowTemplateClient{CallOptions: defaultWorkflowTemplateCallOptions()} + c := &workflowTemplateGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, workflowTemplateClient: dataprocpb.NewWorkflowTemplateServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -217,33 +370,33 @@ func NewWorkflowTemplateClient(ctx context.Context, opts ...option.ClientOption) // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *WorkflowTemplateClient) Connection() *grpc.ClientConn { +func (c *workflowTemplateGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *WorkflowTemplateClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *WorkflowTemplateClient) setGoogleClientInfo(keyval ...string) { +func (c *workflowTemplateGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateWorkflowTemplate creates new workflow template. -func (c *WorkflowTemplateClient) CreateWorkflowTemplate(ctx context.Context, req *dataprocpb.CreateWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *workflowTemplateGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *workflowTemplateGRPCClient) CreateWorkflowTemplate(ctx context.Context, req *dataprocpb.CreateWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -251,7 +404,7 @@ func (c *WorkflowTemplateClient) CreateWorkflowTemplate(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateWorkflowTemplate[0:len(c.CallOptions.CreateWorkflowTemplate):len(c.CallOptions.CreateWorkflowTemplate)], opts...) + opts = append((*c.CallOptions).CreateWorkflowTemplate[0:len((*c.CallOptions).CreateWorkflowTemplate):len((*c.CallOptions).CreateWorkflowTemplate)], opts...) var resp *dataprocpb.WorkflowTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -264,11 +417,7 @@ func (c *WorkflowTemplateClient) CreateWorkflowTemplate(ctx context.Context, req return resp, nil } -// GetWorkflowTemplate retrieves the latest workflow template. -// -// Can retrieve previously instantiated template by specifying optional -// version parameter. -func (c *WorkflowTemplateClient) GetWorkflowTemplate(ctx context.Context, req *dataprocpb.GetWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { +func (c *workflowTemplateGRPCClient) GetWorkflowTemplate(ctx context.Context, req *dataprocpb.GetWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -276,7 +425,7 @@ func (c *WorkflowTemplateClient) GetWorkflowTemplate(ctx context.Context, req *d } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetWorkflowTemplate[0:len(c.CallOptions.GetWorkflowTemplate):len(c.CallOptions.GetWorkflowTemplate)], opts...) + opts = append((*c.CallOptions).GetWorkflowTemplate[0:len((*c.CallOptions).GetWorkflowTemplate):len((*c.CallOptions).GetWorkflowTemplate)], opts...) var resp *dataprocpb.WorkflowTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -289,27 +438,7 @@ func (c *WorkflowTemplateClient) GetWorkflowTemplate(ctx context.Context, req *d return resp, nil } -// InstantiateWorkflowTemplate instantiates a template and begins execution. -// -// The returned Operation can be used to track execution of -// workflow by polling -// operations.get. -// The Operation will complete when entire workflow is finished. -// -// The running workflow can be aborted via -// operations.cancel. -// This will cause any inflight jobs to be cancelled and workflow-owned -// clusters to be deleted. -// -// The Operation.metadata will be -// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#workflowmetadata). -// Also see Using -// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/concepts/workflows/debugging#using_workflowmetadata). -// -// On successful completion, -// Operation.response will be -// Empty. -func (c *WorkflowTemplateClient) InstantiateWorkflowTemplate(ctx context.Context, req *dataprocpb.InstantiateWorkflowTemplateRequest, opts ...gax.CallOption) (*InstantiateWorkflowTemplateOperation, error) { +func (c *workflowTemplateGRPCClient) InstantiateWorkflowTemplate(ctx context.Context, req *dataprocpb.InstantiateWorkflowTemplateRequest, opts ...gax.CallOption) (*InstantiateWorkflowTemplateOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -317,7 +446,7 @@ func (c *WorkflowTemplateClient) InstantiateWorkflowTemplate(ctx context.Context } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.InstantiateWorkflowTemplate[0:len(c.CallOptions.InstantiateWorkflowTemplate):len(c.CallOptions.InstantiateWorkflowTemplate)], opts...) + opts = append((*c.CallOptions).InstantiateWorkflowTemplate[0:len((*c.CallOptions).InstantiateWorkflowTemplate):len((*c.CallOptions).InstantiateWorkflowTemplate)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -328,36 +457,11 @@ func (c *WorkflowTemplateClient) InstantiateWorkflowTemplate(ctx context.Context return nil, err } return &InstantiateWorkflowTemplateOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// InstantiateInlineWorkflowTemplate instantiates a template and begins execution. -// -// This method is equivalent to executing the sequence -// CreateWorkflowTemplate, -// InstantiateWorkflowTemplate, -// DeleteWorkflowTemplate. -// -// The returned Operation can be used to track execution of -// workflow by polling -// operations.get. -// The Operation will complete when entire workflow is finished. -// -// The running workflow can be aborted via -// operations.cancel. -// This will cause any inflight jobs to be cancelled and workflow-owned -// clusters to be deleted. -// -// The Operation.metadata will be -// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#workflowmetadata). -// Also see Using -// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/concepts/workflows/debugging#using_workflowmetadata). -// -// On successful completion, -// Operation.response will be -// Empty. -func (c *WorkflowTemplateClient) InstantiateInlineWorkflowTemplate(ctx context.Context, req *dataprocpb.InstantiateInlineWorkflowTemplateRequest, opts ...gax.CallOption) (*InstantiateInlineWorkflowTemplateOperation, error) { +func (c *workflowTemplateGRPCClient) InstantiateInlineWorkflowTemplate(ctx context.Context, req *dataprocpb.InstantiateInlineWorkflowTemplateRequest, opts ...gax.CallOption) (*InstantiateInlineWorkflowTemplateOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -365,7 +469,7 @@ func (c *WorkflowTemplateClient) InstantiateInlineWorkflowTemplate(ctx context.C } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.InstantiateInlineWorkflowTemplate[0:len(c.CallOptions.InstantiateInlineWorkflowTemplate):len(c.CallOptions.InstantiateInlineWorkflowTemplate)], opts...) + opts = append((*c.CallOptions).InstantiateInlineWorkflowTemplate[0:len((*c.CallOptions).InstantiateInlineWorkflowTemplate):len((*c.CallOptions).InstantiateInlineWorkflowTemplate)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -376,13 +480,11 @@ func (c *WorkflowTemplateClient) InstantiateInlineWorkflowTemplate(ctx context.C return nil, err } return &InstantiateInlineWorkflowTemplateOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateWorkflowTemplate updates (replaces) workflow template. The updated template -// must contain version that matches the current server version. -func (c *WorkflowTemplateClient) UpdateWorkflowTemplate(ctx context.Context, req *dataprocpb.UpdateWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { +func (c *workflowTemplateGRPCClient) UpdateWorkflowTemplate(ctx context.Context, req *dataprocpb.UpdateWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -390,7 +492,7 @@ func (c *WorkflowTemplateClient) UpdateWorkflowTemplate(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "template.name", url.QueryEscape(req.GetTemplate().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateWorkflowTemplate[0:len(c.CallOptions.UpdateWorkflowTemplate):len(c.CallOptions.UpdateWorkflowTemplate)], opts...) + opts = append((*c.CallOptions).UpdateWorkflowTemplate[0:len((*c.CallOptions).UpdateWorkflowTemplate):len((*c.CallOptions).UpdateWorkflowTemplate)], opts...) var resp *dataprocpb.WorkflowTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -403,11 +505,10 @@ func (c *WorkflowTemplateClient) UpdateWorkflowTemplate(ctx context.Context, req return resp, nil } -// ListWorkflowTemplates lists workflows that match the specified filter in the request. -func (c *WorkflowTemplateClient) ListWorkflowTemplates(ctx context.Context, req *dataprocpb.ListWorkflowTemplatesRequest, opts ...gax.CallOption) *WorkflowTemplateIterator { +func (c *workflowTemplateGRPCClient) ListWorkflowTemplates(ctx context.Context, req *dataprocpb.ListWorkflowTemplatesRequest, opts ...gax.CallOption) *WorkflowTemplateIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListWorkflowTemplates[0:len(c.CallOptions.ListWorkflowTemplates):len(c.CallOptions.ListWorkflowTemplates)], opts...) + opts = append((*c.CallOptions).ListWorkflowTemplates[0:len((*c.CallOptions).ListWorkflowTemplates):len((*c.CallOptions).ListWorkflowTemplates)], opts...) it := &WorkflowTemplateIterator{} req = proto.Clone(req).(*dataprocpb.ListWorkflowTemplatesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dataprocpb.WorkflowTemplate, string, error) { @@ -444,8 +545,7 @@ func (c *WorkflowTemplateClient) ListWorkflowTemplates(ctx context.Context, req return it } -// DeleteWorkflowTemplate deletes a workflow template. It does not cancel in-progress workflows. -func (c *WorkflowTemplateClient) DeleteWorkflowTemplate(ctx context.Context, req *dataprocpb.DeleteWorkflowTemplateRequest, opts ...gax.CallOption) error { +func (c *workflowTemplateGRPCClient) DeleteWorkflowTemplate(ctx context.Context, req *dataprocpb.DeleteWorkflowTemplateRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -453,7 +553,7 @@ func (c *WorkflowTemplateClient) DeleteWorkflowTemplate(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteWorkflowTemplate[0:len(c.CallOptions.DeleteWorkflowTemplate):len(c.CallOptions.DeleteWorkflowTemplate)], opts...) + opts = append((*c.CallOptions).DeleteWorkflowTemplate[0:len((*c.CallOptions).DeleteWorkflowTemplate):len((*c.CallOptions).DeleteWorkflowTemplate)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.workflowTemplateClient.DeleteWorkflowTemplate(ctx, req, settings.GRPC...) @@ -469,9 +569,9 @@ type InstantiateInlineWorkflowTemplateOperation struct { // InstantiateInlineWorkflowTemplateOperation returns a new InstantiateInlineWorkflowTemplateOperation from a given name. // The name must be that of a previously created InstantiateInlineWorkflowTemplateOperation, possibly from a different process. -func (c *WorkflowTemplateClient) InstantiateInlineWorkflowTemplateOperation(name string) *InstantiateInlineWorkflowTemplateOperation { +func (c *workflowTemplateGRPCClient) InstantiateInlineWorkflowTemplateOperation(name string) *InstantiateInlineWorkflowTemplateOperation { return &InstantiateInlineWorkflowTemplateOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -527,9 +627,9 @@ type InstantiateWorkflowTemplateOperation struct { // InstantiateWorkflowTemplateOperation returns a new InstantiateWorkflowTemplateOperation from a given name. // The name must be that of a previously created InstantiateWorkflowTemplateOperation, possibly from a different process. -func (c *WorkflowTemplateClient) InstantiateWorkflowTemplateOperation(name string) *InstantiateWorkflowTemplateOperation { +func (c *workflowTemplateGRPCClient) InstantiateWorkflowTemplateOperation(name string) *InstantiateWorkflowTemplateOperation { return &InstantiateWorkflowTemplateOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dataproc/apiv1/workflow_template_client_example_test.go b/dataproc/apiv1/workflow_template_client_example_test.go index 31d5a3e45f25..9ba80112e9c1 100644 --- a/dataproc/apiv1/workflow_template_client_example_test.go +++ b/dataproc/apiv1/workflow_template_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewWorkflowTemplateClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleWorkflowTemplateClient_CreateWorkflowTemplate() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.CreateWorkflowTemplateRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleWorkflowTemplateClient_CreateWorkflowTemplate() { } func ExampleWorkflowTemplateClient_GetWorkflowTemplate() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.GetWorkflowTemplateRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleWorkflowTemplateClient_GetWorkflowTemplate() { } func ExampleWorkflowTemplateClient_InstantiateWorkflowTemplate() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.InstantiateWorkflowTemplateRequest{ // TODO: Fill request struct fields. @@ -98,13 +97,12 @@ func ExampleWorkflowTemplateClient_InstantiateWorkflowTemplate() { } func ExampleWorkflowTemplateClient_InstantiateInlineWorkflowTemplate() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.InstantiateInlineWorkflowTemplateRequest{ // TODO: Fill request struct fields. @@ -121,13 +119,12 @@ func ExampleWorkflowTemplateClient_InstantiateInlineWorkflowTemplate() { } func ExampleWorkflowTemplateClient_UpdateWorkflowTemplate() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.UpdateWorkflowTemplateRequest{ // TODO: Fill request struct fields. @@ -141,14 +138,12 @@ func ExampleWorkflowTemplateClient_UpdateWorkflowTemplate() { } func ExampleWorkflowTemplateClient_ListWorkflowTemplates() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.ListWorkflowTemplatesRequest{ // TODO: Fill request struct fields. @@ -173,6 +168,7 @@ func ExampleWorkflowTemplateClient_DeleteWorkflowTemplate() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DeleteWorkflowTemplateRequest{ // TODO: Fill request struct fields. diff --git a/dataproc/apiv1beta2/autoscaling_policy_client.go b/dataproc/apiv1beta2/autoscaling_policy_client.go index 312e6bc94a59..43925b6887fa 100644 --- a/dataproc/apiv1beta2/autoscaling_policy_client.go +++ b/dataproc/apiv1beta2/autoscaling_policy_client.go @@ -46,7 +46,7 @@ type AutoscalingPolicyCallOptions struct { DeleteAutoscalingPolicy []gax.CallOption } -func defaultAutoscalingPolicyClientOptions() []option.ClientOption { +func defaultAutoscalingPolicyGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dataproc.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dataproc.mtls.googleapis.com:443"), @@ -101,33 +101,109 @@ func defaultAutoscalingPolicyCallOptions() *AutoscalingPolicyCallOptions { } } +// internalAutoscalingPolicyClient is an interface that defines the methods availaible from Cloud Dataproc API. +type internalAutoscalingPolicyClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateAutoscalingPolicy(context.Context, *dataprocpb.CreateAutoscalingPolicyRequest, ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) + UpdateAutoscalingPolicy(context.Context, *dataprocpb.UpdateAutoscalingPolicyRequest, ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) + GetAutoscalingPolicy(context.Context, *dataprocpb.GetAutoscalingPolicyRequest, ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) + ListAutoscalingPolicies(context.Context, *dataprocpb.ListAutoscalingPoliciesRequest, ...gax.CallOption) *AutoscalingPolicyIterator + DeleteAutoscalingPolicy(context.Context, *dataprocpb.DeleteAutoscalingPolicyRequest, ...gax.CallOption) error +} + // AutoscalingPolicyClient is a client for interacting with Cloud Dataproc API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The API interface for managing autoscaling policies in the +// Cloud Dataproc API. type AutoscalingPolicyClient struct { + // The internal transport-dependent client. + internalClient internalAutoscalingPolicyClient + + // The call options for this service. + CallOptions *AutoscalingPolicyCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *AutoscalingPolicyClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *AutoscalingPolicyClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *AutoscalingPolicyClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateAutoscalingPolicy creates new autoscaling policy. +func (c *AutoscalingPolicyClient) CreateAutoscalingPolicy(ctx context.Context, req *dataprocpb.CreateAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { + return c.internalClient.CreateAutoscalingPolicy(ctx, req, opts...) +} + +// UpdateAutoscalingPolicy updates (replaces) autoscaling policy. +// +// Disabled check for update_mask, because all updates will be full +// replacements. +func (c *AutoscalingPolicyClient) UpdateAutoscalingPolicy(ctx context.Context, req *dataprocpb.UpdateAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { + return c.internalClient.UpdateAutoscalingPolicy(ctx, req, opts...) +} + +// GetAutoscalingPolicy retrieves autoscaling policy. +func (c *AutoscalingPolicyClient) GetAutoscalingPolicy(ctx context.Context, req *dataprocpb.GetAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { + return c.internalClient.GetAutoscalingPolicy(ctx, req, opts...) +} + +// ListAutoscalingPolicies lists autoscaling policies in the project. +func (c *AutoscalingPolicyClient) ListAutoscalingPolicies(ctx context.Context, req *dataprocpb.ListAutoscalingPoliciesRequest, opts ...gax.CallOption) *AutoscalingPolicyIterator { + return c.internalClient.ListAutoscalingPolicies(ctx, req, opts...) +} + +// DeleteAutoscalingPolicy deletes an autoscaling policy. It is an error to delete an autoscaling +// policy that is in use by one or more clusters. +func (c *AutoscalingPolicyClient) DeleteAutoscalingPolicy(ctx context.Context, req *dataprocpb.DeleteAutoscalingPolicyRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteAutoscalingPolicy(ctx, req, opts...) +} + +// autoscalingPolicyGRPCClient is a client for interacting with Cloud Dataproc API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type autoscalingPolicyGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing AutoscalingPolicyClient + CallOptions **AutoscalingPolicyCallOptions + // The gRPC API client. autoscalingPolicyClient dataprocpb.AutoscalingPolicyServiceClient - // The call options for this service. - CallOptions *AutoscalingPolicyCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewAutoscalingPolicyClient creates a new autoscaling policy service client. +// NewAutoscalingPolicyClient creates a new autoscaling policy service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The API interface for managing autoscaling policies in the // Cloud Dataproc API. func NewAutoscalingPolicyClient(ctx context.Context, opts ...option.ClientOption) (*AutoscalingPolicyClient, error) { - clientOpts := defaultAutoscalingPolicyClientOptions() - + clientOpts := defaultAutoscalingPolicyGRPCClientOptions() if newAutoscalingPolicyClientHook != nil { hookOpts, err := newAutoscalingPolicyClientHook(ctx, clientHookParams{}) if err != nil { @@ -145,42 +221,44 @@ func NewAutoscalingPolicyClient(ctx context.Context, opts ...option.ClientOption if err != nil { return nil, err } - c := &AutoscalingPolicyClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultAutoscalingPolicyCallOptions(), + client := AutoscalingPolicyClient{CallOptions: defaultAutoscalingPolicyCallOptions()} + c := &autoscalingPolicyGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, autoscalingPolicyClient: dataprocpb.NewAutoscalingPolicyServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *AutoscalingPolicyClient) Connection() *grpc.ClientConn { +func (c *autoscalingPolicyGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *AutoscalingPolicyClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *AutoscalingPolicyClient) setGoogleClientInfo(keyval ...string) { +func (c *autoscalingPolicyGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateAutoscalingPolicy creates new autoscaling policy. -func (c *AutoscalingPolicyClient) CreateAutoscalingPolicy(ctx context.Context, req *dataprocpb.CreateAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *autoscalingPolicyGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *autoscalingPolicyGRPCClient) CreateAutoscalingPolicy(ctx context.Context, req *dataprocpb.CreateAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -188,7 +266,7 @@ func (c *AutoscalingPolicyClient) CreateAutoscalingPolicy(ctx context.Context, r } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateAutoscalingPolicy[0:len(c.CallOptions.CreateAutoscalingPolicy):len(c.CallOptions.CreateAutoscalingPolicy)], opts...) + opts = append((*c.CallOptions).CreateAutoscalingPolicy[0:len((*c.CallOptions).CreateAutoscalingPolicy):len((*c.CallOptions).CreateAutoscalingPolicy)], opts...) var resp *dataprocpb.AutoscalingPolicy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -201,11 +279,7 @@ func (c *AutoscalingPolicyClient) CreateAutoscalingPolicy(ctx context.Context, r return resp, nil } -// UpdateAutoscalingPolicy updates (replaces) autoscaling policy. -// -// Disabled check for update_mask, because all updates will be full -// replacements. -func (c *AutoscalingPolicyClient) UpdateAutoscalingPolicy(ctx context.Context, req *dataprocpb.UpdateAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { +func (c *autoscalingPolicyGRPCClient) UpdateAutoscalingPolicy(ctx context.Context, req *dataprocpb.UpdateAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -213,7 +287,7 @@ func (c *AutoscalingPolicyClient) UpdateAutoscalingPolicy(ctx context.Context, r } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "policy.name", url.QueryEscape(req.GetPolicy().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateAutoscalingPolicy[0:len(c.CallOptions.UpdateAutoscalingPolicy):len(c.CallOptions.UpdateAutoscalingPolicy)], opts...) + opts = append((*c.CallOptions).UpdateAutoscalingPolicy[0:len((*c.CallOptions).UpdateAutoscalingPolicy):len((*c.CallOptions).UpdateAutoscalingPolicy)], opts...) var resp *dataprocpb.AutoscalingPolicy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -226,8 +300,7 @@ func (c *AutoscalingPolicyClient) UpdateAutoscalingPolicy(ctx context.Context, r return resp, nil } -// GetAutoscalingPolicy retrieves autoscaling policy. -func (c *AutoscalingPolicyClient) GetAutoscalingPolicy(ctx context.Context, req *dataprocpb.GetAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { +func (c *autoscalingPolicyGRPCClient) GetAutoscalingPolicy(ctx context.Context, req *dataprocpb.GetAutoscalingPolicyRequest, opts ...gax.CallOption) (*dataprocpb.AutoscalingPolicy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -235,7 +308,7 @@ func (c *AutoscalingPolicyClient) GetAutoscalingPolicy(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetAutoscalingPolicy[0:len(c.CallOptions.GetAutoscalingPolicy):len(c.CallOptions.GetAutoscalingPolicy)], opts...) + opts = append((*c.CallOptions).GetAutoscalingPolicy[0:len((*c.CallOptions).GetAutoscalingPolicy):len((*c.CallOptions).GetAutoscalingPolicy)], opts...) var resp *dataprocpb.AutoscalingPolicy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -248,11 +321,10 @@ func (c *AutoscalingPolicyClient) GetAutoscalingPolicy(ctx context.Context, req return resp, nil } -// ListAutoscalingPolicies lists autoscaling policies in the project. -func (c *AutoscalingPolicyClient) ListAutoscalingPolicies(ctx context.Context, req *dataprocpb.ListAutoscalingPoliciesRequest, opts ...gax.CallOption) *AutoscalingPolicyIterator { +func (c *autoscalingPolicyGRPCClient) ListAutoscalingPolicies(ctx context.Context, req *dataprocpb.ListAutoscalingPoliciesRequest, opts ...gax.CallOption) *AutoscalingPolicyIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAutoscalingPolicies[0:len(c.CallOptions.ListAutoscalingPolicies):len(c.CallOptions.ListAutoscalingPolicies)], opts...) + opts = append((*c.CallOptions).ListAutoscalingPolicies[0:len((*c.CallOptions).ListAutoscalingPolicies):len((*c.CallOptions).ListAutoscalingPolicies)], opts...) it := &AutoscalingPolicyIterator{} req = proto.Clone(req).(*dataprocpb.ListAutoscalingPoliciesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dataprocpb.AutoscalingPolicy, string, error) { @@ -289,9 +361,7 @@ func (c *AutoscalingPolicyClient) ListAutoscalingPolicies(ctx context.Context, r return it } -// DeleteAutoscalingPolicy deletes an autoscaling policy. It is an error to delete an autoscaling -// policy that is in use by one or more clusters. -func (c *AutoscalingPolicyClient) DeleteAutoscalingPolicy(ctx context.Context, req *dataprocpb.DeleteAutoscalingPolicyRequest, opts ...gax.CallOption) error { +func (c *autoscalingPolicyGRPCClient) DeleteAutoscalingPolicy(ctx context.Context, req *dataprocpb.DeleteAutoscalingPolicyRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -299,7 +369,7 @@ func (c *AutoscalingPolicyClient) DeleteAutoscalingPolicy(ctx context.Context, r } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteAutoscalingPolicy[0:len(c.CallOptions.DeleteAutoscalingPolicy):len(c.CallOptions.DeleteAutoscalingPolicy)], opts...) + opts = append((*c.CallOptions).DeleteAutoscalingPolicy[0:len((*c.CallOptions).DeleteAutoscalingPolicy):len((*c.CallOptions).DeleteAutoscalingPolicy)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.autoscalingPolicyClient.DeleteAutoscalingPolicy(ctx, req, settings.GRPC...) diff --git a/dataproc/apiv1beta2/autoscaling_policy_client_example_test.go b/dataproc/apiv1beta2/autoscaling_policy_client_example_test.go index af2af53659a3..7201337850ca 100644 --- a/dataproc/apiv1beta2/autoscaling_policy_client_example_test.go +++ b/dataproc/apiv1beta2/autoscaling_policy_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewAutoscalingPolicyClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleAutoscalingPolicyClient_CreateAutoscalingPolicy() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewAutoscalingPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.CreateAutoscalingPolicyRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleAutoscalingPolicyClient_CreateAutoscalingPolicy() { } func ExampleAutoscalingPolicyClient_UpdateAutoscalingPolicy() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewAutoscalingPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.UpdateAutoscalingPolicyRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleAutoscalingPolicyClient_UpdateAutoscalingPolicy() { } func ExampleAutoscalingPolicyClient_GetAutoscalingPolicy() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewAutoscalingPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.GetAutoscalingPolicyRequest{ // TODO: Fill request struct fields. @@ -95,14 +94,12 @@ func ExampleAutoscalingPolicyClient_GetAutoscalingPolicy() { } func ExampleAutoscalingPolicyClient_ListAutoscalingPolicies() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dataproc.NewAutoscalingPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.ListAutoscalingPoliciesRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleAutoscalingPolicyClient_DeleteAutoscalingPolicy() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DeleteAutoscalingPolicyRequest{ // TODO: Fill request struct fields. diff --git a/dataproc/apiv1beta2/cluster_controller_client.go b/dataproc/apiv1beta2/cluster_controller_client.go index 7a0f86a8fada..bff0ea43fdb0 100644 --- a/dataproc/apiv1beta2/cluster_controller_client.go +++ b/dataproc/apiv1beta2/cluster_controller_client.go @@ -50,7 +50,7 @@ type ClusterControllerCallOptions struct { DiagnoseCluster []gax.CallOption } -func defaultClusterControllerClientOptions() []option.ClientOption { +func defaultClusterControllerGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dataproc.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dataproc.mtls.googleapis.com:443"), @@ -137,38 +137,161 @@ func defaultClusterControllerCallOptions() *ClusterControllerCallOptions { } } +// internalClusterControllerClient is an interface that defines the methods availaible from Cloud Dataproc API. +type internalClusterControllerClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateCluster(context.Context, *dataprocpb.CreateClusterRequest, ...gax.CallOption) (*CreateClusterOperation, error) + CreateClusterOperation(name string) *CreateClusterOperation + UpdateCluster(context.Context, *dataprocpb.UpdateClusterRequest, ...gax.CallOption) (*UpdateClusterOperation, error) + UpdateClusterOperation(name string) *UpdateClusterOperation + DeleteCluster(context.Context, *dataprocpb.DeleteClusterRequest, ...gax.CallOption) (*DeleteClusterOperation, error) + DeleteClusterOperation(name string) *DeleteClusterOperation + GetCluster(context.Context, *dataprocpb.GetClusterRequest, ...gax.CallOption) (*dataprocpb.Cluster, error) + ListClusters(context.Context, *dataprocpb.ListClustersRequest, ...gax.CallOption) *ClusterIterator + DiagnoseCluster(context.Context, *dataprocpb.DiagnoseClusterRequest, ...gax.CallOption) (*DiagnoseClusterOperation, error) + DiagnoseClusterOperation(name string) *DiagnoseClusterOperation +} + // ClusterControllerClient is a client for interacting with Cloud Dataproc API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The ClusterControllerService provides methods to manage clusters +// of Compute Engine instances. type ClusterControllerClient struct { + // The internal transport-dependent client. + internalClient internalClusterControllerClient + + // The call options for this service. + CallOptions *ClusterControllerCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ClusterControllerClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ClusterControllerClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ClusterControllerClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateCluster creates a cluster in a project. The returned +// Operation.metadata will be +// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1beta2#clusteroperationmetadata). +func (c *ClusterControllerClient) CreateCluster(ctx context.Context, req *dataprocpb.CreateClusterRequest, opts ...gax.CallOption) (*CreateClusterOperation, error) { + return c.internalClient.CreateCluster(ctx, req, opts...) +} + +// CreateClusterOperation returns a new CreateClusterOperation from a given name. +// The name must be that of a previously created CreateClusterOperation, possibly from a different process. +func (c *ClusterControllerClient) CreateClusterOperation(name string) *CreateClusterOperation { + return c.internalClient.CreateClusterOperation(name) +} + +// UpdateCluster updates a cluster in a project. The returned +// Operation.metadata will be +// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1beta2#clusteroperationmetadata). +func (c *ClusterControllerClient) UpdateCluster(ctx context.Context, req *dataprocpb.UpdateClusterRequest, opts ...gax.CallOption) (*UpdateClusterOperation, error) { + return c.internalClient.UpdateCluster(ctx, req, opts...) +} + +// UpdateClusterOperation returns a new UpdateClusterOperation from a given name. +// The name must be that of a previously created UpdateClusterOperation, possibly from a different process. +func (c *ClusterControllerClient) UpdateClusterOperation(name string) *UpdateClusterOperation { + return c.internalClient.UpdateClusterOperation(name) +} + +// DeleteCluster deletes a cluster in a project. The returned +// Operation.metadata will be +// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1beta2#clusteroperationmetadata). +func (c *ClusterControllerClient) DeleteCluster(ctx context.Context, req *dataprocpb.DeleteClusterRequest, opts ...gax.CallOption) (*DeleteClusterOperation, error) { + return c.internalClient.DeleteCluster(ctx, req, opts...) +} + +// DeleteClusterOperation returns a new DeleteClusterOperation from a given name. +// The name must be that of a previously created DeleteClusterOperation, possibly from a different process. +func (c *ClusterControllerClient) DeleteClusterOperation(name string) *DeleteClusterOperation { + return c.internalClient.DeleteClusterOperation(name) +} + +// GetCluster gets the resource representation for a cluster in a project. +func (c *ClusterControllerClient) GetCluster(ctx context.Context, req *dataprocpb.GetClusterRequest, opts ...gax.CallOption) (*dataprocpb.Cluster, error) { + return c.internalClient.GetCluster(ctx, req, opts...) +} + +// ListClusters lists all regions/{region}/clusters in a project alphabetically. +func (c *ClusterControllerClient) ListClusters(ctx context.Context, req *dataprocpb.ListClustersRequest, opts ...gax.CallOption) *ClusterIterator { + return c.internalClient.ListClusters(ctx, req, opts...) +} + +// DiagnoseCluster gets cluster diagnostic information. The returned +// Operation.metadata will be +// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1beta2#clusteroperationmetadata). +// After the operation completes, +// Operation.response +// contains +// Empty. +func (c *ClusterControllerClient) DiagnoseCluster(ctx context.Context, req *dataprocpb.DiagnoseClusterRequest, opts ...gax.CallOption) (*DiagnoseClusterOperation, error) { + return c.internalClient.DiagnoseCluster(ctx, req, opts...) +} + +// DiagnoseClusterOperation returns a new DiagnoseClusterOperation from a given name. +// The name must be that of a previously created DiagnoseClusterOperation, possibly from a different process. +func (c *ClusterControllerClient) DiagnoseClusterOperation(name string) *DiagnoseClusterOperation { + return c.internalClient.DiagnoseClusterOperation(name) +} + +// clusterControllerGRPCClient is a client for interacting with Cloud Dataproc API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type clusterControllerGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ClusterControllerClient + CallOptions **ClusterControllerCallOptions + // The gRPC API client. clusterControllerClient dataprocpb.ClusterControllerClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *ClusterControllerCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClusterControllerClient creates a new cluster controller client. +// NewClusterControllerClient creates a new cluster controller client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The ClusterControllerService provides methods to manage clusters // of Compute Engine instances. func NewClusterControllerClient(ctx context.Context, opts ...option.ClientOption) (*ClusterControllerClient, error) { - clientOpts := defaultClusterControllerClientOptions() - + clientOpts := defaultClusterControllerGRPCClientOptions() if newClusterControllerClientHook != nil { hookOpts, err := newClusterControllerClientHook(ctx, clientHookParams{}) if err != nil { @@ -186,16 +309,19 @@ func NewClusterControllerClient(ctx context.Context, opts ...option.ClientOption if err != nil { return nil, err } - c := &ClusterControllerClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultClusterControllerCallOptions(), + client := ClusterControllerClient{CallOptions: defaultClusterControllerCallOptions()} + c := &clusterControllerGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, clusterControllerClient: dataprocpb.NewClusterControllerClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -205,35 +331,33 @@ func NewClusterControllerClient(ctx context.Context, opts ...option.ClientOption // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ClusterControllerClient) Connection() *grpc.ClientConn { +func (c *clusterControllerGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ClusterControllerClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ClusterControllerClient) setGoogleClientInfo(keyval ...string) { +func (c *clusterControllerGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateCluster creates a cluster in a project. The returned -// Operation.metadata will be -// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1beta2#clusteroperationmetadata). -func (c *ClusterControllerClient) CreateCluster(ctx context.Context, req *dataprocpb.CreateClusterRequest, opts ...gax.CallOption) (*CreateClusterOperation, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *clusterControllerGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *clusterControllerGRPCClient) CreateCluster(ctx context.Context, req *dataprocpb.CreateClusterRequest, opts ...gax.CallOption) (*CreateClusterOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -241,7 +365,7 @@ func (c *ClusterControllerClient) CreateCluster(ctx context.Context, req *datapr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCluster[0:len(c.CallOptions.CreateCluster):len(c.CallOptions.CreateCluster)], opts...) + opts = append((*c.CallOptions).CreateCluster[0:len((*c.CallOptions).CreateCluster):len((*c.CallOptions).CreateCluster)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -252,14 +376,11 @@ func (c *ClusterControllerClient) CreateCluster(ctx context.Context, req *datapr return nil, err } return &CreateClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateCluster updates a cluster in a project. The returned -// Operation.metadata will be -// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1beta2#clusteroperationmetadata). -func (c *ClusterControllerClient) UpdateCluster(ctx context.Context, req *dataprocpb.UpdateClusterRequest, opts ...gax.CallOption) (*UpdateClusterOperation, error) { +func (c *clusterControllerGRPCClient) UpdateCluster(ctx context.Context, req *dataprocpb.UpdateClusterRequest, opts ...gax.CallOption) (*UpdateClusterOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -267,7 +388,7 @@ func (c *ClusterControllerClient) UpdateCluster(ctx context.Context, req *datapr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "cluster_name", url.QueryEscape(req.GetClusterName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCluster[0:len(c.CallOptions.UpdateCluster):len(c.CallOptions.UpdateCluster)], opts...) + opts = append((*c.CallOptions).UpdateCluster[0:len((*c.CallOptions).UpdateCluster):len((*c.CallOptions).UpdateCluster)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -278,14 +399,11 @@ func (c *ClusterControllerClient) UpdateCluster(ctx context.Context, req *datapr return nil, err } return &UpdateClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteCluster deletes a cluster in a project. The returned -// Operation.metadata will be -// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1beta2#clusteroperationmetadata). -func (c *ClusterControllerClient) DeleteCluster(ctx context.Context, req *dataprocpb.DeleteClusterRequest, opts ...gax.CallOption) (*DeleteClusterOperation, error) { +func (c *clusterControllerGRPCClient) DeleteCluster(ctx context.Context, req *dataprocpb.DeleteClusterRequest, opts ...gax.CallOption) (*DeleteClusterOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -293,7 +411,7 @@ func (c *ClusterControllerClient) DeleteCluster(ctx context.Context, req *datapr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "cluster_name", url.QueryEscape(req.GetClusterName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteCluster[0:len(c.CallOptions.DeleteCluster):len(c.CallOptions.DeleteCluster)], opts...) + opts = append((*c.CallOptions).DeleteCluster[0:len((*c.CallOptions).DeleteCluster):len((*c.CallOptions).DeleteCluster)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -304,12 +422,11 @@ func (c *ClusterControllerClient) DeleteCluster(ctx context.Context, req *datapr return nil, err } return &DeleteClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetCluster gets the resource representation for a cluster in a project. -func (c *ClusterControllerClient) GetCluster(ctx context.Context, req *dataprocpb.GetClusterRequest, opts ...gax.CallOption) (*dataprocpb.Cluster, error) { +func (c *clusterControllerGRPCClient) GetCluster(ctx context.Context, req *dataprocpb.GetClusterRequest, opts ...gax.CallOption) (*dataprocpb.Cluster, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -317,7 +434,7 @@ func (c *ClusterControllerClient) GetCluster(ctx context.Context, req *dataprocp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "cluster_name", url.QueryEscape(req.GetClusterName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCluster[0:len(c.CallOptions.GetCluster):len(c.CallOptions.GetCluster)], opts...) + opts = append((*c.CallOptions).GetCluster[0:len((*c.CallOptions).GetCluster):len((*c.CallOptions).GetCluster)], opts...) var resp *dataprocpb.Cluster err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -330,11 +447,10 @@ func (c *ClusterControllerClient) GetCluster(ctx context.Context, req *dataprocp return resp, nil } -// ListClusters lists all regions/{region}/clusters in a project alphabetically. -func (c *ClusterControllerClient) ListClusters(ctx context.Context, req *dataprocpb.ListClustersRequest, opts ...gax.CallOption) *ClusterIterator { +func (c *clusterControllerGRPCClient) ListClusters(ctx context.Context, req *dataprocpb.ListClustersRequest, opts ...gax.CallOption) *ClusterIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListClusters[0:len(c.CallOptions.ListClusters):len(c.CallOptions.ListClusters)], opts...) + opts = append((*c.CallOptions).ListClusters[0:len((*c.CallOptions).ListClusters):len((*c.CallOptions).ListClusters)], opts...) it := &ClusterIterator{} req = proto.Clone(req).(*dataprocpb.ListClustersRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dataprocpb.Cluster, string, error) { @@ -371,14 +487,7 @@ func (c *ClusterControllerClient) ListClusters(ctx context.Context, req *datapro return it } -// DiagnoseCluster gets cluster diagnostic information. The returned -// Operation.metadata will be -// ClusterOperationMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1beta2#clusteroperationmetadata). -// After the operation completes, -// Operation.response -// contains -// Empty. -func (c *ClusterControllerClient) DiagnoseCluster(ctx context.Context, req *dataprocpb.DiagnoseClusterRequest, opts ...gax.CallOption) (*DiagnoseClusterOperation, error) { +func (c *clusterControllerGRPCClient) DiagnoseCluster(ctx context.Context, req *dataprocpb.DiagnoseClusterRequest, opts ...gax.CallOption) (*DiagnoseClusterOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -386,7 +495,7 @@ func (c *ClusterControllerClient) DiagnoseCluster(ctx context.Context, req *data } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "cluster_name", url.QueryEscape(req.GetClusterName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DiagnoseCluster[0:len(c.CallOptions.DiagnoseCluster):len(c.CallOptions.DiagnoseCluster)], opts...) + opts = append((*c.CallOptions).DiagnoseCluster[0:len((*c.CallOptions).DiagnoseCluster):len((*c.CallOptions).DiagnoseCluster)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -397,7 +506,7 @@ func (c *ClusterControllerClient) DiagnoseCluster(ctx context.Context, req *data return nil, err } return &DiagnoseClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -408,9 +517,9 @@ type CreateClusterOperation struct { // CreateClusterOperation returns a new CreateClusterOperation from a given name. // The name must be that of a previously created CreateClusterOperation, possibly from a different process. -func (c *ClusterControllerClient) CreateClusterOperation(name string) *CreateClusterOperation { +func (c *clusterControllerGRPCClient) CreateClusterOperation(name string) *CreateClusterOperation { return &CreateClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -477,9 +586,9 @@ type DeleteClusterOperation struct { // DeleteClusterOperation returns a new DeleteClusterOperation from a given name. // The name must be that of a previously created DeleteClusterOperation, possibly from a different process. -func (c *ClusterControllerClient) DeleteClusterOperation(name string) *DeleteClusterOperation { +func (c *clusterControllerGRPCClient) DeleteClusterOperation(name string) *DeleteClusterOperation { return &DeleteClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -535,9 +644,9 @@ type DiagnoseClusterOperation struct { // DiagnoseClusterOperation returns a new DiagnoseClusterOperation from a given name. // The name must be that of a previously created DiagnoseClusterOperation, possibly from a different process. -func (c *ClusterControllerClient) DiagnoseClusterOperation(name string) *DiagnoseClusterOperation { +func (c *clusterControllerGRPCClient) DiagnoseClusterOperation(name string) *DiagnoseClusterOperation { return &DiagnoseClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -593,9 +702,9 @@ type UpdateClusterOperation struct { // UpdateClusterOperation returns a new UpdateClusterOperation from a given name. // The name must be that of a previously created UpdateClusterOperation, possibly from a different process. -func (c *ClusterControllerClient) UpdateClusterOperation(name string) *UpdateClusterOperation { +func (c *clusterControllerGRPCClient) UpdateClusterOperation(name string) *UpdateClusterOperation { return &UpdateClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dataproc/apiv1beta2/cluster_controller_client_example_test.go b/dataproc/apiv1beta2/cluster_controller_client_example_test.go index 65638ca0b131..f8abd8caef7c 100644 --- a/dataproc/apiv1beta2/cluster_controller_client_example_test.go +++ b/dataproc/apiv1beta2/cluster_controller_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClusterControllerClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClusterControllerClient_CreateCluster() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.CreateClusterRequest{ // TODO: Fill request struct fields. @@ -60,13 +61,12 @@ func ExampleClusterControllerClient_CreateCluster() { } func ExampleClusterControllerClient_UpdateCluster() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.UpdateClusterRequest{ // TODO: Fill request struct fields. @@ -85,13 +85,12 @@ func ExampleClusterControllerClient_UpdateCluster() { } func ExampleClusterControllerClient_DeleteCluster() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DeleteClusterRequest{ // TODO: Fill request struct fields. @@ -108,13 +107,12 @@ func ExampleClusterControllerClient_DeleteCluster() { } func ExampleClusterControllerClient_GetCluster() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.GetClusterRequest{ // TODO: Fill request struct fields. @@ -128,14 +126,12 @@ func ExampleClusterControllerClient_GetCluster() { } func ExampleClusterControllerClient_ListClusters() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.ListClustersRequest{ // TODO: Fill request struct fields. @@ -155,13 +151,12 @@ func ExampleClusterControllerClient_ListClusters() { } func ExampleClusterControllerClient_DiagnoseCluster() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DiagnoseClusterRequest{ // TODO: Fill request struct fields. diff --git a/dataproc/apiv1beta2/doc.go b/dataproc/apiv1beta2/doc.go index a366ff67d783..b31775416cef 100644 --- a/dataproc/apiv1beta2/doc.go +++ b/dataproc/apiv1beta2/doc.go @@ -19,6 +19,8 @@ // // Manages Hadoop-based clusters and jobs on Google Cloud Platform. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -28,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package dataproc // import "cloud.google.com/go/dataproc/apiv1beta2" import ( @@ -48,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/dataproc/apiv1beta2/job_controller_client.go b/dataproc/apiv1beta2/job_controller_client.go index 7a13aa01a00d..e90fcf7c3dcc 100644 --- a/dataproc/apiv1beta2/job_controller_client.go +++ b/dataproc/apiv1beta2/job_controller_client.go @@ -51,7 +51,7 @@ type JobControllerCallOptions struct { DeleteJob []gax.CallOption } -func defaultJobControllerClientOptions() []option.ClientOption { +func defaultJobControllerGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dataproc.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dataproc.mtls.googleapis.com:443"), @@ -151,37 +151,137 @@ func defaultJobControllerCallOptions() *JobControllerCallOptions { } } +// internalJobControllerClient is an interface that defines the methods availaible from Cloud Dataproc API. +type internalJobControllerClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + SubmitJob(context.Context, *dataprocpb.SubmitJobRequest, ...gax.CallOption) (*dataprocpb.Job, error) + SubmitJobAsOperation(context.Context, *dataprocpb.SubmitJobRequest, ...gax.CallOption) (*SubmitJobAsOperationOperation, error) + SubmitJobAsOperationOperation(name string) *SubmitJobAsOperationOperation + GetJob(context.Context, *dataprocpb.GetJobRequest, ...gax.CallOption) (*dataprocpb.Job, error) + ListJobs(context.Context, *dataprocpb.ListJobsRequest, ...gax.CallOption) *JobIterator + UpdateJob(context.Context, *dataprocpb.UpdateJobRequest, ...gax.CallOption) (*dataprocpb.Job, error) + CancelJob(context.Context, *dataprocpb.CancelJobRequest, ...gax.CallOption) (*dataprocpb.Job, error) + DeleteJob(context.Context, *dataprocpb.DeleteJobRequest, ...gax.CallOption) error +} + // JobControllerClient is a client for interacting with Cloud Dataproc API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The JobController provides methods to manage jobs. type JobControllerClient struct { + // The internal transport-dependent client. + internalClient internalJobControllerClient + + // The call options for this service. + CallOptions *JobControllerCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *JobControllerClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *JobControllerClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *JobControllerClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// SubmitJob submits a job to a cluster. +func (c *JobControllerClient) SubmitJob(ctx context.Context, req *dataprocpb.SubmitJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { + return c.internalClient.SubmitJob(ctx, req, opts...) +} + +// SubmitJobAsOperation submits job to a cluster. +func (c *JobControllerClient) SubmitJobAsOperation(ctx context.Context, req *dataprocpb.SubmitJobRequest, opts ...gax.CallOption) (*SubmitJobAsOperationOperation, error) { + return c.internalClient.SubmitJobAsOperation(ctx, req, opts...) +} + +// SubmitJobAsOperationOperation returns a new SubmitJobAsOperationOperation from a given name. +// The name must be that of a previously created SubmitJobAsOperationOperation, possibly from a different process. +func (c *JobControllerClient) SubmitJobAsOperationOperation(name string) *SubmitJobAsOperationOperation { + return c.internalClient.SubmitJobAsOperationOperation(name) +} + +// GetJob gets the resource representation for a job in a project. +func (c *JobControllerClient) GetJob(ctx context.Context, req *dataprocpb.GetJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { + return c.internalClient.GetJob(ctx, req, opts...) +} + +// ListJobs lists regions/{region}/jobs in a project. +func (c *JobControllerClient) ListJobs(ctx context.Context, req *dataprocpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { + return c.internalClient.ListJobs(ctx, req, opts...) +} + +// UpdateJob updates a job in a project. +func (c *JobControllerClient) UpdateJob(ctx context.Context, req *dataprocpb.UpdateJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { + return c.internalClient.UpdateJob(ctx, req, opts...) +} + +// CancelJob starts a job cancellation request. To access the job resource +// after cancellation, call +// regions/{region}/jobs.list (at https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/projects.regions.jobs/list) +// or +// regions/{region}/jobs.get (at https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/projects.regions.jobs/get). +func (c *JobControllerClient) CancelJob(ctx context.Context, req *dataprocpb.CancelJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { + return c.internalClient.CancelJob(ctx, req, opts...) +} + +// DeleteJob deletes the job from the project. If the job is active, the delete fails, +// and the response returns FAILED_PRECONDITION. +func (c *JobControllerClient) DeleteJob(ctx context.Context, req *dataprocpb.DeleteJobRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteJob(ctx, req, opts...) +} + +// jobControllerGRPCClient is a client for interacting with Cloud Dataproc API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type jobControllerGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing JobControllerClient + CallOptions **JobControllerCallOptions + // The gRPC API client. jobControllerClient dataprocpb.JobControllerClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *JobControllerCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewJobControllerClient creates a new job controller client. +// NewJobControllerClient creates a new job controller client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The JobController provides methods to manage jobs. func NewJobControllerClient(ctx context.Context, opts ...option.ClientOption) (*JobControllerClient, error) { - clientOpts := defaultJobControllerClientOptions() - + clientOpts := defaultJobControllerGRPCClientOptions() if newJobControllerClientHook != nil { hookOpts, err := newJobControllerClientHook(ctx, clientHookParams{}) if err != nil { @@ -199,16 +299,19 @@ func NewJobControllerClient(ctx context.Context, opts ...option.ClientOption) (* if err != nil { return nil, err } - c := &JobControllerClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultJobControllerCallOptions(), + client := JobControllerClient{CallOptions: defaultJobControllerCallOptions()} + c := &jobControllerGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, jobControllerClient: dataprocpb.NewJobControllerClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -218,33 +321,33 @@ func NewJobControllerClient(ctx context.Context, opts ...option.ClientOption) (* // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *JobControllerClient) Connection() *grpc.ClientConn { +func (c *jobControllerGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *JobControllerClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *JobControllerClient) setGoogleClientInfo(keyval ...string) { +func (c *jobControllerGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// SubmitJob submits a job to a cluster. -func (c *JobControllerClient) SubmitJob(ctx context.Context, req *dataprocpb.SubmitJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *jobControllerGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *jobControllerGRPCClient) SubmitJob(ctx context.Context, req *dataprocpb.SubmitJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 900000*time.Millisecond) defer cancel() @@ -252,7 +355,7 @@ func (c *JobControllerClient) SubmitJob(ctx context.Context, req *dataprocpb.Sub } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SubmitJob[0:len(c.CallOptions.SubmitJob):len(c.CallOptions.SubmitJob)], opts...) + opts = append((*c.CallOptions).SubmitJob[0:len((*c.CallOptions).SubmitJob):len((*c.CallOptions).SubmitJob)], opts...) var resp *dataprocpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -265,8 +368,7 @@ func (c *JobControllerClient) SubmitJob(ctx context.Context, req *dataprocpb.Sub return resp, nil } -// SubmitJobAsOperation submits job to a cluster. -func (c *JobControllerClient) SubmitJobAsOperation(ctx context.Context, req *dataprocpb.SubmitJobRequest, opts ...gax.CallOption) (*SubmitJobAsOperationOperation, error) { +func (c *jobControllerGRPCClient) SubmitJobAsOperation(ctx context.Context, req *dataprocpb.SubmitJobRequest, opts ...gax.CallOption) (*SubmitJobAsOperationOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 900000*time.Millisecond) defer cancel() @@ -274,7 +376,7 @@ func (c *JobControllerClient) SubmitJobAsOperation(ctx context.Context, req *dat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SubmitJobAsOperation[0:len(c.CallOptions.SubmitJobAsOperation):len(c.CallOptions.SubmitJobAsOperation)], opts...) + opts = append((*c.CallOptions).SubmitJobAsOperation[0:len((*c.CallOptions).SubmitJobAsOperation):len((*c.CallOptions).SubmitJobAsOperation)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -285,12 +387,11 @@ func (c *JobControllerClient) SubmitJobAsOperation(ctx context.Context, req *dat return nil, err } return &SubmitJobAsOperationOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetJob gets the resource representation for a job in a project. -func (c *JobControllerClient) GetJob(ctx context.Context, req *dataprocpb.GetJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { +func (c *jobControllerGRPCClient) GetJob(ctx context.Context, req *dataprocpb.GetJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 900000*time.Millisecond) defer cancel() @@ -298,7 +399,7 @@ func (c *JobControllerClient) GetJob(ctx context.Context, req *dataprocpb.GetJob } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "job_id", url.QueryEscape(req.GetJobId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetJob[0:len(c.CallOptions.GetJob):len(c.CallOptions.GetJob)], opts...) + opts = append((*c.CallOptions).GetJob[0:len((*c.CallOptions).GetJob):len((*c.CallOptions).GetJob)], opts...) var resp *dataprocpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -311,11 +412,10 @@ func (c *JobControllerClient) GetJob(ctx context.Context, req *dataprocpb.GetJob return resp, nil } -// ListJobs lists regions/{region}/jobs in a project. -func (c *JobControllerClient) ListJobs(ctx context.Context, req *dataprocpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { +func (c *jobControllerGRPCClient) ListJobs(ctx context.Context, req *dataprocpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListJobs[0:len(c.CallOptions.ListJobs):len(c.CallOptions.ListJobs)], opts...) + opts = append((*c.CallOptions).ListJobs[0:len((*c.CallOptions).ListJobs):len((*c.CallOptions).ListJobs)], opts...) it := &JobIterator{} req = proto.Clone(req).(*dataprocpb.ListJobsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dataprocpb.Job, string, error) { @@ -352,8 +452,7 @@ func (c *JobControllerClient) ListJobs(ctx context.Context, req *dataprocpb.List return it } -// UpdateJob updates a job in a project. -func (c *JobControllerClient) UpdateJob(ctx context.Context, req *dataprocpb.UpdateJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { +func (c *jobControllerGRPCClient) UpdateJob(ctx context.Context, req *dataprocpb.UpdateJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 900000*time.Millisecond) defer cancel() @@ -361,7 +460,7 @@ func (c *JobControllerClient) UpdateJob(ctx context.Context, req *dataprocpb.Upd } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "job_id", url.QueryEscape(req.GetJobId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateJob[0:len(c.CallOptions.UpdateJob):len(c.CallOptions.UpdateJob)], opts...) + opts = append((*c.CallOptions).UpdateJob[0:len((*c.CallOptions).UpdateJob):len((*c.CallOptions).UpdateJob)], opts...) var resp *dataprocpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -374,12 +473,7 @@ func (c *JobControllerClient) UpdateJob(ctx context.Context, req *dataprocpb.Upd return resp, nil } -// CancelJob starts a job cancellation request. To access the job resource -// after cancellation, call -// regions/{region}/jobs.list (at https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/projects.regions.jobs/list) -// or -// regions/{region}/jobs.get (at https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/projects.regions.jobs/get). -func (c *JobControllerClient) CancelJob(ctx context.Context, req *dataprocpb.CancelJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { +func (c *jobControllerGRPCClient) CancelJob(ctx context.Context, req *dataprocpb.CancelJobRequest, opts ...gax.CallOption) (*dataprocpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 900000*time.Millisecond) defer cancel() @@ -387,7 +481,7 @@ func (c *JobControllerClient) CancelJob(ctx context.Context, req *dataprocpb.Can } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "job_id", url.QueryEscape(req.GetJobId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CancelJob[0:len(c.CallOptions.CancelJob):len(c.CallOptions.CancelJob)], opts...) + opts = append((*c.CallOptions).CancelJob[0:len((*c.CallOptions).CancelJob):len((*c.CallOptions).CancelJob)], opts...) var resp *dataprocpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -400,9 +494,7 @@ func (c *JobControllerClient) CancelJob(ctx context.Context, req *dataprocpb.Can return resp, nil } -// DeleteJob deletes the job from the project. If the job is active, the delete fails, -// and the response returns FAILED_PRECONDITION. -func (c *JobControllerClient) DeleteJob(ctx context.Context, req *dataprocpb.DeleteJobRequest, opts ...gax.CallOption) error { +func (c *jobControllerGRPCClient) DeleteJob(ctx context.Context, req *dataprocpb.DeleteJobRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 900000*time.Millisecond) defer cancel() @@ -410,7 +502,7 @@ func (c *JobControllerClient) DeleteJob(ctx context.Context, req *dataprocpb.Del } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "region", url.QueryEscape(req.GetRegion()), "job_id", url.QueryEscape(req.GetJobId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteJob[0:len(c.CallOptions.DeleteJob):len(c.CallOptions.DeleteJob)], opts...) + opts = append((*c.CallOptions).DeleteJob[0:len((*c.CallOptions).DeleteJob):len((*c.CallOptions).DeleteJob)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.jobControllerClient.DeleteJob(ctx, req, settings.GRPC...) @@ -426,9 +518,9 @@ type SubmitJobAsOperationOperation struct { // SubmitJobAsOperationOperation returns a new SubmitJobAsOperationOperation from a given name. // The name must be that of a previously created SubmitJobAsOperationOperation, possibly from a different process. -func (c *JobControllerClient) SubmitJobAsOperationOperation(name string) *SubmitJobAsOperationOperation { +func (c *jobControllerGRPCClient) SubmitJobAsOperationOperation(name string) *SubmitJobAsOperationOperation { return &SubmitJobAsOperationOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dataproc/apiv1beta2/job_controller_client_example_test.go b/dataproc/apiv1beta2/job_controller_client_example_test.go index 82db7a80d49c..88ed5dd08f1c 100644 --- a/dataproc/apiv1beta2/job_controller_client_example_test.go +++ b/dataproc/apiv1beta2/job_controller_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewJobControllerClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleJobControllerClient_SubmitJob() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.SubmitJobRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleJobControllerClient_SubmitJob() { } func ExampleJobControllerClient_SubmitJobAsOperation() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.SubmitJobRequest{ // TODO: Fill request struct fields. @@ -80,13 +80,12 @@ func ExampleJobControllerClient_SubmitJobAsOperation() { } func ExampleJobControllerClient_GetJob() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.GetJobRequest{ // TODO: Fill request struct fields. @@ -100,14 +99,12 @@ func ExampleJobControllerClient_GetJob() { } func ExampleJobControllerClient_ListJobs() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.ListJobsRequest{ // TODO: Fill request struct fields. @@ -127,13 +124,12 @@ func ExampleJobControllerClient_ListJobs() { } func ExampleJobControllerClient_UpdateJob() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.UpdateJobRequest{ // TODO: Fill request struct fields. @@ -147,13 +143,12 @@ func ExampleJobControllerClient_UpdateJob() { } func ExampleJobControllerClient_CancelJob() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.CancelJobRequest{ // TODO: Fill request struct fields. @@ -172,6 +167,7 @@ func ExampleJobControllerClient_DeleteJob() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DeleteJobRequest{ // TODO: Fill request struct fields. diff --git a/dataproc/apiv1beta2/workflow_template_client.go b/dataproc/apiv1beta2/workflow_template_client.go index 7ef668b845cd..8faff9cb37f8 100644 --- a/dataproc/apiv1beta2/workflow_template_client.go +++ b/dataproc/apiv1beta2/workflow_template_client.go @@ -51,7 +51,7 @@ type WorkflowTemplateCallOptions struct { DeleteWorkflowTemplate []gax.CallOption } -func defaultWorkflowTemplateClientOptions() []option.ClientOption { +func defaultWorkflowTemplateGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dataproc.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dataproc.mtls.googleapis.com:443"), @@ -149,38 +149,188 @@ func defaultWorkflowTemplateCallOptions() *WorkflowTemplateCallOptions { } } +// internalWorkflowTemplateClient is an interface that defines the methods availaible from Cloud Dataproc API. +type internalWorkflowTemplateClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateWorkflowTemplate(context.Context, *dataprocpb.CreateWorkflowTemplateRequest, ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) + GetWorkflowTemplate(context.Context, *dataprocpb.GetWorkflowTemplateRequest, ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) + InstantiateWorkflowTemplate(context.Context, *dataprocpb.InstantiateWorkflowTemplateRequest, ...gax.CallOption) (*InstantiateWorkflowTemplateOperation, error) + InstantiateWorkflowTemplateOperation(name string) *InstantiateWorkflowTemplateOperation + InstantiateInlineWorkflowTemplate(context.Context, *dataprocpb.InstantiateInlineWorkflowTemplateRequest, ...gax.CallOption) (*InstantiateInlineWorkflowTemplateOperation, error) + InstantiateInlineWorkflowTemplateOperation(name string) *InstantiateInlineWorkflowTemplateOperation + UpdateWorkflowTemplate(context.Context, *dataprocpb.UpdateWorkflowTemplateRequest, ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) + ListWorkflowTemplates(context.Context, *dataprocpb.ListWorkflowTemplatesRequest, ...gax.CallOption) *WorkflowTemplateIterator + DeleteWorkflowTemplate(context.Context, *dataprocpb.DeleteWorkflowTemplateRequest, ...gax.CallOption) error +} + // WorkflowTemplateClient is a client for interacting with Cloud Dataproc API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The API interface for managing Workflow Templates in the +// Dataproc API. type WorkflowTemplateClient struct { + // The internal transport-dependent client. + internalClient internalWorkflowTemplateClient + + // The call options for this service. + CallOptions *WorkflowTemplateCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *WorkflowTemplateClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *WorkflowTemplateClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *WorkflowTemplateClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateWorkflowTemplate creates new workflow template. +func (c *WorkflowTemplateClient) CreateWorkflowTemplate(ctx context.Context, req *dataprocpb.CreateWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { + return c.internalClient.CreateWorkflowTemplate(ctx, req, opts...) +} + +// GetWorkflowTemplate retrieves the latest workflow template. +// +// Can retrieve previously instantiated template by specifying optional +// version parameter. +func (c *WorkflowTemplateClient) GetWorkflowTemplate(ctx context.Context, req *dataprocpb.GetWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { + return c.internalClient.GetWorkflowTemplate(ctx, req, opts...) +} + +// InstantiateWorkflowTemplate instantiates a template and begins execution. +// +// The returned Operation can be used to track execution of +// workflow by polling +// operations.get. +// The Operation will complete when entire workflow is finished. +// +// The running workflow can be aborted via +// operations.cancel. +// This will cause any inflight jobs to be cancelled and workflow-owned +// clusters to be deleted. +// +// The Operation.metadata will be +// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1beta2#workflowmetadata). +// Also see Using +// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/concepts/workflows/debugging#using_workflowmetadata). +// +// On successful completion, +// Operation.response will be +// Empty. +func (c *WorkflowTemplateClient) InstantiateWorkflowTemplate(ctx context.Context, req *dataprocpb.InstantiateWorkflowTemplateRequest, opts ...gax.CallOption) (*InstantiateWorkflowTemplateOperation, error) { + return c.internalClient.InstantiateWorkflowTemplate(ctx, req, opts...) +} + +// InstantiateWorkflowTemplateOperation returns a new InstantiateWorkflowTemplateOperation from a given name. +// The name must be that of a previously created InstantiateWorkflowTemplateOperation, possibly from a different process. +func (c *WorkflowTemplateClient) InstantiateWorkflowTemplateOperation(name string) *InstantiateWorkflowTemplateOperation { + return c.internalClient.InstantiateWorkflowTemplateOperation(name) +} + +// InstantiateInlineWorkflowTemplate instantiates a template and begins execution. +// +// This method is equivalent to executing the sequence +// CreateWorkflowTemplate, +// InstantiateWorkflowTemplate, +// DeleteWorkflowTemplate. +// +// The returned Operation can be used to track execution of +// workflow by polling +// operations.get. +// The Operation will complete when entire workflow is finished. +// +// The running workflow can be aborted via +// operations.cancel. +// This will cause any inflight jobs to be cancelled and workflow-owned +// clusters to be deleted. +// +// The Operation.metadata will be +// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#workflowmetadata). +// Also see Using +// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/concepts/workflows/debugging#using_workflowmetadata). +// +// On successful completion, +// Operation.response will be +// Empty. +func (c *WorkflowTemplateClient) InstantiateInlineWorkflowTemplate(ctx context.Context, req *dataprocpb.InstantiateInlineWorkflowTemplateRequest, opts ...gax.CallOption) (*InstantiateInlineWorkflowTemplateOperation, error) { + return c.internalClient.InstantiateInlineWorkflowTemplate(ctx, req, opts...) +} + +// InstantiateInlineWorkflowTemplateOperation returns a new InstantiateInlineWorkflowTemplateOperation from a given name. +// The name must be that of a previously created InstantiateInlineWorkflowTemplateOperation, possibly from a different process. +func (c *WorkflowTemplateClient) InstantiateInlineWorkflowTemplateOperation(name string) *InstantiateInlineWorkflowTemplateOperation { + return c.internalClient.InstantiateInlineWorkflowTemplateOperation(name) +} + +// UpdateWorkflowTemplate updates (replaces) workflow template. The updated template +// must contain version that matches the current server version. +func (c *WorkflowTemplateClient) UpdateWorkflowTemplate(ctx context.Context, req *dataprocpb.UpdateWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { + return c.internalClient.UpdateWorkflowTemplate(ctx, req, opts...) +} + +// ListWorkflowTemplates lists workflows that match the specified filter in the request. +func (c *WorkflowTemplateClient) ListWorkflowTemplates(ctx context.Context, req *dataprocpb.ListWorkflowTemplatesRequest, opts ...gax.CallOption) *WorkflowTemplateIterator { + return c.internalClient.ListWorkflowTemplates(ctx, req, opts...) +} + +// DeleteWorkflowTemplate deletes a workflow template. It does not cancel in-progress workflows. +func (c *WorkflowTemplateClient) DeleteWorkflowTemplate(ctx context.Context, req *dataprocpb.DeleteWorkflowTemplateRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteWorkflowTemplate(ctx, req, opts...) +} + +// workflowTemplateGRPCClient is a client for interacting with Cloud Dataproc API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type workflowTemplateGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing WorkflowTemplateClient + CallOptions **WorkflowTemplateCallOptions + // The gRPC API client. workflowTemplateClient dataprocpb.WorkflowTemplateServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *WorkflowTemplateCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewWorkflowTemplateClient creates a new workflow template service client. +// NewWorkflowTemplateClient creates a new workflow template service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The API interface for managing Workflow Templates in the // Dataproc API. func NewWorkflowTemplateClient(ctx context.Context, opts ...option.ClientOption) (*WorkflowTemplateClient, error) { - clientOpts := defaultWorkflowTemplateClientOptions() - + clientOpts := defaultWorkflowTemplateGRPCClientOptions() if newWorkflowTemplateClientHook != nil { hookOpts, err := newWorkflowTemplateClientHook(ctx, clientHookParams{}) if err != nil { @@ -198,16 +348,19 @@ func NewWorkflowTemplateClient(ctx context.Context, opts ...option.ClientOption) if err != nil { return nil, err } - c := &WorkflowTemplateClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultWorkflowTemplateCallOptions(), + client := WorkflowTemplateClient{CallOptions: defaultWorkflowTemplateCallOptions()} + c := &workflowTemplateGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, workflowTemplateClient: dataprocpb.NewWorkflowTemplateServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -217,33 +370,33 @@ func NewWorkflowTemplateClient(ctx context.Context, opts ...option.ClientOption) // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *WorkflowTemplateClient) Connection() *grpc.ClientConn { +func (c *workflowTemplateGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *WorkflowTemplateClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *WorkflowTemplateClient) setGoogleClientInfo(keyval ...string) { +func (c *workflowTemplateGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateWorkflowTemplate creates new workflow template. -func (c *WorkflowTemplateClient) CreateWorkflowTemplate(ctx context.Context, req *dataprocpb.CreateWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *workflowTemplateGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *workflowTemplateGRPCClient) CreateWorkflowTemplate(ctx context.Context, req *dataprocpb.CreateWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -251,7 +404,7 @@ func (c *WorkflowTemplateClient) CreateWorkflowTemplate(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateWorkflowTemplate[0:len(c.CallOptions.CreateWorkflowTemplate):len(c.CallOptions.CreateWorkflowTemplate)], opts...) + opts = append((*c.CallOptions).CreateWorkflowTemplate[0:len((*c.CallOptions).CreateWorkflowTemplate):len((*c.CallOptions).CreateWorkflowTemplate)], opts...) var resp *dataprocpb.WorkflowTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -264,11 +417,7 @@ func (c *WorkflowTemplateClient) CreateWorkflowTemplate(ctx context.Context, req return resp, nil } -// GetWorkflowTemplate retrieves the latest workflow template. -// -// Can retrieve previously instantiated template by specifying optional -// version parameter. -func (c *WorkflowTemplateClient) GetWorkflowTemplate(ctx context.Context, req *dataprocpb.GetWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { +func (c *workflowTemplateGRPCClient) GetWorkflowTemplate(ctx context.Context, req *dataprocpb.GetWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -276,7 +425,7 @@ func (c *WorkflowTemplateClient) GetWorkflowTemplate(ctx context.Context, req *d } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetWorkflowTemplate[0:len(c.CallOptions.GetWorkflowTemplate):len(c.CallOptions.GetWorkflowTemplate)], opts...) + opts = append((*c.CallOptions).GetWorkflowTemplate[0:len((*c.CallOptions).GetWorkflowTemplate):len((*c.CallOptions).GetWorkflowTemplate)], opts...) var resp *dataprocpb.WorkflowTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -289,27 +438,7 @@ func (c *WorkflowTemplateClient) GetWorkflowTemplate(ctx context.Context, req *d return resp, nil } -// InstantiateWorkflowTemplate instantiates a template and begins execution. -// -// The returned Operation can be used to track execution of -// workflow by polling -// operations.get. -// The Operation will complete when entire workflow is finished. -// -// The running workflow can be aborted via -// operations.cancel. -// This will cause any inflight jobs to be cancelled and workflow-owned -// clusters to be deleted. -// -// The Operation.metadata will be -// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1beta2#workflowmetadata). -// Also see Using -// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/concepts/workflows/debugging#using_workflowmetadata). -// -// On successful completion, -// Operation.response will be -// Empty. -func (c *WorkflowTemplateClient) InstantiateWorkflowTemplate(ctx context.Context, req *dataprocpb.InstantiateWorkflowTemplateRequest, opts ...gax.CallOption) (*InstantiateWorkflowTemplateOperation, error) { +func (c *workflowTemplateGRPCClient) InstantiateWorkflowTemplate(ctx context.Context, req *dataprocpb.InstantiateWorkflowTemplateRequest, opts ...gax.CallOption) (*InstantiateWorkflowTemplateOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -317,7 +446,7 @@ func (c *WorkflowTemplateClient) InstantiateWorkflowTemplate(ctx context.Context } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.InstantiateWorkflowTemplate[0:len(c.CallOptions.InstantiateWorkflowTemplate):len(c.CallOptions.InstantiateWorkflowTemplate)], opts...) + opts = append((*c.CallOptions).InstantiateWorkflowTemplate[0:len((*c.CallOptions).InstantiateWorkflowTemplate):len((*c.CallOptions).InstantiateWorkflowTemplate)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -328,36 +457,11 @@ func (c *WorkflowTemplateClient) InstantiateWorkflowTemplate(ctx context.Context return nil, err } return &InstantiateWorkflowTemplateOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// InstantiateInlineWorkflowTemplate instantiates a template and begins execution. -// -// This method is equivalent to executing the sequence -// CreateWorkflowTemplate, -// InstantiateWorkflowTemplate, -// DeleteWorkflowTemplate. -// -// The returned Operation can be used to track execution of -// workflow by polling -// operations.get. -// The Operation will complete when entire workflow is finished. -// -// The running workflow can be aborted via -// operations.cancel. -// This will cause any inflight jobs to be cancelled and workflow-owned -// clusters to be deleted. -// -// The Operation.metadata will be -// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/reference/rpc/google.cloud.dataproc.v1#workflowmetadata). -// Also see Using -// WorkflowMetadata (at https://cloud.google.com/dataproc/docs/concepts/workflows/debugging#using_workflowmetadata). -// -// On successful completion, -// Operation.response will be -// Empty. -func (c *WorkflowTemplateClient) InstantiateInlineWorkflowTemplate(ctx context.Context, req *dataprocpb.InstantiateInlineWorkflowTemplateRequest, opts ...gax.CallOption) (*InstantiateInlineWorkflowTemplateOperation, error) { +func (c *workflowTemplateGRPCClient) InstantiateInlineWorkflowTemplate(ctx context.Context, req *dataprocpb.InstantiateInlineWorkflowTemplateRequest, opts ...gax.CallOption) (*InstantiateInlineWorkflowTemplateOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -365,7 +469,7 @@ func (c *WorkflowTemplateClient) InstantiateInlineWorkflowTemplate(ctx context.C } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.InstantiateInlineWorkflowTemplate[0:len(c.CallOptions.InstantiateInlineWorkflowTemplate):len(c.CallOptions.InstantiateInlineWorkflowTemplate)], opts...) + opts = append((*c.CallOptions).InstantiateInlineWorkflowTemplate[0:len((*c.CallOptions).InstantiateInlineWorkflowTemplate):len((*c.CallOptions).InstantiateInlineWorkflowTemplate)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -376,13 +480,11 @@ func (c *WorkflowTemplateClient) InstantiateInlineWorkflowTemplate(ctx context.C return nil, err } return &InstantiateInlineWorkflowTemplateOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateWorkflowTemplate updates (replaces) workflow template. The updated template -// must contain version that matches the current server version. -func (c *WorkflowTemplateClient) UpdateWorkflowTemplate(ctx context.Context, req *dataprocpb.UpdateWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { +func (c *workflowTemplateGRPCClient) UpdateWorkflowTemplate(ctx context.Context, req *dataprocpb.UpdateWorkflowTemplateRequest, opts ...gax.CallOption) (*dataprocpb.WorkflowTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -390,7 +492,7 @@ func (c *WorkflowTemplateClient) UpdateWorkflowTemplate(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "template.name", url.QueryEscape(req.GetTemplate().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateWorkflowTemplate[0:len(c.CallOptions.UpdateWorkflowTemplate):len(c.CallOptions.UpdateWorkflowTemplate)], opts...) + opts = append((*c.CallOptions).UpdateWorkflowTemplate[0:len((*c.CallOptions).UpdateWorkflowTemplate):len((*c.CallOptions).UpdateWorkflowTemplate)], opts...) var resp *dataprocpb.WorkflowTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -403,11 +505,10 @@ func (c *WorkflowTemplateClient) UpdateWorkflowTemplate(ctx context.Context, req return resp, nil } -// ListWorkflowTemplates lists workflows that match the specified filter in the request. -func (c *WorkflowTemplateClient) ListWorkflowTemplates(ctx context.Context, req *dataprocpb.ListWorkflowTemplatesRequest, opts ...gax.CallOption) *WorkflowTemplateIterator { +func (c *workflowTemplateGRPCClient) ListWorkflowTemplates(ctx context.Context, req *dataprocpb.ListWorkflowTemplatesRequest, opts ...gax.CallOption) *WorkflowTemplateIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListWorkflowTemplates[0:len(c.CallOptions.ListWorkflowTemplates):len(c.CallOptions.ListWorkflowTemplates)], opts...) + opts = append((*c.CallOptions).ListWorkflowTemplates[0:len((*c.CallOptions).ListWorkflowTemplates):len((*c.CallOptions).ListWorkflowTemplates)], opts...) it := &WorkflowTemplateIterator{} req = proto.Clone(req).(*dataprocpb.ListWorkflowTemplatesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dataprocpb.WorkflowTemplate, string, error) { @@ -444,8 +545,7 @@ func (c *WorkflowTemplateClient) ListWorkflowTemplates(ctx context.Context, req return it } -// DeleteWorkflowTemplate deletes a workflow template. It does not cancel in-progress workflows. -func (c *WorkflowTemplateClient) DeleteWorkflowTemplate(ctx context.Context, req *dataprocpb.DeleteWorkflowTemplateRequest, opts ...gax.CallOption) error { +func (c *workflowTemplateGRPCClient) DeleteWorkflowTemplate(ctx context.Context, req *dataprocpb.DeleteWorkflowTemplateRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -453,7 +553,7 @@ func (c *WorkflowTemplateClient) DeleteWorkflowTemplate(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteWorkflowTemplate[0:len(c.CallOptions.DeleteWorkflowTemplate):len(c.CallOptions.DeleteWorkflowTemplate)], opts...) + opts = append((*c.CallOptions).DeleteWorkflowTemplate[0:len((*c.CallOptions).DeleteWorkflowTemplate):len((*c.CallOptions).DeleteWorkflowTemplate)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.workflowTemplateClient.DeleteWorkflowTemplate(ctx, req, settings.GRPC...) @@ -469,9 +569,9 @@ type InstantiateInlineWorkflowTemplateOperation struct { // InstantiateInlineWorkflowTemplateOperation returns a new InstantiateInlineWorkflowTemplateOperation from a given name. // The name must be that of a previously created InstantiateInlineWorkflowTemplateOperation, possibly from a different process. -func (c *WorkflowTemplateClient) InstantiateInlineWorkflowTemplateOperation(name string) *InstantiateInlineWorkflowTemplateOperation { +func (c *workflowTemplateGRPCClient) InstantiateInlineWorkflowTemplateOperation(name string) *InstantiateInlineWorkflowTemplateOperation { return &InstantiateInlineWorkflowTemplateOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -527,9 +627,9 @@ type InstantiateWorkflowTemplateOperation struct { // InstantiateWorkflowTemplateOperation returns a new InstantiateWorkflowTemplateOperation from a given name. // The name must be that of a previously created InstantiateWorkflowTemplateOperation, possibly from a different process. -func (c *WorkflowTemplateClient) InstantiateWorkflowTemplateOperation(name string) *InstantiateWorkflowTemplateOperation { +func (c *workflowTemplateGRPCClient) InstantiateWorkflowTemplateOperation(name string) *InstantiateWorkflowTemplateOperation { return &InstantiateWorkflowTemplateOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dataproc/apiv1beta2/workflow_template_client_example_test.go b/dataproc/apiv1beta2/workflow_template_client_example_test.go index af018e923720..cf256b12fc13 100644 --- a/dataproc/apiv1beta2/workflow_template_client_example_test.go +++ b/dataproc/apiv1beta2/workflow_template_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewWorkflowTemplateClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleWorkflowTemplateClient_CreateWorkflowTemplate() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.CreateWorkflowTemplateRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleWorkflowTemplateClient_CreateWorkflowTemplate() { } func ExampleWorkflowTemplateClient_GetWorkflowTemplate() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.GetWorkflowTemplateRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleWorkflowTemplateClient_GetWorkflowTemplate() { } func ExampleWorkflowTemplateClient_InstantiateWorkflowTemplate() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.InstantiateWorkflowTemplateRequest{ // TODO: Fill request struct fields. @@ -98,13 +97,12 @@ func ExampleWorkflowTemplateClient_InstantiateWorkflowTemplate() { } func ExampleWorkflowTemplateClient_InstantiateInlineWorkflowTemplate() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.InstantiateInlineWorkflowTemplateRequest{ // TODO: Fill request struct fields. @@ -121,13 +119,12 @@ func ExampleWorkflowTemplateClient_InstantiateInlineWorkflowTemplate() { } func ExampleWorkflowTemplateClient_UpdateWorkflowTemplate() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.UpdateWorkflowTemplateRequest{ // TODO: Fill request struct fields. @@ -141,14 +138,12 @@ func ExampleWorkflowTemplateClient_UpdateWorkflowTemplate() { } func ExampleWorkflowTemplateClient_ListWorkflowTemplates() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.ListWorkflowTemplatesRequest{ // TODO: Fill request struct fields. @@ -173,6 +168,7 @@ func ExampleWorkflowTemplateClient_DeleteWorkflowTemplate() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DeleteWorkflowTemplateRequest{ // TODO: Fill request struct fields. diff --git a/dataqna/apiv1alpha/auto_suggestion_client.go b/dataqna/apiv1alpha/auto_suggestion_client.go index 2568d20b7b57..192fd27a31a1 100644 --- a/dataqna/apiv1alpha/auto_suggestion_client.go +++ b/dataqna/apiv1alpha/auto_suggestion_client.go @@ -39,7 +39,7 @@ type AutoSuggestionCallOptions struct { SuggestQueries []gax.CallOption } -func defaultAutoSuggestionClientOptions() []option.ClientOption { +func defaultAutoSuggestionGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dataqna.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dataqna.mtls.googleapis.com:443"), @@ -57,27 +57,90 @@ func defaultAutoSuggestionCallOptions() *AutoSuggestionCallOptions { } } +// internalAutoSuggestionClient is an interface that defines the methods availaible from Data QnA API. +type internalAutoSuggestionClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + SuggestQueries(context.Context, *dataqnapb.SuggestQueriesRequest, ...gax.CallOption) (*dataqnapb.SuggestQueriesResponse, error) +} + // AutoSuggestionClient is a client for interacting with Data QnA API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// This stateless API provides automatic suggestions for natural language +// queries for the data sources in the provided project and location. +// +// The service provides a resourceless operation suggestQueries that can be +// called to get a list of suggestions for a given incomplete query and scope +// (or list of scopes) under which the query is to be interpreted. +// +// There are two types of suggestions, ENTITY for single entity suggestions +// and TEMPLATE for full sentences. By default, both types are returned. +// +// Example Request: +// +// The service will retrieve information based on the given scope(s) and give +// suggestions based on that (e.g. “top item” for “top it” if “item” is a known +// dimension for the provided scope). type AutoSuggestionClient struct { + // The internal transport-dependent client. + internalClient internalAutoSuggestionClient + + // The call options for this service. + CallOptions *AutoSuggestionCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *AutoSuggestionClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *AutoSuggestionClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *AutoSuggestionClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// SuggestQueries gets a list of suggestions based on a prefix string. +// AutoSuggestion tolerance should be less than 1 second. +func (c *AutoSuggestionClient) SuggestQueries(ctx context.Context, req *dataqnapb.SuggestQueriesRequest, opts ...gax.CallOption) (*dataqnapb.SuggestQueriesResponse, error) { + return c.internalClient.SuggestQueries(ctx, req, opts...) +} + +// autoSuggestionGRPCClient is a client for interacting with Data QnA API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type autoSuggestionGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing AutoSuggestionClient + CallOptions **AutoSuggestionCallOptions + // The gRPC API client. autoSuggestionClient dataqnapb.AutoSuggestionServiceClient - // The call options for this service. - CallOptions *AutoSuggestionCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewAutoSuggestionClient creates a new auto suggestion service client. +// NewAutoSuggestionClient creates a new auto suggestion service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // This stateless API provides automatic suggestions for natural language // queries for the data sources in the provided project and location. @@ -95,8 +158,7 @@ type AutoSuggestionClient struct { // suggestions based on that (e.g. “top item” for “top it” if “item” is a known // dimension for the provided scope). func NewAutoSuggestionClient(ctx context.Context, opts ...option.ClientOption) (*AutoSuggestionClient, error) { - clientOpts := defaultAutoSuggestionClientOptions() - + clientOpts := defaultAutoSuggestionGRPCClientOptions() if newAutoSuggestionClientHook != nil { hookOpts, err := newAutoSuggestionClientHook(ctx, clientHookParams{}) if err != nil { @@ -114,43 +176,44 @@ func NewAutoSuggestionClient(ctx context.Context, opts ...option.ClientOption) ( if err != nil { return nil, err } - c := &AutoSuggestionClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultAutoSuggestionCallOptions(), + client := AutoSuggestionClient{CallOptions: defaultAutoSuggestionCallOptions()} + c := &autoSuggestionGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, autoSuggestionClient: dataqnapb.NewAutoSuggestionServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *AutoSuggestionClient) Connection() *grpc.ClientConn { +func (c *autoSuggestionGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *AutoSuggestionClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *AutoSuggestionClient) setGoogleClientInfo(keyval ...string) { +func (c *autoSuggestionGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// SuggestQueries gets a list of suggestions based on a prefix string. -// AutoSuggestion tolerance should be less than 1 second. -func (c *AutoSuggestionClient) SuggestQueries(ctx context.Context, req *dataqnapb.SuggestQueriesRequest, opts ...gax.CallOption) (*dataqnapb.SuggestQueriesResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *autoSuggestionGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *autoSuggestionGRPCClient) SuggestQueries(ctx context.Context, req *dataqnapb.SuggestQueriesRequest, opts ...gax.CallOption) (*dataqnapb.SuggestQueriesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 2000*time.Millisecond) defer cancel() @@ -158,7 +221,7 @@ func (c *AutoSuggestionClient) SuggestQueries(ctx context.Context, req *dataqnap } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SuggestQueries[0:len(c.CallOptions.SuggestQueries):len(c.CallOptions.SuggestQueries)], opts...) + opts = append((*c.CallOptions).SuggestQueries[0:len((*c.CallOptions).SuggestQueries):len((*c.CallOptions).SuggestQueries)], opts...) var resp *dataqnapb.SuggestQueriesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/dataqna/apiv1alpha/auto_suggestion_client_example_test.go b/dataqna/apiv1alpha/auto_suggestion_client_example_test.go index 83e90393afa0..0431108f0296 100644 --- a/dataqna/apiv1alpha/auto_suggestion_client_example_test.go +++ b/dataqna/apiv1alpha/auto_suggestion_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewAutoSuggestionClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleAutoSuggestionClient_SuggestQueries() { - // import dataqnapb "google.golang.org/genproto/googleapis/cloud/dataqna/v1alpha" - ctx := context.Background() c, err := dataqna.NewAutoSuggestionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataqnapb.SuggestQueriesRequest{ // TODO: Fill request struct fields. diff --git a/dataqna/apiv1alpha/doc.go b/dataqna/apiv1alpha/doc.go index b7a4d206e506..9fb294bf0449 100644 --- a/dataqna/apiv1alpha/doc.go +++ b/dataqna/apiv1alpha/doc.go @@ -20,6 +20,8 @@ // Data QnA is a natural language question and answer service for BigQuery // data. // +// NOTE: This package is in alpha. It is not stable, and is likely to change. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package dataqna // import "cloud.google.com/go/dataqna/apiv1alpha" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/dataqna/apiv1alpha/question_client.go b/dataqna/apiv1alpha/question_client.go index 9639756cfaa7..b9b008ef3ae1 100644 --- a/dataqna/apiv1alpha/question_client.go +++ b/dataqna/apiv1alpha/question_client.go @@ -44,7 +44,7 @@ type QuestionCallOptions struct { UpdateUserFeedback []gax.CallOption } -func defaultQuestionClientOptions() []option.ClientOption { +func defaultQuestionGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dataqna.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dataqna.mtls.googleapis.com:443"), @@ -86,27 +86,114 @@ func defaultQuestionCallOptions() *QuestionCallOptions { } } +// internalQuestionClient is an interface that defines the methods availaible from Data QnA API. +type internalQuestionClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + GetQuestion(context.Context, *dataqnapb.GetQuestionRequest, ...gax.CallOption) (*dataqnapb.Question, error) + CreateQuestion(context.Context, *dataqnapb.CreateQuestionRequest, ...gax.CallOption) (*dataqnapb.Question, error) + ExecuteQuestion(context.Context, *dataqnapb.ExecuteQuestionRequest, ...gax.CallOption) (*dataqnapb.Question, error) + GetUserFeedback(context.Context, *dataqnapb.GetUserFeedbackRequest, ...gax.CallOption) (*dataqnapb.UserFeedback, error) + UpdateUserFeedback(context.Context, *dataqnapb.UpdateUserFeedbackRequest, ...gax.CallOption) (*dataqnapb.UserFeedback, error) +} + // QuestionClient is a client for interacting with Data QnA API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service to interpret natural language queries. +// The service allows to create Question resources that are interpreted and +// are filled with one or more interpretations if the question could be +// interpreted. Once a Question resource is created and has at least one +// interpretation, an interpretation can be chosen for execution, which +// triggers a query to the backend (for BigQuery, it will create a job). +// Upon successful execution of that interpretation, backend specific +// information will be returned so that the client can retrieve the results +// from the backend. +// +// The Question resources are named projects/*/locations/*/questions/*. +// +// The Question resource has a singletion sub-resource UserFeedback named +// projects/*/locations/*/questions/*/userFeedback, which allows access to +// user feedback. type QuestionClient struct { + // The internal transport-dependent client. + internalClient internalQuestionClient + + // The call options for this service. + CallOptions *QuestionCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *QuestionClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *QuestionClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *QuestionClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// GetQuestion gets a previously created question. +func (c *QuestionClient) GetQuestion(ctx context.Context, req *dataqnapb.GetQuestionRequest, opts ...gax.CallOption) (*dataqnapb.Question, error) { + return c.internalClient.GetQuestion(ctx, req, opts...) +} + +// CreateQuestion creates a question. +func (c *QuestionClient) CreateQuestion(ctx context.Context, req *dataqnapb.CreateQuestionRequest, opts ...gax.CallOption) (*dataqnapb.Question, error) { + return c.internalClient.CreateQuestion(ctx, req, opts...) +} + +// ExecuteQuestion executes an interpretation. +func (c *QuestionClient) ExecuteQuestion(ctx context.Context, req *dataqnapb.ExecuteQuestionRequest, opts ...gax.CallOption) (*dataqnapb.Question, error) { + return c.internalClient.ExecuteQuestion(ctx, req, opts...) +} + +// GetUserFeedback gets previously created user feedback. +func (c *QuestionClient) GetUserFeedback(ctx context.Context, req *dataqnapb.GetUserFeedbackRequest, opts ...gax.CallOption) (*dataqnapb.UserFeedback, error) { + return c.internalClient.GetUserFeedback(ctx, req, opts...) +} + +// UpdateUserFeedback updates user feedback. This creates user feedback if there was none before +// (upsert). +func (c *QuestionClient) UpdateUserFeedback(ctx context.Context, req *dataqnapb.UpdateUserFeedbackRequest, opts ...gax.CallOption) (*dataqnapb.UserFeedback, error) { + return c.internalClient.UpdateUserFeedback(ctx, req, opts...) +} + +// questionGRPCClient is a client for interacting with Data QnA API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type questionGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing QuestionClient + CallOptions **QuestionCallOptions + // The gRPC API client. questionClient dataqnapb.QuestionServiceClient - // The call options for this service. - CallOptions *QuestionCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewQuestionClient creates a new question service client. +// NewQuestionClient creates a new question service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service to interpret natural language queries. // The service allows to create Question resources that are interpreted and @@ -124,8 +211,7 @@ type QuestionClient struct { // projects/*/locations/*/questions/*/userFeedback, which allows access to // user feedback. func NewQuestionClient(ctx context.Context, opts ...option.ClientOption) (*QuestionClient, error) { - clientOpts := defaultQuestionClientOptions() - + clientOpts := defaultQuestionGRPCClientOptions() if newQuestionClientHook != nil { hookOpts, err := newQuestionClientHook(ctx, clientHookParams{}) if err != nil { @@ -143,42 +229,44 @@ func NewQuestionClient(ctx context.Context, opts ...option.ClientOption) (*Quest if err != nil { return nil, err } - c := &QuestionClient{ + client := QuestionClient{CallOptions: defaultQuestionCallOptions()} + + c := &questionGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultQuestionCallOptions(), - - questionClient: dataqnapb.NewQuestionServiceClient(connPool), + questionClient: dataqnapb.NewQuestionServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *QuestionClient) Connection() *grpc.ClientConn { +func (c *questionGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *QuestionClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *QuestionClient) setGoogleClientInfo(keyval ...string) { +func (c *questionGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// GetQuestion gets a previously created question. -func (c *QuestionClient) GetQuestion(ctx context.Context, req *dataqnapb.GetQuestionRequest, opts ...gax.CallOption) (*dataqnapb.Question, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *questionGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *questionGRPCClient) GetQuestion(ctx context.Context, req *dataqnapb.GetQuestionRequest, opts ...gax.CallOption) (*dataqnapb.Question, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -186,7 +274,7 @@ func (c *QuestionClient) GetQuestion(ctx context.Context, req *dataqnapb.GetQues } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetQuestion[0:len(c.CallOptions.GetQuestion):len(c.CallOptions.GetQuestion)], opts...) + opts = append((*c.CallOptions).GetQuestion[0:len((*c.CallOptions).GetQuestion):len((*c.CallOptions).GetQuestion)], opts...) var resp *dataqnapb.Question err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -199,8 +287,7 @@ func (c *QuestionClient) GetQuestion(ctx context.Context, req *dataqnapb.GetQues return resp, nil } -// CreateQuestion creates a question. -func (c *QuestionClient) CreateQuestion(ctx context.Context, req *dataqnapb.CreateQuestionRequest, opts ...gax.CallOption) (*dataqnapb.Question, error) { +func (c *questionGRPCClient) CreateQuestion(ctx context.Context, req *dataqnapb.CreateQuestionRequest, opts ...gax.CallOption) (*dataqnapb.Question, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -208,7 +295,7 @@ func (c *QuestionClient) CreateQuestion(ctx context.Context, req *dataqnapb.Crea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateQuestion[0:len(c.CallOptions.CreateQuestion):len(c.CallOptions.CreateQuestion)], opts...) + opts = append((*c.CallOptions).CreateQuestion[0:len((*c.CallOptions).CreateQuestion):len((*c.CallOptions).CreateQuestion)], opts...) var resp *dataqnapb.Question err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -221,8 +308,7 @@ func (c *QuestionClient) CreateQuestion(ctx context.Context, req *dataqnapb.Crea return resp, nil } -// ExecuteQuestion executes an interpretation. -func (c *QuestionClient) ExecuteQuestion(ctx context.Context, req *dataqnapb.ExecuteQuestionRequest, opts ...gax.CallOption) (*dataqnapb.Question, error) { +func (c *questionGRPCClient) ExecuteQuestion(ctx context.Context, req *dataqnapb.ExecuteQuestionRequest, opts ...gax.CallOption) (*dataqnapb.Question, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -230,7 +316,7 @@ func (c *QuestionClient) ExecuteQuestion(ctx context.Context, req *dataqnapb.Exe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExecuteQuestion[0:len(c.CallOptions.ExecuteQuestion):len(c.CallOptions.ExecuteQuestion)], opts...) + opts = append((*c.CallOptions).ExecuteQuestion[0:len((*c.CallOptions).ExecuteQuestion):len((*c.CallOptions).ExecuteQuestion)], opts...) var resp *dataqnapb.Question err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -243,8 +329,7 @@ func (c *QuestionClient) ExecuteQuestion(ctx context.Context, req *dataqnapb.Exe return resp, nil } -// GetUserFeedback gets previously created user feedback. -func (c *QuestionClient) GetUserFeedback(ctx context.Context, req *dataqnapb.GetUserFeedbackRequest, opts ...gax.CallOption) (*dataqnapb.UserFeedback, error) { +func (c *questionGRPCClient) GetUserFeedback(ctx context.Context, req *dataqnapb.GetUserFeedbackRequest, opts ...gax.CallOption) (*dataqnapb.UserFeedback, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -252,7 +337,7 @@ func (c *QuestionClient) GetUserFeedback(ctx context.Context, req *dataqnapb.Get } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetUserFeedback[0:len(c.CallOptions.GetUserFeedback):len(c.CallOptions.GetUserFeedback)], opts...) + opts = append((*c.CallOptions).GetUserFeedback[0:len((*c.CallOptions).GetUserFeedback):len((*c.CallOptions).GetUserFeedback)], opts...) var resp *dataqnapb.UserFeedback err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -265,9 +350,7 @@ func (c *QuestionClient) GetUserFeedback(ctx context.Context, req *dataqnapb.Get return resp, nil } -// UpdateUserFeedback updates user feedback. This creates user feedback if there was none before -// (upsert). -func (c *QuestionClient) UpdateUserFeedback(ctx context.Context, req *dataqnapb.UpdateUserFeedbackRequest, opts ...gax.CallOption) (*dataqnapb.UserFeedback, error) { +func (c *questionGRPCClient) UpdateUserFeedback(ctx context.Context, req *dataqnapb.UpdateUserFeedbackRequest, opts ...gax.CallOption) (*dataqnapb.UserFeedback, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -275,7 +358,7 @@ func (c *QuestionClient) UpdateUserFeedback(ctx context.Context, req *dataqnapb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "user_feedback.name", url.QueryEscape(req.GetUserFeedback().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateUserFeedback[0:len(c.CallOptions.UpdateUserFeedback):len(c.CallOptions.UpdateUserFeedback)], opts...) + opts = append((*c.CallOptions).UpdateUserFeedback[0:len((*c.CallOptions).UpdateUserFeedback):len((*c.CallOptions).UpdateUserFeedback)], opts...) var resp *dataqnapb.UserFeedback err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/dataqna/apiv1alpha/question_client_example_test.go b/dataqna/apiv1alpha/question_client_example_test.go index 40112dbcdc6a..3fdec9466585 100644 --- a/dataqna/apiv1alpha/question_client_example_test.go +++ b/dataqna/apiv1alpha/question_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewQuestionClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleQuestionClient_GetQuestion() { - // import dataqnapb "google.golang.org/genproto/googleapis/cloud/dataqna/v1alpha" - ctx := context.Background() c, err := dataqna.NewQuestionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataqnapb.GetQuestionRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleQuestionClient_GetQuestion() { } func ExampleQuestionClient_CreateQuestion() { - // import dataqnapb "google.golang.org/genproto/googleapis/cloud/dataqna/v1alpha" - ctx := context.Background() c, err := dataqna.NewQuestionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataqnapb.CreateQuestionRequest{ // TODO: Fill request struct fields. @@ -74,13 +74,12 @@ func ExampleQuestionClient_CreateQuestion() { } func ExampleQuestionClient_ExecuteQuestion() { - // import dataqnapb "google.golang.org/genproto/googleapis/cloud/dataqna/v1alpha" - ctx := context.Background() c, err := dataqna.NewQuestionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataqnapb.ExecuteQuestionRequest{ // TODO: Fill request struct fields. @@ -94,13 +93,12 @@ func ExampleQuestionClient_ExecuteQuestion() { } func ExampleQuestionClient_GetUserFeedback() { - // import dataqnapb "google.golang.org/genproto/googleapis/cloud/dataqna/v1alpha" - ctx := context.Background() c, err := dataqna.NewQuestionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataqnapb.GetUserFeedbackRequest{ // TODO: Fill request struct fields. @@ -114,13 +112,12 @@ func ExampleQuestionClient_GetUserFeedback() { } func ExampleQuestionClient_UpdateUserFeedback() { - // import dataqnapb "google.golang.org/genproto/googleapis/cloud/dataqna/v1alpha" - ctx := context.Background() c, err := dataqna.NewQuestionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataqnapb.UpdateUserFeedbackRequest{ // TODO: Fill request struct fields. diff --git a/datastore/admin/apiv1/datastore_admin_client.go b/datastore/admin/apiv1/datastore_admin_client.go index 006f2dfc5d72..fb281cbfcef6 100644 --- a/datastore/admin/apiv1/datastore_admin_client.go +++ b/datastore/admin/apiv1/datastore_admin_client.go @@ -50,7 +50,7 @@ type DatastoreAdminCallOptions struct { ListIndexes []gax.CallOption } -func defaultDatastoreAdminClientOptions() []option.ClientOption { +func defaultDatastoreAdminGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("datastore.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("datastore.mtls.googleapis.com:443"), @@ -95,32 +95,225 @@ func defaultDatastoreAdminCallOptions() *DatastoreAdminCallOptions { } } +// internalDatastoreAdminClient is an interface that defines the methods availaible from Cloud Datastore API. +type internalDatastoreAdminClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ExportEntities(context.Context, *adminpb.ExportEntitiesRequest, ...gax.CallOption) (*ExportEntitiesOperation, error) + ExportEntitiesOperation(name string) *ExportEntitiesOperation + ImportEntities(context.Context, *adminpb.ImportEntitiesRequest, ...gax.CallOption) (*ImportEntitiesOperation, error) + ImportEntitiesOperation(name string) *ImportEntitiesOperation + CreateIndex(context.Context, *adminpb.CreateIndexRequest, ...gax.CallOption) (*CreateIndexOperation, error) + CreateIndexOperation(name string) *CreateIndexOperation + DeleteIndex(context.Context, *adminpb.DeleteIndexRequest, ...gax.CallOption) (*DeleteIndexOperation, error) + DeleteIndexOperation(name string) *DeleteIndexOperation + GetIndex(context.Context, *adminpb.GetIndexRequest, ...gax.CallOption) (*adminpb.Index, error) + ListIndexes(context.Context, *adminpb.ListIndexesRequest, ...gax.CallOption) *IndexIterator +} + // DatastoreAdminClient is a client for interacting with Cloud Datastore API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Google Cloud Datastore Admin API +// +// The Datastore Admin API provides several admin services for Cloud Datastore. +// +// ConceptsProject, namespace, kind, and entity as defined in the Google Cloud Datastore +// API. +// +// Operation: An Operation represents work being performed in the background. +// +// EntityFilter: Allows specifying a subset of entities in a project. This is +// specified as a combination of kinds and namespaces (either or both of which +// may be all). +// +// ServicesExport/ImportThe Export/Import service provides the ability to copy all or a subset of +// entities to/from Google Cloud Storage. +// +// Exported data may be imported into Cloud Datastore for any Google Cloud +// Platform project. It is not restricted to the export source project. It is +// possible to export from one project and then import into another. +// +// Exported data can also be loaded into Google BigQuery for analysis. +// +// Exports and imports are performed asynchronously. An Operation resource is +// created for each export/import. The state (including any errors encountered) +// of the export/import may be queried via the Operation resource. +// +// IndexThe index service manages Cloud Datastore composite indexes. +// +// Index creation and deletion are performed asynchronously. +// An Operation resource is created for each such asynchronous operation. +// The state of the operation (including any errors encountered) +// may be queried via the Operation resource. +// +// OperationThe Operations collection provides a record of actions performed for the +// specified project (including any operations in progress). Operations are not +// created directly but through calls on other collections or resources. +// +// An operation that is not yet done may be cancelled. The request to cancel is +// asynchronous and the operation may continue to run for some time after the +// request to cancel is made. +// +// An operation that is done may be deleted so that it is no longer listed as +// part of the Operation collection. +// +// ListOperations returns all pending operations, but not completed operations. +// +// Operations are created by service DatastoreAdmin, +// but are accessed via service google.longrunning.Operations. type DatastoreAdminClient struct { + // The internal transport-dependent client. + internalClient internalDatastoreAdminClient + + // The call options for this service. + CallOptions *DatastoreAdminCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *DatastoreAdminClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *DatastoreAdminClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *DatastoreAdminClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ExportEntities exports a copy of all or a subset of entities from Google Cloud Datastore +// to another storage system, such as Google Cloud Storage. Recent updates to +// entities may not be reflected in the export. The export occurs in the +// background and its progress can be monitored and managed via the +// Operation resource that is created. The output of an export may only be +// used once the associated operation is done. If an export operation is +// cancelled before completion it may leave partial data behind in Google +// Cloud Storage. +func (c *DatastoreAdminClient) ExportEntities(ctx context.Context, req *adminpb.ExportEntitiesRequest, opts ...gax.CallOption) (*ExportEntitiesOperation, error) { + return c.internalClient.ExportEntities(ctx, req, opts...) +} + +// ExportEntitiesOperation returns a new ExportEntitiesOperation from a given name. +// The name must be that of a previously created ExportEntitiesOperation, possibly from a different process. +func (c *DatastoreAdminClient) ExportEntitiesOperation(name string) *ExportEntitiesOperation { + return c.internalClient.ExportEntitiesOperation(name) +} + +// ImportEntities imports entities into Google Cloud Datastore. Existing entities with the +// same key are overwritten. The import occurs in the background and its +// progress can be monitored and managed via the Operation resource that is +// created. If an ImportEntities operation is cancelled, it is possible +// that a subset of the data has already been imported to Cloud Datastore. +func (c *DatastoreAdminClient) ImportEntities(ctx context.Context, req *adminpb.ImportEntitiesRequest, opts ...gax.CallOption) (*ImportEntitiesOperation, error) { + return c.internalClient.ImportEntities(ctx, req, opts...) +} + +// ImportEntitiesOperation returns a new ImportEntitiesOperation from a given name. +// The name must be that of a previously created ImportEntitiesOperation, possibly from a different process. +func (c *DatastoreAdminClient) ImportEntitiesOperation(name string) *ImportEntitiesOperation { + return c.internalClient.ImportEntitiesOperation(name) +} + +// CreateIndex creates the specified index. +// A newly created index’s initial state is CREATING. On completion of the +// returned google.longrunning.Operation, the state will be READY. +// If the index already exists, the call will return an ALREADY_EXISTS +// status. +// +// During index creation, the process could result in an error, in which +// case the index will move to the ERROR state. The process can be recovered +// by fixing the data that caused the error, removing the index with +// delete, then +// re-creating the index with [create] +// [google.datastore.admin.v1.DatastoreAdmin.CreateIndex]. +// +// Indexes with a single property cannot be created. +func (c *DatastoreAdminClient) CreateIndex(ctx context.Context, req *adminpb.CreateIndexRequest, opts ...gax.CallOption) (*CreateIndexOperation, error) { + return c.internalClient.CreateIndex(ctx, req, opts...) +} + +// CreateIndexOperation returns a new CreateIndexOperation from a given name. +// The name must be that of a previously created CreateIndexOperation, possibly from a different process. +func (c *DatastoreAdminClient) CreateIndexOperation(name string) *CreateIndexOperation { + return c.internalClient.CreateIndexOperation(name) +} + +// DeleteIndex deletes an existing index. +// An index can only be deleted if it is in a READY or ERROR state. On +// successful execution of the request, the index will be in a DELETING +// state. And on completion of the +// returned google.longrunning.Operation, the index will be removed. +// +// During index deletion, the process could result in an error, in which +// case the index will move to the ERROR state. The process can be recovered +// by fixing the data that caused the error, followed by calling +// delete again. +func (c *DatastoreAdminClient) DeleteIndex(ctx context.Context, req *adminpb.DeleteIndexRequest, opts ...gax.CallOption) (*DeleteIndexOperation, error) { + return c.internalClient.DeleteIndex(ctx, req, opts...) +} + +// DeleteIndexOperation returns a new DeleteIndexOperation from a given name. +// The name must be that of a previously created DeleteIndexOperation, possibly from a different process. +func (c *DatastoreAdminClient) DeleteIndexOperation(name string) *DeleteIndexOperation { + return c.internalClient.DeleteIndexOperation(name) +} + +// GetIndex gets an index. +func (c *DatastoreAdminClient) GetIndex(ctx context.Context, req *adminpb.GetIndexRequest, opts ...gax.CallOption) (*adminpb.Index, error) { + return c.internalClient.GetIndex(ctx, req, opts...) +} + +// ListIndexes lists the indexes that match the specified filters. Datastore uses an +// eventually consistent query to fetch the list of indexes and may +// occasionally return stale results. +func (c *DatastoreAdminClient) ListIndexes(ctx context.Context, req *adminpb.ListIndexesRequest, opts ...gax.CallOption) *IndexIterator { + return c.internalClient.ListIndexes(ctx, req, opts...) +} + +// datastoreAdminGRPCClient is a client for interacting with Cloud Datastore API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type datastoreAdminGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing DatastoreAdminClient + CallOptions **DatastoreAdminCallOptions + // The gRPC API client. datastoreAdminClient adminpb.DatastoreAdminClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *DatastoreAdminCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewDatastoreAdminClient creates a new datastore admin client. +// NewDatastoreAdminClient creates a new datastore admin client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Google Cloud Datastore Admin API // @@ -171,8 +364,7 @@ type DatastoreAdminClient struct { // Operations are created by service DatastoreAdmin, // but are accessed via service google.longrunning.Operations. func NewDatastoreAdminClient(ctx context.Context, opts ...option.ClientOption) (*DatastoreAdminClient, error) { - clientOpts := defaultDatastoreAdminClientOptions() - + clientOpts := defaultDatastoreAdminGRPCClientOptions() if newDatastoreAdminClientHook != nil { hookOpts, err := newDatastoreAdminClientHook(ctx, clientHookParams{}) if err != nil { @@ -190,16 +382,19 @@ func NewDatastoreAdminClient(ctx context.Context, opts ...option.ClientOption) ( if err != nil { return nil, err } - c := &DatastoreAdminClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultDatastoreAdminCallOptions(), + client := DatastoreAdminClient{CallOptions: defaultDatastoreAdminCallOptions()} + c := &datastoreAdminGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, datastoreAdminClient: adminpb.NewDatastoreAdminClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -209,40 +404,33 @@ func NewDatastoreAdminClient(ctx context.Context, opts ...option.ClientOption) ( // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *DatastoreAdminClient) Connection() *grpc.ClientConn { +func (c *datastoreAdminGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *DatastoreAdminClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *DatastoreAdminClient) setGoogleClientInfo(keyval ...string) { +func (c *datastoreAdminGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ExportEntities exports a copy of all or a subset of entities from Google Cloud Datastore -// to another storage system, such as Google Cloud Storage. Recent updates to -// entities may not be reflected in the export. The export occurs in the -// background and its progress can be monitored and managed via the -// Operation resource that is created. The output of an export may only be -// used once the associated operation is done. If an export operation is -// cancelled before completion it may leave partial data behind in Google -// Cloud Storage. -func (c *DatastoreAdminClient) ExportEntities(ctx context.Context, req *adminpb.ExportEntitiesRequest, opts ...gax.CallOption) (*ExportEntitiesOperation, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *datastoreAdminGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *datastoreAdminGRPCClient) ExportEntities(ctx context.Context, req *adminpb.ExportEntitiesRequest, opts ...gax.CallOption) (*ExportEntitiesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -250,7 +438,7 @@ func (c *DatastoreAdminClient) ExportEntities(ctx context.Context, req *adminpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportEntities[0:len(c.CallOptions.ExportEntities):len(c.CallOptions.ExportEntities)], opts...) + opts = append((*c.CallOptions).ExportEntities[0:len((*c.CallOptions).ExportEntities):len((*c.CallOptions).ExportEntities)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -261,16 +449,11 @@ func (c *DatastoreAdminClient) ExportEntities(ctx context.Context, req *adminpb. return nil, err } return &ExportEntitiesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ImportEntities imports entities into Google Cloud Datastore. Existing entities with the -// same key are overwritten. The import occurs in the background and its -// progress can be monitored and managed via the Operation resource that is -// created. If an ImportEntities operation is cancelled, it is possible -// that a subset of the data has already been imported to Cloud Datastore. -func (c *DatastoreAdminClient) ImportEntities(ctx context.Context, req *adminpb.ImportEntitiesRequest, opts ...gax.CallOption) (*ImportEntitiesOperation, error) { +func (c *datastoreAdminGRPCClient) ImportEntities(ctx context.Context, req *adminpb.ImportEntitiesRequest, opts ...gax.CallOption) (*ImportEntitiesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -278,7 +461,7 @@ func (c *DatastoreAdminClient) ImportEntities(ctx context.Context, req *adminpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportEntities[0:len(c.CallOptions.ImportEntities):len(c.CallOptions.ImportEntities)], opts...) + opts = append((*c.CallOptions).ImportEntities[0:len((*c.CallOptions).ImportEntities):len((*c.CallOptions).ImportEntities)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -289,25 +472,11 @@ func (c *DatastoreAdminClient) ImportEntities(ctx context.Context, req *adminpb. return nil, err } return &ImportEntitiesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// CreateIndex creates the specified index. -// A newly created index’s initial state is CREATING. On completion of the -// returned google.longrunning.Operation, the state will be READY. -// If the index already exists, the call will return an ALREADY_EXISTS -// status. -// -// During index creation, the process could result in an error, in which -// case the index will move to the ERROR state. The process can be recovered -// by fixing the data that caused the error, removing the index with -// delete, then -// re-creating the index with [create] -// [google.datastore.admin.v1.DatastoreAdmin.CreateIndex]. -// -// Indexes with a single property cannot be created. -func (c *DatastoreAdminClient) CreateIndex(ctx context.Context, req *adminpb.CreateIndexRequest, opts ...gax.CallOption) (*CreateIndexOperation, error) { +func (c *datastoreAdminGRPCClient) CreateIndex(ctx context.Context, req *adminpb.CreateIndexRequest, opts ...gax.CallOption) (*CreateIndexOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -315,7 +484,7 @@ func (c *DatastoreAdminClient) CreateIndex(ctx context.Context, req *adminpb.Cre } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateIndex[0:len(c.CallOptions.CreateIndex):len(c.CallOptions.CreateIndex)], opts...) + opts = append((*c.CallOptions).CreateIndex[0:len((*c.CallOptions).CreateIndex):len((*c.CallOptions).CreateIndex)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -326,21 +495,11 @@ func (c *DatastoreAdminClient) CreateIndex(ctx context.Context, req *adminpb.Cre return nil, err } return &CreateIndexOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteIndex deletes an existing index. -// An index can only be deleted if it is in a READY or ERROR state. On -// successful execution of the request, the index will be in a DELETING -// state. And on completion of the -// returned google.longrunning.Operation, the index will be removed. -// -// During index deletion, the process could result in an error, in which -// case the index will move to the ERROR state. The process can be recovered -// by fixing the data that caused the error, followed by calling -// delete again. -func (c *DatastoreAdminClient) DeleteIndex(ctx context.Context, req *adminpb.DeleteIndexRequest, opts ...gax.CallOption) (*DeleteIndexOperation, error) { +func (c *datastoreAdminGRPCClient) DeleteIndex(ctx context.Context, req *adminpb.DeleteIndexRequest, opts ...gax.CallOption) (*DeleteIndexOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -348,7 +507,7 @@ func (c *DatastoreAdminClient) DeleteIndex(ctx context.Context, req *adminpb.Del } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "index_id", url.QueryEscape(req.GetIndexId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteIndex[0:len(c.CallOptions.DeleteIndex):len(c.CallOptions.DeleteIndex)], opts...) + opts = append((*c.CallOptions).DeleteIndex[0:len((*c.CallOptions).DeleteIndex):len((*c.CallOptions).DeleteIndex)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -359,12 +518,11 @@ func (c *DatastoreAdminClient) DeleteIndex(ctx context.Context, req *adminpb.Del return nil, err } return &DeleteIndexOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetIndex gets an index. -func (c *DatastoreAdminClient) GetIndex(ctx context.Context, req *adminpb.GetIndexRequest, opts ...gax.CallOption) (*adminpb.Index, error) { +func (c *datastoreAdminGRPCClient) GetIndex(ctx context.Context, req *adminpb.GetIndexRequest, opts ...gax.CallOption) (*adminpb.Index, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -372,7 +530,7 @@ func (c *DatastoreAdminClient) GetIndex(ctx context.Context, req *adminpb.GetInd } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "index_id", url.QueryEscape(req.GetIndexId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIndex[0:len(c.CallOptions.GetIndex):len(c.CallOptions.GetIndex)], opts...) + opts = append((*c.CallOptions).GetIndex[0:len((*c.CallOptions).GetIndex):len((*c.CallOptions).GetIndex)], opts...) var resp *adminpb.Index err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -385,13 +543,10 @@ func (c *DatastoreAdminClient) GetIndex(ctx context.Context, req *adminpb.GetInd return resp, nil } -// ListIndexes lists the indexes that match the specified filters. Datastore uses an -// eventually consistent query to fetch the list of indexes and may -// occasionally return stale results. -func (c *DatastoreAdminClient) ListIndexes(ctx context.Context, req *adminpb.ListIndexesRequest, opts ...gax.CallOption) *IndexIterator { +func (c *datastoreAdminGRPCClient) ListIndexes(ctx context.Context, req *adminpb.ListIndexesRequest, opts ...gax.CallOption) *IndexIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListIndexes[0:len(c.CallOptions.ListIndexes):len(c.CallOptions.ListIndexes)], opts...) + opts = append((*c.CallOptions).ListIndexes[0:len((*c.CallOptions).ListIndexes):len((*c.CallOptions).ListIndexes)], opts...) it := &IndexIterator{} req = proto.Clone(req).(*adminpb.ListIndexesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*adminpb.Index, string, error) { @@ -435,9 +590,9 @@ type CreateIndexOperation struct { // CreateIndexOperation returns a new CreateIndexOperation from a given name. // The name must be that of a previously created CreateIndexOperation, possibly from a different process. -func (c *DatastoreAdminClient) CreateIndexOperation(name string) *CreateIndexOperation { +func (c *datastoreAdminGRPCClient) CreateIndexOperation(name string) *CreateIndexOperation { return &CreateIndexOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -504,9 +659,9 @@ type DeleteIndexOperation struct { // DeleteIndexOperation returns a new DeleteIndexOperation from a given name. // The name must be that of a previously created DeleteIndexOperation, possibly from a different process. -func (c *DatastoreAdminClient) DeleteIndexOperation(name string) *DeleteIndexOperation { +func (c *datastoreAdminGRPCClient) DeleteIndexOperation(name string) *DeleteIndexOperation { return &DeleteIndexOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -573,9 +728,9 @@ type ExportEntitiesOperation struct { // ExportEntitiesOperation returns a new ExportEntitiesOperation from a given name. // The name must be that of a previously created ExportEntitiesOperation, possibly from a different process. -func (c *DatastoreAdminClient) ExportEntitiesOperation(name string) *ExportEntitiesOperation { +func (c *datastoreAdminGRPCClient) ExportEntitiesOperation(name string) *ExportEntitiesOperation { return &ExportEntitiesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -642,9 +797,9 @@ type ImportEntitiesOperation struct { // ImportEntitiesOperation returns a new ImportEntitiesOperation from a given name. // The name must be that of a previously created ImportEntitiesOperation, possibly from a different process. -func (c *DatastoreAdminClient) ImportEntitiesOperation(name string) *ImportEntitiesOperation { +func (c *datastoreAdminGRPCClient) ImportEntitiesOperation(name string) *ImportEntitiesOperation { return &ImportEntitiesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/datastore/admin/apiv1/datastore_admin_client_example_test.go b/datastore/admin/apiv1/datastore_admin_client_example_test.go index ef3a9614a195..c463f80acccc 100644 --- a/datastore/admin/apiv1/datastore_admin_client_example_test.go +++ b/datastore/admin/apiv1/datastore_admin_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewDatastoreAdminClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleDatastoreAdminClient_ExportEntities() { - // import adminpb "google.golang.org/genproto/googleapis/datastore/admin/v1" - ctx := context.Background() c, err := admin.NewDatastoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ExportEntitiesRequest{ // TODO: Fill request struct fields. @@ -60,13 +61,12 @@ func ExampleDatastoreAdminClient_ExportEntities() { } func ExampleDatastoreAdminClient_ImportEntities() { - // import adminpb "google.golang.org/genproto/googleapis/datastore/admin/v1" - ctx := context.Background() c, err := admin.NewDatastoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ImportEntitiesRequest{ // TODO: Fill request struct fields. @@ -83,13 +83,12 @@ func ExampleDatastoreAdminClient_ImportEntities() { } func ExampleDatastoreAdminClient_CreateIndex() { - // import adminpb "google.golang.org/genproto/googleapis/datastore/admin/v1" - ctx := context.Background() c, err := admin.NewDatastoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.CreateIndexRequest{ // TODO: Fill request struct fields. @@ -108,13 +107,12 @@ func ExampleDatastoreAdminClient_CreateIndex() { } func ExampleDatastoreAdminClient_DeleteIndex() { - // import adminpb "google.golang.org/genproto/googleapis/datastore/admin/v1" - ctx := context.Background() c, err := admin.NewDatastoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteIndexRequest{ // TODO: Fill request struct fields. @@ -133,13 +131,12 @@ func ExampleDatastoreAdminClient_DeleteIndex() { } func ExampleDatastoreAdminClient_GetIndex() { - // import adminpb "google.golang.org/genproto/googleapis/datastore/admin/v1" - ctx := context.Background() c, err := admin.NewDatastoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetIndexRequest{ // TODO: Fill request struct fields. @@ -153,14 +150,12 @@ func ExampleDatastoreAdminClient_GetIndex() { } func ExampleDatastoreAdminClient_ListIndexes() { - // import adminpb "google.golang.org/genproto/googleapis/datastore/admin/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewDatastoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListIndexesRequest{ // TODO: Fill request struct fields. diff --git a/datastore/admin/apiv1/doc.go b/datastore/admin/apiv1/doc.go index 2eeb1da6b4d9..669b91dda08f 100644 --- a/datastore/admin/apiv1/doc.go +++ b/datastore/admin/apiv1/doc.go @@ -20,6 +20,8 @@ // Accesses the schemaless NoSQL database to provide fully managed, robust, // scalable storage for your application. // +// NOTE: This package is in alpha. It is not stable, and is likely to change. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package admin // import "cloud.google.com/go/datastore/admin/apiv1" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/datastore/go.mod b/datastore/go.mod index 4ecc20632cf3..e488c429bffd 100644 --- a/datastore/go.mod +++ b/datastore/go.mod @@ -7,8 +7,8 @@ require ( github.com/golang/protobuf v1.5.2 github.com/google/go-cmp v0.5.5 github.com/googleapis/gax-go/v2 v2.0.5 - google.golang.org/api v0.46.0 - google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a + google.golang.org/api v0.47.0 + google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d google.golang.org/grpc v1.37.1 google.golang.org/protobuf v1.26.0 ) diff --git a/datastore/go.sum b/datastore/go.sum index 21f3a0377fc0..259241ea7f17 100644 --- a/datastore/go.sum +++ b/datastore/go.sum @@ -144,6 +144,7 @@ github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -179,8 +180,9 @@ golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5 h1:2M3HP5CCK1Si9FQhwnzYhXdG6DXeebvUHFpre8QvbyI= golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 h1:VLliZ0d+/avPrXXH+OakdXhpJuEoBZuwh1m2j7U6Iug= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= @@ -190,8 +192,9 @@ golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.1 h1:Kvvh58BN8Y9/lBi7hTekvtMpm07eUZ0ck5pRHpsMWrY= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -225,6 +228,7 @@ golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420 h1:a8jGStKg0XqKDlKqjLrXn0ioF5MH36pT7Z0BRTqLhbk= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -238,8 +242,8 @@ golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210427180440-81ed05c6b58c h1:SgVl/sCtkicsS7psKkje4H9YtjdEl3xsYh7N+5TDHqY= -golang.org/x/oauth2 v0.0.0-20210427180440-81ed05c6b58c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c h1:pkQiBZBvdos9qq4wBAHqlzuZHEXo07pqV06ef90u1WI= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -286,9 +290,11 @@ golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210503080704-8803ae5d1324 h1:pAwJxDByZctfPwzlNGrDN2BQLsdPb9NkhoTJtUkAO28= -golang.org/x/sys v0.0.0-20210503080704-8803ae5d1324/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015 h1:hZR0X1kPW+nwyJ9xRxqZk1vx5RUObAPBdKVvXPDUH/E= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -347,8 +353,9 @@ golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.0 h1:po9/4sTYwZU9lPhi1tOrb4hCv3qrhiQ77LZfGa2OjwY= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.1 h1:wGiQel/hW0NnEkJUk8lbzkX2gFJU6PFxf1v5OlCfuOs= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -375,8 +382,8 @@ google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34q google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= -google.golang.org/api v0.46.0 h1:jkDWHOBIoNSD0OQpq4rtBVu+Rh325MPjXG1rakAp8JU= -google.golang.org/api v0.46.0/go.mod h1:ceL4oozhkAiTID8XMmJBsIxID/9wMXJVVFXPg4ylg3I= +google.golang.org/api v0.47.0 h1:sQLWZQvP6jPGIP4JGPkJu4zHswrv81iobiyszr3b/0I= +google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -424,9 +431,9 @@ google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= -google.golang.org/genproto v0.0.0-20210429181445-86c259c2b4ab/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= -google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a h1:VA0wtJaR+W1I11P2f535J7D/YxyvEFMTMvcmyeZ9FBE= -google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d h1:bRz6UmsZEz/CzoTjUDp4ZcdguhSWi6CyU299wMQBpZU= +google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= @@ -445,7 +452,6 @@ google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA5 google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.37.1 h1:ARnQJNWxGyYJpdf/JXscNlQr/uv607ZPU9Z7ogHi+iI= google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= diff --git a/debugger/apiv2/controller2_client.go b/debugger/apiv2/controller2_client.go index 2b40270662e4..4b597052b50b 100644 --- a/debugger/apiv2/controller2_client.go +++ b/debugger/apiv2/controller2_client.go @@ -42,7 +42,7 @@ type Controller2CallOptions struct { UpdateActiveBreakpoint []gax.CallOption } -func defaultController2ClientOptions() []option.ClientOption { +func defaultController2GRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("clouddebugger.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("clouddebugger.mtls.googleapis.com:443"), @@ -84,27 +84,134 @@ func defaultController2CallOptions() *Controller2CallOptions { } } +// internalController2Client is an interface that defines the methods availaible from Stackdriver Debugger API. +type internalController2Client interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + RegisterDebuggee(context.Context, *clouddebuggerpb.RegisterDebuggeeRequest, ...gax.CallOption) (*clouddebuggerpb.RegisterDebuggeeResponse, error) + ListActiveBreakpoints(context.Context, *clouddebuggerpb.ListActiveBreakpointsRequest, ...gax.CallOption) (*clouddebuggerpb.ListActiveBreakpointsResponse, error) + UpdateActiveBreakpoint(context.Context, *clouddebuggerpb.UpdateActiveBreakpointRequest, ...gax.CallOption) (*clouddebuggerpb.UpdateActiveBreakpointResponse, error) +} + // Controller2Client is a client for interacting with Stackdriver Debugger API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The Controller service provides the API for orchestrating a collection of +// debugger agents to perform debugging tasks. These agents are each attached +// to a process of an application which may include one or more replicas. +// +// The debugger agents register with the Controller to identify the application +// being debugged, the Debuggee. All agents that register with the same data, +// represent the same Debuggee, and are assigned the same debuggee_id. +// +// The debugger agents call the Controller to retrieve the list of active +// Breakpoints. Agents with the same debuggee_id get the same breakpoints +// list. An agent that can fulfill the breakpoint request updates the +// Controller with the breakpoint result. The controller selects the first +// result received and discards the rest of the results. +// Agents that poll again for active breakpoints will no longer have +// the completed breakpoint in the list and should remove that breakpoint from +// their attached process. +// +// The Controller service does not provide a way to retrieve the results of +// a completed breakpoint. This functionality is available using the Debugger +// service. type Controller2Client struct { + // The internal transport-dependent client. + internalClient internalController2Client + + // The call options for this service. + CallOptions *Controller2CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Controller2Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Controller2Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Controller2Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// RegisterDebuggee registers the debuggee with the controller service. +// +// All agents attached to the same application must call this method with +// exactly the same request content to get back the same stable debuggee_id. +// Agents should call this method again whenever google.rpc.Code.NOT_FOUND +// is returned from any controller method. +// +// This protocol allows the controller service to disable debuggees, recover +// from data loss, or change the debuggee_id format. Agents must handle +// debuggee_id value changing upon re-registration. +func (c *Controller2Client) RegisterDebuggee(ctx context.Context, req *clouddebuggerpb.RegisterDebuggeeRequest, opts ...gax.CallOption) (*clouddebuggerpb.RegisterDebuggeeResponse, error) { + return c.internalClient.RegisterDebuggee(ctx, req, opts...) +} + +// ListActiveBreakpoints returns the list of all active breakpoints for the debuggee. +// +// The breakpoint specification (location, condition, and expressions +// fields) is semantically immutable, although the field values may +// change. For example, an agent may update the location line number +// to reflect the actual line where the breakpoint was set, but this +// doesn’t change the breakpoint semantics. +// +// This means that an agent does not need to check if a breakpoint has changed +// when it encounters the same breakpoint on a successive call. +// Moreover, an agent should remember the breakpoints that are completed +// until the controller removes them from the active list to avoid +// setting those breakpoints again. +func (c *Controller2Client) ListActiveBreakpoints(ctx context.Context, req *clouddebuggerpb.ListActiveBreakpointsRequest, opts ...gax.CallOption) (*clouddebuggerpb.ListActiveBreakpointsResponse, error) { + return c.internalClient.ListActiveBreakpoints(ctx, req, opts...) +} + +// UpdateActiveBreakpoint updates the breakpoint state or mutable fields. +// The entire Breakpoint message must be sent back to the controller service. +// +// Updates to active breakpoint fields are only allowed if the new value +// does not change the breakpoint specification. Updates to the location, +// condition and expressions fields should not alter the breakpoint +// semantics. These may only make changes such as canonicalizing a value +// or snapping the location to the correct line of code. +func (c *Controller2Client) UpdateActiveBreakpoint(ctx context.Context, req *clouddebuggerpb.UpdateActiveBreakpointRequest, opts ...gax.CallOption) (*clouddebuggerpb.UpdateActiveBreakpointResponse, error) { + return c.internalClient.UpdateActiveBreakpoint(ctx, req, opts...) +} + +// controller2GRPCClient is a client for interacting with Stackdriver Debugger API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type controller2GRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Controller2Client + CallOptions **Controller2CallOptions + // The gRPC API client. controller2Client clouddebuggerpb.Controller2Client - // The call options for this service. - CallOptions *Controller2CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewController2Client creates a new controller2 client. +// NewController2Client creates a new controller2 client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The Controller service provides the API for orchestrating a collection of // debugger agents to perform debugging tasks. These agents are each attached @@ -127,8 +234,7 @@ type Controller2Client struct { // a completed breakpoint. This functionality is available using the Debugger // service. func NewController2Client(ctx context.Context, opts ...option.ClientOption) (*Controller2Client, error) { - clientOpts := defaultController2ClientOptions() - + clientOpts := defaultController2GRPCClientOptions() if newController2ClientHook != nil { hookOpts, err := newController2ClientHook(ctx, clientHookParams{}) if err != nil { @@ -146,58 +252,51 @@ func NewController2Client(ctx context.Context, opts ...option.ClientOption) (*Co if err != nil { return nil, err } - c := &Controller2Client{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultController2CallOptions(), + client := Controller2Client{CallOptions: defaultController2CallOptions()} + c := &controller2GRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, controller2Client: clouddebuggerpb.NewController2Client(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Controller2Client) Connection() *grpc.ClientConn { +func (c *controller2GRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Controller2Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Controller2Client) setGoogleClientInfo(keyval ...string) { +func (c *controller2GRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// RegisterDebuggee registers the debuggee with the controller service. -// -// All agents attached to the same application must call this method with -// exactly the same request content to get back the same stable debuggee_id. -// Agents should call this method again whenever google.rpc.Code.NOT_FOUND -// is returned from any controller method. -// -// This protocol allows the controller service to disable debuggees, recover -// from data loss, or change the debuggee_id format. Agents must handle -// debuggee_id value changing upon re-registration. -func (c *Controller2Client) RegisterDebuggee(ctx context.Context, req *clouddebuggerpb.RegisterDebuggeeRequest, opts ...gax.CallOption) (*clouddebuggerpb.RegisterDebuggeeResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *controller2GRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *controller2GRPCClient) RegisterDebuggee(ctx context.Context, req *clouddebuggerpb.RegisterDebuggeeRequest, opts ...gax.CallOption) (*clouddebuggerpb.RegisterDebuggeeResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.RegisterDebuggee[0:len(c.CallOptions.RegisterDebuggee):len(c.CallOptions.RegisterDebuggee)], opts...) + opts = append((*c.CallOptions).RegisterDebuggee[0:len((*c.CallOptions).RegisterDebuggee):len((*c.CallOptions).RegisterDebuggee)], opts...) var resp *clouddebuggerpb.RegisterDebuggeeResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -210,20 +309,7 @@ func (c *Controller2Client) RegisterDebuggee(ctx context.Context, req *clouddebu return resp, nil } -// ListActiveBreakpoints returns the list of all active breakpoints for the debuggee. -// -// The breakpoint specification (location, condition, and expressions -// fields) is semantically immutable, although the field values may -// change. For example, an agent may update the location line number -// to reflect the actual line where the breakpoint was set, but this -// doesn’t change the breakpoint semantics. -// -// This means that an agent does not need to check if a breakpoint has changed -// when it encounters the same breakpoint on a successive call. -// Moreover, an agent should remember the breakpoints that are completed -// until the controller removes them from the active list to avoid -// setting those breakpoints again. -func (c *Controller2Client) ListActiveBreakpoints(ctx context.Context, req *clouddebuggerpb.ListActiveBreakpointsRequest, opts ...gax.CallOption) (*clouddebuggerpb.ListActiveBreakpointsResponse, error) { +func (c *controller2GRPCClient) ListActiveBreakpoints(ctx context.Context, req *clouddebuggerpb.ListActiveBreakpointsRequest, opts ...gax.CallOption) (*clouddebuggerpb.ListActiveBreakpointsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -231,7 +317,7 @@ func (c *Controller2Client) ListActiveBreakpoints(ctx context.Context, req *clou } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "debuggee_id", url.QueryEscape(req.GetDebuggeeId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListActiveBreakpoints[0:len(c.CallOptions.ListActiveBreakpoints):len(c.CallOptions.ListActiveBreakpoints)], opts...) + opts = append((*c.CallOptions).ListActiveBreakpoints[0:len((*c.CallOptions).ListActiveBreakpoints):len((*c.CallOptions).ListActiveBreakpoints)], opts...) var resp *clouddebuggerpb.ListActiveBreakpointsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -244,15 +330,7 @@ func (c *Controller2Client) ListActiveBreakpoints(ctx context.Context, req *clou return resp, nil } -// UpdateActiveBreakpoint updates the breakpoint state or mutable fields. -// The entire Breakpoint message must be sent back to the controller service. -// -// Updates to active breakpoint fields are only allowed if the new value -// does not change the breakpoint specification. Updates to the location, -// condition and expressions fields should not alter the breakpoint -// semantics. These may only make changes such as canonicalizing a value -// or snapping the location to the correct line of code. -func (c *Controller2Client) UpdateActiveBreakpoint(ctx context.Context, req *clouddebuggerpb.UpdateActiveBreakpointRequest, opts ...gax.CallOption) (*clouddebuggerpb.UpdateActiveBreakpointResponse, error) { +func (c *controller2GRPCClient) UpdateActiveBreakpoint(ctx context.Context, req *clouddebuggerpb.UpdateActiveBreakpointRequest, opts ...gax.CallOption) (*clouddebuggerpb.UpdateActiveBreakpointResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -260,7 +338,7 @@ func (c *Controller2Client) UpdateActiveBreakpoint(ctx context.Context, req *clo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "debuggee_id", url.QueryEscape(req.GetDebuggeeId()), "breakpoint.id", url.QueryEscape(req.GetBreakpoint().GetId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateActiveBreakpoint[0:len(c.CallOptions.UpdateActiveBreakpoint):len(c.CallOptions.UpdateActiveBreakpoint)], opts...) + opts = append((*c.CallOptions).UpdateActiveBreakpoint[0:len((*c.CallOptions).UpdateActiveBreakpoint):len((*c.CallOptions).UpdateActiveBreakpoint)], opts...) var resp *clouddebuggerpb.UpdateActiveBreakpointResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/debugger/apiv2/controller2_client_example_test.go b/debugger/apiv2/controller2_client_example_test.go index 58d57d0e43ee..d876844e6d14 100644 --- a/debugger/apiv2/controller2_client_example_test.go +++ b/debugger/apiv2/controller2_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewController2Client() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleController2Client_RegisterDebuggee() { - // import clouddebuggerpb "google.golang.org/genproto/googleapis/devtools/clouddebugger/v2" - ctx := context.Background() c, err := debugger.NewController2Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddebuggerpb.RegisterDebuggeeRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleController2Client_RegisterDebuggee() { } func ExampleController2Client_ListActiveBreakpoints() { - // import clouddebuggerpb "google.golang.org/genproto/googleapis/devtools/clouddebugger/v2" - ctx := context.Background() c, err := debugger.NewController2Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddebuggerpb.ListActiveBreakpointsRequest{ // TODO: Fill request struct fields. @@ -74,13 +74,12 @@ func ExampleController2Client_ListActiveBreakpoints() { } func ExampleController2Client_UpdateActiveBreakpoint() { - // import clouddebuggerpb "google.golang.org/genproto/googleapis/devtools/clouddebugger/v2" - ctx := context.Background() c, err := debugger.NewController2Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddebuggerpb.UpdateActiveBreakpointRequest{ // TODO: Fill request struct fields. diff --git a/debugger/apiv2/debugger2_client.go b/debugger/apiv2/debugger2_client.go index be3253a004b5..4141f3a7e7cd 100644 --- a/debugger/apiv2/debugger2_client.go +++ b/debugger/apiv2/debugger2_client.go @@ -44,7 +44,7 @@ type Debugger2CallOptions struct { ListDebuggees []gax.CallOption } -func defaultDebugger2ClientOptions() []option.ClientOption { +func defaultDebugger2GRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("clouddebugger.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("clouddebugger.mtls.googleapis.com:443"), @@ -110,27 +110,110 @@ func defaultDebugger2CallOptions() *Debugger2CallOptions { } } +// internalDebugger2Client is an interface that defines the methods availaible from Stackdriver Debugger API. +type internalDebugger2Client interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + SetBreakpoint(context.Context, *clouddebuggerpb.SetBreakpointRequest, ...gax.CallOption) (*clouddebuggerpb.SetBreakpointResponse, error) + GetBreakpoint(context.Context, *clouddebuggerpb.GetBreakpointRequest, ...gax.CallOption) (*clouddebuggerpb.GetBreakpointResponse, error) + DeleteBreakpoint(context.Context, *clouddebuggerpb.DeleteBreakpointRequest, ...gax.CallOption) error + ListBreakpoints(context.Context, *clouddebuggerpb.ListBreakpointsRequest, ...gax.CallOption) (*clouddebuggerpb.ListBreakpointsResponse, error) + ListDebuggees(context.Context, *clouddebuggerpb.ListDebuggeesRequest, ...gax.CallOption) (*clouddebuggerpb.ListDebuggeesResponse, error) +} + // Debugger2Client is a client for interacting with Stackdriver Debugger API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The Debugger service provides the API that allows users to collect run-time +// information from a running application, without stopping or slowing it down +// and without modifying its state. An application may include one or +// more replicated processes performing the same work. +// +// A debugged application is represented using the Debuggee concept. The +// Debugger service provides a way to query for available debuggees, but does +// not provide a way to create one. A debuggee is created using the Controller +// service, usually by running a debugger agent with the application. +// +// The Debugger service enables the client to set one or more Breakpoints on a +// Debuggee and collect the results of the set Breakpoints. type Debugger2Client struct { + // The internal transport-dependent client. + internalClient internalDebugger2Client + + // The call options for this service. + CallOptions *Debugger2CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Debugger2Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Debugger2Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Debugger2Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// SetBreakpoint sets the breakpoint to the debuggee. +func (c *Debugger2Client) SetBreakpoint(ctx context.Context, req *clouddebuggerpb.SetBreakpointRequest, opts ...gax.CallOption) (*clouddebuggerpb.SetBreakpointResponse, error) { + return c.internalClient.SetBreakpoint(ctx, req, opts...) +} + +// GetBreakpoint gets breakpoint information. +func (c *Debugger2Client) GetBreakpoint(ctx context.Context, req *clouddebuggerpb.GetBreakpointRequest, opts ...gax.CallOption) (*clouddebuggerpb.GetBreakpointResponse, error) { + return c.internalClient.GetBreakpoint(ctx, req, opts...) +} + +// DeleteBreakpoint deletes the breakpoint from the debuggee. +func (c *Debugger2Client) DeleteBreakpoint(ctx context.Context, req *clouddebuggerpb.DeleteBreakpointRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteBreakpoint(ctx, req, opts...) +} + +// ListBreakpoints lists all breakpoints for the debuggee. +func (c *Debugger2Client) ListBreakpoints(ctx context.Context, req *clouddebuggerpb.ListBreakpointsRequest, opts ...gax.CallOption) (*clouddebuggerpb.ListBreakpointsResponse, error) { + return c.internalClient.ListBreakpoints(ctx, req, opts...) +} + +// ListDebuggees lists all the debuggees that the user has access to. +func (c *Debugger2Client) ListDebuggees(ctx context.Context, req *clouddebuggerpb.ListDebuggeesRequest, opts ...gax.CallOption) (*clouddebuggerpb.ListDebuggeesResponse, error) { + return c.internalClient.ListDebuggees(ctx, req, opts...) +} + +// debugger2GRPCClient is a client for interacting with Stackdriver Debugger API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type debugger2GRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Debugger2Client + CallOptions **Debugger2CallOptions + // The gRPC API client. debugger2Client clouddebuggerpb.Debugger2Client - // The call options for this service. - CallOptions *Debugger2CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewDebugger2Client creates a new debugger2 client. +// NewDebugger2Client creates a new debugger2 client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The Debugger service provides the API that allows users to collect run-time // information from a running application, without stopping or slowing it down @@ -145,8 +228,7 @@ type Debugger2Client struct { // The Debugger service enables the client to set one or more Breakpoints on a // Debuggee and collect the results of the set Breakpoints. func NewDebugger2Client(ctx context.Context, opts ...option.ClientOption) (*Debugger2Client, error) { - clientOpts := defaultDebugger2ClientOptions() - + clientOpts := defaultDebugger2GRPCClientOptions() if newDebugger2ClientHook != nil { hookOpts, err := newDebugger2ClientHook(ctx, clientHookParams{}) if err != nil { @@ -164,42 +246,44 @@ func NewDebugger2Client(ctx context.Context, opts ...option.ClientOption) (*Debu if err != nil { return nil, err } - c := &Debugger2Client{ + client := Debugger2Client{CallOptions: defaultDebugger2CallOptions()} + + c := &debugger2GRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultDebugger2CallOptions(), - - debugger2Client: clouddebuggerpb.NewDebugger2Client(connPool), + debugger2Client: clouddebuggerpb.NewDebugger2Client(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Debugger2Client) Connection() *grpc.ClientConn { +func (c *debugger2GRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Debugger2Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Debugger2Client) setGoogleClientInfo(keyval ...string) { +func (c *debugger2GRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// SetBreakpoint sets the breakpoint to the debuggee. -func (c *Debugger2Client) SetBreakpoint(ctx context.Context, req *clouddebuggerpb.SetBreakpointRequest, opts ...gax.CallOption) (*clouddebuggerpb.SetBreakpointResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *debugger2GRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *debugger2GRPCClient) SetBreakpoint(ctx context.Context, req *clouddebuggerpb.SetBreakpointRequest, opts ...gax.CallOption) (*clouddebuggerpb.SetBreakpointResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -207,7 +291,7 @@ func (c *Debugger2Client) SetBreakpoint(ctx context.Context, req *clouddebuggerp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "debuggee_id", url.QueryEscape(req.GetDebuggeeId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetBreakpoint[0:len(c.CallOptions.SetBreakpoint):len(c.CallOptions.SetBreakpoint)], opts...) + opts = append((*c.CallOptions).SetBreakpoint[0:len((*c.CallOptions).SetBreakpoint):len((*c.CallOptions).SetBreakpoint)], opts...) var resp *clouddebuggerpb.SetBreakpointResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -220,8 +304,7 @@ func (c *Debugger2Client) SetBreakpoint(ctx context.Context, req *clouddebuggerp return resp, nil } -// GetBreakpoint gets breakpoint information. -func (c *Debugger2Client) GetBreakpoint(ctx context.Context, req *clouddebuggerpb.GetBreakpointRequest, opts ...gax.CallOption) (*clouddebuggerpb.GetBreakpointResponse, error) { +func (c *debugger2GRPCClient) GetBreakpoint(ctx context.Context, req *clouddebuggerpb.GetBreakpointRequest, opts ...gax.CallOption) (*clouddebuggerpb.GetBreakpointResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -229,7 +312,7 @@ func (c *Debugger2Client) GetBreakpoint(ctx context.Context, req *clouddebuggerp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "debuggee_id", url.QueryEscape(req.GetDebuggeeId()), "breakpoint_id", url.QueryEscape(req.GetBreakpointId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetBreakpoint[0:len(c.CallOptions.GetBreakpoint):len(c.CallOptions.GetBreakpoint)], opts...) + opts = append((*c.CallOptions).GetBreakpoint[0:len((*c.CallOptions).GetBreakpoint):len((*c.CallOptions).GetBreakpoint)], opts...) var resp *clouddebuggerpb.GetBreakpointResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -242,8 +325,7 @@ func (c *Debugger2Client) GetBreakpoint(ctx context.Context, req *clouddebuggerp return resp, nil } -// DeleteBreakpoint deletes the breakpoint from the debuggee. -func (c *Debugger2Client) DeleteBreakpoint(ctx context.Context, req *clouddebuggerpb.DeleteBreakpointRequest, opts ...gax.CallOption) error { +func (c *debugger2GRPCClient) DeleteBreakpoint(ctx context.Context, req *clouddebuggerpb.DeleteBreakpointRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -251,7 +333,7 @@ func (c *Debugger2Client) DeleteBreakpoint(ctx context.Context, req *clouddebugg } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "debuggee_id", url.QueryEscape(req.GetDebuggeeId()), "breakpoint_id", url.QueryEscape(req.GetBreakpointId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteBreakpoint[0:len(c.CallOptions.DeleteBreakpoint):len(c.CallOptions.DeleteBreakpoint)], opts...) + opts = append((*c.CallOptions).DeleteBreakpoint[0:len((*c.CallOptions).DeleteBreakpoint):len((*c.CallOptions).DeleteBreakpoint)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.debugger2Client.DeleteBreakpoint(ctx, req, settings.GRPC...) @@ -260,8 +342,7 @@ func (c *Debugger2Client) DeleteBreakpoint(ctx context.Context, req *clouddebugg return err } -// ListBreakpoints lists all breakpoints for the debuggee. -func (c *Debugger2Client) ListBreakpoints(ctx context.Context, req *clouddebuggerpb.ListBreakpointsRequest, opts ...gax.CallOption) (*clouddebuggerpb.ListBreakpointsResponse, error) { +func (c *debugger2GRPCClient) ListBreakpoints(ctx context.Context, req *clouddebuggerpb.ListBreakpointsRequest, opts ...gax.CallOption) (*clouddebuggerpb.ListBreakpointsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -269,7 +350,7 @@ func (c *Debugger2Client) ListBreakpoints(ctx context.Context, req *clouddebugge } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "debuggee_id", url.QueryEscape(req.GetDebuggeeId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListBreakpoints[0:len(c.CallOptions.ListBreakpoints):len(c.CallOptions.ListBreakpoints)], opts...) + opts = append((*c.CallOptions).ListBreakpoints[0:len((*c.CallOptions).ListBreakpoints):len((*c.CallOptions).ListBreakpoints)], opts...) var resp *clouddebuggerpb.ListBreakpointsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -282,15 +363,14 @@ func (c *Debugger2Client) ListBreakpoints(ctx context.Context, req *clouddebugge return resp, nil } -// ListDebuggees lists all the debuggees that the user has access to. -func (c *Debugger2Client) ListDebuggees(ctx context.Context, req *clouddebuggerpb.ListDebuggeesRequest, opts ...gax.CallOption) (*clouddebuggerpb.ListDebuggeesResponse, error) { +func (c *debugger2GRPCClient) ListDebuggees(ctx context.Context, req *clouddebuggerpb.ListDebuggeesRequest, opts ...gax.CallOption) (*clouddebuggerpb.ListDebuggeesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListDebuggees[0:len(c.CallOptions.ListDebuggees):len(c.CallOptions.ListDebuggees)], opts...) + opts = append((*c.CallOptions).ListDebuggees[0:len((*c.CallOptions).ListDebuggees):len((*c.CallOptions).ListDebuggees)], opts...) var resp *clouddebuggerpb.ListDebuggeesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/debugger/apiv2/debugger2_client_example_test.go b/debugger/apiv2/debugger2_client_example_test.go index 0ea81e723c1f..a7cbcf0e7633 100644 --- a/debugger/apiv2/debugger2_client_example_test.go +++ b/debugger/apiv2/debugger2_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewDebugger2Client() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleDebugger2Client_SetBreakpoint() { - // import clouddebuggerpb "google.golang.org/genproto/googleapis/devtools/clouddebugger/v2" - ctx := context.Background() c, err := debugger.NewDebugger2Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddebuggerpb.SetBreakpointRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleDebugger2Client_SetBreakpoint() { } func ExampleDebugger2Client_GetBreakpoint() { - // import clouddebuggerpb "google.golang.org/genproto/googleapis/devtools/clouddebugger/v2" - ctx := context.Background() c, err := debugger.NewDebugger2Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddebuggerpb.GetBreakpointRequest{ // TODO: Fill request struct fields. @@ -79,6 +79,7 @@ func ExampleDebugger2Client_DeleteBreakpoint() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddebuggerpb.DeleteBreakpointRequest{ // TODO: Fill request struct fields. @@ -90,13 +91,12 @@ func ExampleDebugger2Client_DeleteBreakpoint() { } func ExampleDebugger2Client_ListBreakpoints() { - // import clouddebuggerpb "google.golang.org/genproto/googleapis/devtools/clouddebugger/v2" - ctx := context.Background() c, err := debugger.NewDebugger2Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddebuggerpb.ListBreakpointsRequest{ // TODO: Fill request struct fields. @@ -110,13 +110,12 @@ func ExampleDebugger2Client_ListBreakpoints() { } func ExampleDebugger2Client_ListDebuggees() { - // import clouddebuggerpb "google.golang.org/genproto/googleapis/devtools/clouddebugger/v2" - ctx := context.Background() c, err := debugger.NewDebugger2Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddebuggerpb.ListDebuggeesRequest{ // TODO: Fill request struct fields. diff --git a/debugger/apiv2/doc.go b/debugger/apiv2/doc.go index 604ed648e59d..b9716555fcd4 100644 --- a/debugger/apiv2/doc.go +++ b/debugger/apiv2/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package debugger // import "cloud.google.com/go/debugger/apiv2" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/dialogflow/apiv2/agents_client.go b/dialogflow/apiv2/agents_client.go index 045a5e340484..53fa786a2cae 100644 --- a/dialogflow/apiv2/agents_client.go +++ b/dialogflow/apiv2/agents_client.go @@ -54,7 +54,7 @@ type AgentsCallOptions struct { GetValidationResult []gax.CallOption } -func defaultAgentsClientOptions() []option.ClientOption { +func defaultAgentsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -170,37 +170,199 @@ func defaultAgentsCallOptions() *AgentsCallOptions { } } +// internalAgentsClient is an interface that defines the methods availaible from Dialogflow API. +type internalAgentsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + GetAgent(context.Context, *dialogflowpb.GetAgentRequest, ...gax.CallOption) (*dialogflowpb.Agent, error) + SetAgent(context.Context, *dialogflowpb.SetAgentRequest, ...gax.CallOption) (*dialogflowpb.Agent, error) + DeleteAgent(context.Context, *dialogflowpb.DeleteAgentRequest, ...gax.CallOption) error + SearchAgents(context.Context, *dialogflowpb.SearchAgentsRequest, ...gax.CallOption) *AgentIterator + TrainAgent(context.Context, *dialogflowpb.TrainAgentRequest, ...gax.CallOption) (*TrainAgentOperation, error) + TrainAgentOperation(name string) *TrainAgentOperation + ExportAgent(context.Context, *dialogflowpb.ExportAgentRequest, ...gax.CallOption) (*ExportAgentOperation, error) + ExportAgentOperation(name string) *ExportAgentOperation + ImportAgent(context.Context, *dialogflowpb.ImportAgentRequest, ...gax.CallOption) (*ImportAgentOperation, error) + ImportAgentOperation(name string) *ImportAgentOperation + RestoreAgent(context.Context, *dialogflowpb.RestoreAgentRequest, ...gax.CallOption) (*RestoreAgentOperation, error) + RestoreAgentOperation(name string) *RestoreAgentOperation + GetValidationResult(context.Context, *dialogflowpb.GetValidationResultRequest, ...gax.CallOption) (*dialogflowpb.ValidationResult, error) +} + // AgentsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Agents. type AgentsClient struct { + // The internal transport-dependent client. + internalClient internalAgentsClient + + // The call options for this service. + CallOptions *AgentsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *AgentsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *AgentsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *AgentsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// GetAgent retrieves the specified agent. +func (c *AgentsClient) GetAgent(ctx context.Context, req *dialogflowpb.GetAgentRequest, opts ...gax.CallOption) (*dialogflowpb.Agent, error) { + return c.internalClient.GetAgent(ctx, req, opts...) +} + +// SetAgent creates/updates the specified agent. +func (c *AgentsClient) SetAgent(ctx context.Context, req *dialogflowpb.SetAgentRequest, opts ...gax.CallOption) (*dialogflowpb.Agent, error) { + return c.internalClient.SetAgent(ctx, req, opts...) +} + +// DeleteAgent deletes the specified agent. +func (c *AgentsClient) DeleteAgent(ctx context.Context, req *dialogflowpb.DeleteAgentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteAgent(ctx, req, opts...) +} + +// SearchAgents returns the list of agents. +// +// Since there is at most one conversational agent per project, this method is +// useful primarily for listing all agents across projects the caller has +// access to. One can achieve that with a wildcard project collection id “-”. +// Refer to List +// Sub-Collections (at https://cloud.google.com/apis/design/design_patterns#list_sub-collections). +func (c *AgentsClient) SearchAgents(ctx context.Context, req *dialogflowpb.SearchAgentsRequest, opts ...gax.CallOption) *AgentIterator { + return c.internalClient.SearchAgents(ctx, req, opts...) +} + +// TrainAgent trains the specified agent. +// +// Operation +func (c *AgentsClient) TrainAgent(ctx context.Context, req *dialogflowpb.TrainAgentRequest, opts ...gax.CallOption) (*TrainAgentOperation, error) { + return c.internalClient.TrainAgent(ctx, req, opts...) +} + +// TrainAgentOperation returns a new TrainAgentOperation from a given name. +// The name must be that of a previously created TrainAgentOperation, possibly from a different process. +func (c *AgentsClient) TrainAgentOperation(name string) *TrainAgentOperation { + return c.internalClient.TrainAgentOperation(name) +} + +// ExportAgent exports the specified agent to a ZIP file. +// +// Operation +func (c *AgentsClient) ExportAgent(ctx context.Context, req *dialogflowpb.ExportAgentRequest, opts ...gax.CallOption) (*ExportAgentOperation, error) { + return c.internalClient.ExportAgent(ctx, req, opts...) +} + +// ExportAgentOperation returns a new ExportAgentOperation from a given name. +// The name must be that of a previously created ExportAgentOperation, possibly from a different process. +func (c *AgentsClient) ExportAgentOperation(name string) *ExportAgentOperation { + return c.internalClient.ExportAgentOperation(name) +} + +// ImportAgent imports the specified agent from a ZIP file. +// +// Uploads new intents and entity types without deleting the existing ones. +// Intents and entity types with the same name are replaced with the new +// versions from ImportAgentRequest. After the import, the imported draft +// agent will be trained automatically (unless disabled in agent settings). +// However, once the import is done, training may not be completed yet. Please +// call TrainAgent and wait for the operation it returns in order to train +// explicitly. +// +// Operation +// An operation which tracks when importing is complete. It only tracks +// when the draft agent is updated not when it is done training. +func (c *AgentsClient) ImportAgent(ctx context.Context, req *dialogflowpb.ImportAgentRequest, opts ...gax.CallOption) (*ImportAgentOperation, error) { + return c.internalClient.ImportAgent(ctx, req, opts...) +} + +// ImportAgentOperation returns a new ImportAgentOperation from a given name. +// The name must be that of a previously created ImportAgentOperation, possibly from a different process. +func (c *AgentsClient) ImportAgentOperation(name string) *ImportAgentOperation { + return c.internalClient.ImportAgentOperation(name) +} + +// RestoreAgent restores the specified agent from a ZIP file. +// +// Replaces the current agent version with a new one. All the intents and +// entity types in the older version are deleted. After the restore, the +// restored draft agent will be trained automatically (unless disabled in +// agent settings). However, once the restore is done, training may not be +// completed yet. Please call TrainAgent and wait for the operation it +// returns in order to train explicitly. +// +// Operation +// An operation which tracks when restoring is complete. It only tracks +// when the draft agent is updated not when it is done training. +func (c *AgentsClient) RestoreAgent(ctx context.Context, req *dialogflowpb.RestoreAgentRequest, opts ...gax.CallOption) (*RestoreAgentOperation, error) { + return c.internalClient.RestoreAgent(ctx, req, opts...) +} + +// RestoreAgentOperation returns a new RestoreAgentOperation from a given name. +// The name must be that of a previously created RestoreAgentOperation, possibly from a different process. +func (c *AgentsClient) RestoreAgentOperation(name string) *RestoreAgentOperation { + return c.internalClient.RestoreAgentOperation(name) +} + +// GetValidationResult gets agent validation result. Agent validation is performed during +// training time and is updated automatically when training is completed. +func (c *AgentsClient) GetValidationResult(ctx context.Context, req *dialogflowpb.GetValidationResultRequest, opts ...gax.CallOption) (*dialogflowpb.ValidationResult, error) { + return c.internalClient.GetValidationResult(ctx, req, opts...) +} + +// agentsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type agentsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing AgentsClient + CallOptions **AgentsCallOptions + // The gRPC API client. agentsClient dialogflowpb.AgentsClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *AgentsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewAgentsClient creates a new agents client. +// NewAgentsClient creates a new agents client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Agents. func NewAgentsClient(ctx context.Context, opts ...option.ClientOption) (*AgentsClient, error) { - clientOpts := defaultAgentsClientOptions() - + clientOpts := defaultAgentsGRPCClientOptions() if newAgentsClientHook != nil { hookOpts, err := newAgentsClientHook(ctx, clientHookParams{}) if err != nil { @@ -218,16 +380,19 @@ func NewAgentsClient(ctx context.Context, opts ...option.ClientOption) (*AgentsC if err != nil { return nil, err } - c := &AgentsClient{ + client := AgentsClient{CallOptions: defaultAgentsCallOptions()} + + c := &agentsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultAgentsCallOptions(), - - agentsClient: dialogflowpb.NewAgentsClient(connPool), + agentsClient: dialogflowpb.NewAgentsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -237,33 +402,33 @@ func NewAgentsClient(ctx context.Context, opts ...option.ClientOption) (*AgentsC // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *AgentsClient) Connection() *grpc.ClientConn { +func (c *agentsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *AgentsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *AgentsClient) setGoogleClientInfo(keyval ...string) { +func (c *agentsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// GetAgent retrieves the specified agent. -func (c *AgentsClient) GetAgent(ctx context.Context, req *dialogflowpb.GetAgentRequest, opts ...gax.CallOption) (*dialogflowpb.Agent, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *agentsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *agentsGRPCClient) GetAgent(ctx context.Context, req *dialogflowpb.GetAgentRequest, opts ...gax.CallOption) (*dialogflowpb.Agent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -271,7 +436,7 @@ func (c *AgentsClient) GetAgent(ctx context.Context, req *dialogflowpb.GetAgentR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetAgent[0:len(c.CallOptions.GetAgent):len(c.CallOptions.GetAgent)], opts...) + opts = append((*c.CallOptions).GetAgent[0:len((*c.CallOptions).GetAgent):len((*c.CallOptions).GetAgent)], opts...) var resp *dialogflowpb.Agent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -284,8 +449,7 @@ func (c *AgentsClient) GetAgent(ctx context.Context, req *dialogflowpb.GetAgentR return resp, nil } -// SetAgent creates/updates the specified agent. -func (c *AgentsClient) SetAgent(ctx context.Context, req *dialogflowpb.SetAgentRequest, opts ...gax.CallOption) (*dialogflowpb.Agent, error) { +func (c *agentsGRPCClient) SetAgent(ctx context.Context, req *dialogflowpb.SetAgentRequest, opts ...gax.CallOption) (*dialogflowpb.Agent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -293,7 +457,7 @@ func (c *AgentsClient) SetAgent(ctx context.Context, req *dialogflowpb.SetAgentR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "agent.parent", url.QueryEscape(req.GetAgent().GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetAgent[0:len(c.CallOptions.SetAgent):len(c.CallOptions.SetAgent)], opts...) + opts = append((*c.CallOptions).SetAgent[0:len((*c.CallOptions).SetAgent):len((*c.CallOptions).SetAgent)], opts...) var resp *dialogflowpb.Agent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -306,8 +470,7 @@ func (c *AgentsClient) SetAgent(ctx context.Context, req *dialogflowpb.SetAgentR return resp, nil } -// DeleteAgent deletes the specified agent. -func (c *AgentsClient) DeleteAgent(ctx context.Context, req *dialogflowpb.DeleteAgentRequest, opts ...gax.CallOption) error { +func (c *agentsGRPCClient) DeleteAgent(ctx context.Context, req *dialogflowpb.DeleteAgentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -315,7 +478,7 @@ func (c *AgentsClient) DeleteAgent(ctx context.Context, req *dialogflowpb.Delete } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteAgent[0:len(c.CallOptions.DeleteAgent):len(c.CallOptions.DeleteAgent)], opts...) + opts = append((*c.CallOptions).DeleteAgent[0:len((*c.CallOptions).DeleteAgent):len((*c.CallOptions).DeleteAgent)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.agentsClient.DeleteAgent(ctx, req, settings.GRPC...) @@ -324,17 +487,10 @@ func (c *AgentsClient) DeleteAgent(ctx context.Context, req *dialogflowpb.Delete return err } -// SearchAgents returns the list of agents. -// -// Since there is at most one conversational agent per project, this method is -// useful primarily for listing all agents across projects the caller has -// access to. One can achieve that with a wildcard project collection id “-”. -// Refer to List -// Sub-Collections (at https://cloud.google.com/apis/design/design_patterns#list_sub-collections). -func (c *AgentsClient) SearchAgents(ctx context.Context, req *dialogflowpb.SearchAgentsRequest, opts ...gax.CallOption) *AgentIterator { +func (c *agentsGRPCClient) SearchAgents(ctx context.Context, req *dialogflowpb.SearchAgentsRequest, opts ...gax.CallOption) *AgentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SearchAgents[0:len(c.CallOptions.SearchAgents):len(c.CallOptions.SearchAgents)], opts...) + opts = append((*c.CallOptions).SearchAgents[0:len((*c.CallOptions).SearchAgents):len((*c.CallOptions).SearchAgents)], opts...) it := &AgentIterator{} req = proto.Clone(req).(*dialogflowpb.SearchAgentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Agent, string, error) { @@ -371,10 +527,7 @@ func (c *AgentsClient) SearchAgents(ctx context.Context, req *dialogflowpb.Searc return it } -// TrainAgent trains the specified agent. -// -// Operation -func (c *AgentsClient) TrainAgent(ctx context.Context, req *dialogflowpb.TrainAgentRequest, opts ...gax.CallOption) (*TrainAgentOperation, error) { +func (c *agentsGRPCClient) TrainAgent(ctx context.Context, req *dialogflowpb.TrainAgentRequest, opts ...gax.CallOption) (*TrainAgentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -382,7 +535,7 @@ func (c *AgentsClient) TrainAgent(ctx context.Context, req *dialogflowpb.TrainAg } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TrainAgent[0:len(c.CallOptions.TrainAgent):len(c.CallOptions.TrainAgent)], opts...) + opts = append((*c.CallOptions).TrainAgent[0:len((*c.CallOptions).TrainAgent):len((*c.CallOptions).TrainAgent)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -393,14 +546,11 @@ func (c *AgentsClient) TrainAgent(ctx context.Context, req *dialogflowpb.TrainAg return nil, err } return &TrainAgentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ExportAgent exports the specified agent to a ZIP file. -// -// Operation -func (c *AgentsClient) ExportAgent(ctx context.Context, req *dialogflowpb.ExportAgentRequest, opts ...gax.CallOption) (*ExportAgentOperation, error) { +func (c *agentsGRPCClient) ExportAgent(ctx context.Context, req *dialogflowpb.ExportAgentRequest, opts ...gax.CallOption) (*ExportAgentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -408,7 +558,7 @@ func (c *AgentsClient) ExportAgent(ctx context.Context, req *dialogflowpb.Export } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportAgent[0:len(c.CallOptions.ExportAgent):len(c.CallOptions.ExportAgent)], opts...) + opts = append((*c.CallOptions).ExportAgent[0:len((*c.CallOptions).ExportAgent):len((*c.CallOptions).ExportAgent)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -419,24 +569,11 @@ func (c *AgentsClient) ExportAgent(ctx context.Context, req *dialogflowpb.Export return nil, err } return &ExportAgentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ImportAgent imports the specified agent from a ZIP file. -// -// Uploads new intents and entity types without deleting the existing ones. -// Intents and entity types with the same name are replaced with the new -// versions from ImportAgentRequest. After the import, the imported draft -// agent will be trained automatically (unless disabled in agent settings). -// However, once the import is done, training may not be completed yet. Please -// call TrainAgent and wait for the operation it returns in order to train -// explicitly. -// -// Operation -// An operation which tracks when importing is complete. It only tracks -// when the draft agent is updated not when it is done training. -func (c *AgentsClient) ImportAgent(ctx context.Context, req *dialogflowpb.ImportAgentRequest, opts ...gax.CallOption) (*ImportAgentOperation, error) { +func (c *agentsGRPCClient) ImportAgent(ctx context.Context, req *dialogflowpb.ImportAgentRequest, opts ...gax.CallOption) (*ImportAgentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -444,7 +581,7 @@ func (c *AgentsClient) ImportAgent(ctx context.Context, req *dialogflowpb.Import } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportAgent[0:len(c.CallOptions.ImportAgent):len(c.CallOptions.ImportAgent)], opts...) + opts = append((*c.CallOptions).ImportAgent[0:len((*c.CallOptions).ImportAgent):len((*c.CallOptions).ImportAgent)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -455,23 +592,11 @@ func (c *AgentsClient) ImportAgent(ctx context.Context, req *dialogflowpb.Import return nil, err } return &ImportAgentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// RestoreAgent restores the specified agent from a ZIP file. -// -// Replaces the current agent version with a new one. All the intents and -// entity types in the older version are deleted. After the restore, the -// restored draft agent will be trained automatically (unless disabled in -// agent settings). However, once the restore is done, training may not be -// completed yet. Please call TrainAgent and wait for the operation it -// returns in order to train explicitly. -// -// Operation -// An operation which tracks when restoring is complete. It only tracks -// when the draft agent is updated not when it is done training. -func (c *AgentsClient) RestoreAgent(ctx context.Context, req *dialogflowpb.RestoreAgentRequest, opts ...gax.CallOption) (*RestoreAgentOperation, error) { +func (c *agentsGRPCClient) RestoreAgent(ctx context.Context, req *dialogflowpb.RestoreAgentRequest, opts ...gax.CallOption) (*RestoreAgentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -479,7 +604,7 @@ func (c *AgentsClient) RestoreAgent(ctx context.Context, req *dialogflowpb.Resto } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RestoreAgent[0:len(c.CallOptions.RestoreAgent):len(c.CallOptions.RestoreAgent)], opts...) + opts = append((*c.CallOptions).RestoreAgent[0:len((*c.CallOptions).RestoreAgent):len((*c.CallOptions).RestoreAgent)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -490,13 +615,11 @@ func (c *AgentsClient) RestoreAgent(ctx context.Context, req *dialogflowpb.Resto return nil, err } return &RestoreAgentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetValidationResult gets agent validation result. Agent validation is performed during -// training time and is updated automatically when training is completed. -func (c *AgentsClient) GetValidationResult(ctx context.Context, req *dialogflowpb.GetValidationResultRequest, opts ...gax.CallOption) (*dialogflowpb.ValidationResult, error) { +func (c *agentsGRPCClient) GetValidationResult(ctx context.Context, req *dialogflowpb.GetValidationResultRequest, opts ...gax.CallOption) (*dialogflowpb.ValidationResult, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -504,7 +627,7 @@ func (c *AgentsClient) GetValidationResult(ctx context.Context, req *dialogflowp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetValidationResult[0:len(c.CallOptions.GetValidationResult):len(c.CallOptions.GetValidationResult)], opts...) + opts = append((*c.CallOptions).GetValidationResult[0:len((*c.CallOptions).GetValidationResult):len((*c.CallOptions).GetValidationResult)], opts...) var resp *dialogflowpb.ValidationResult err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -524,9 +647,9 @@ type ExportAgentOperation struct { // ExportAgentOperation returns a new ExportAgentOperation from a given name. // The name must be that of a previously created ExportAgentOperation, possibly from a different process. -func (c *AgentsClient) ExportAgentOperation(name string) *ExportAgentOperation { +func (c *agentsGRPCClient) ExportAgentOperation(name string) *ExportAgentOperation { return &ExportAgentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -593,9 +716,9 @@ type ImportAgentOperation struct { // ImportAgentOperation returns a new ImportAgentOperation from a given name. // The name must be that of a previously created ImportAgentOperation, possibly from a different process. -func (c *AgentsClient) ImportAgentOperation(name string) *ImportAgentOperation { +func (c *agentsGRPCClient) ImportAgentOperation(name string) *ImportAgentOperation { return &ImportAgentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -651,9 +774,9 @@ type RestoreAgentOperation struct { // RestoreAgentOperation returns a new RestoreAgentOperation from a given name. // The name must be that of a previously created RestoreAgentOperation, possibly from a different process. -func (c *AgentsClient) RestoreAgentOperation(name string) *RestoreAgentOperation { +func (c *agentsGRPCClient) RestoreAgentOperation(name string) *RestoreAgentOperation { return &RestoreAgentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -709,9 +832,9 @@ type TrainAgentOperation struct { // TrainAgentOperation returns a new TrainAgentOperation from a given name. // The name must be that of a previously created TrainAgentOperation, possibly from a different process. -func (c *AgentsClient) TrainAgentOperation(name string) *TrainAgentOperation { +func (c *agentsGRPCClient) TrainAgentOperation(name string) *TrainAgentOperation { return &TrainAgentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dialogflow/apiv2/agents_client_example_test.go b/dialogflow/apiv2/agents_client_example_test.go index 8ca2bd0d810c..ffabded7ea87 100644 --- a/dialogflow/apiv2/agents_client_example_test.go +++ b/dialogflow/apiv2/agents_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewAgentsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleAgentsClient_GetAgent() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetAgentRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleAgentsClient_GetAgent() { } func ExampleAgentsClient_SetAgent() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.SetAgentRequest{ // TODO: Fill request struct fields. @@ -80,6 +80,7 @@ func ExampleAgentsClient_DeleteAgent() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteAgentRequest{ // TODO: Fill request struct fields. @@ -91,14 +92,12 @@ func ExampleAgentsClient_DeleteAgent() { } func ExampleAgentsClient_SearchAgents() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.SearchAgentsRequest{ // TODO: Fill request struct fields. @@ -118,13 +117,12 @@ func ExampleAgentsClient_SearchAgents() { } func ExampleAgentsClient_TrainAgent() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.TrainAgentRequest{ // TODO: Fill request struct fields. @@ -141,13 +139,12 @@ func ExampleAgentsClient_TrainAgent() { } func ExampleAgentsClient_ExportAgent() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ExportAgentRequest{ // TODO: Fill request struct fields. @@ -166,13 +163,12 @@ func ExampleAgentsClient_ExportAgent() { } func ExampleAgentsClient_ImportAgent() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ImportAgentRequest{ // TODO: Fill request struct fields. @@ -189,13 +185,12 @@ func ExampleAgentsClient_ImportAgent() { } func ExampleAgentsClient_RestoreAgent() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.RestoreAgentRequest{ // TODO: Fill request struct fields. @@ -212,13 +207,12 @@ func ExampleAgentsClient_RestoreAgent() { } func ExampleAgentsClient_GetValidationResult() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetValidationResultRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/apiv2/answer_records_client.go b/dialogflow/apiv2/answer_records_client.go index ab16ca5b0885..54652622f0f3 100644 --- a/dialogflow/apiv2/answer_records_client.go +++ b/dialogflow/apiv2/answer_records_client.go @@ -43,7 +43,7 @@ type AnswerRecordsCallOptions struct { UpdateAnswerRecord []gax.CallOption } -func defaultAnswerRecordsClientOptions() []option.ClientOption { +func defaultAnswerRecordsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -82,32 +82,86 @@ func defaultAnswerRecordsCallOptions() *AnswerRecordsCallOptions { } } +// internalAnswerRecordsClient is an interface that defines the methods availaible from Dialogflow API. +type internalAnswerRecordsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListAnswerRecords(context.Context, *dialogflowpb.ListAnswerRecordsRequest, ...gax.CallOption) *AnswerRecordIterator + UpdateAnswerRecord(context.Context, *dialogflowpb.UpdateAnswerRecordRequest, ...gax.CallOption) (*dialogflowpb.AnswerRecord, error) +} + // AnswerRecordsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing AnswerRecords. type AnswerRecordsClient struct { + // The internal transport-dependent client. + internalClient internalAnswerRecordsClient + + // The call options for this service. + CallOptions *AnswerRecordsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *AnswerRecordsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *AnswerRecordsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *AnswerRecordsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListAnswerRecords returns the list of all answer records in the specified project in reverse +// chronological order. +func (c *AnswerRecordsClient) ListAnswerRecords(ctx context.Context, req *dialogflowpb.ListAnswerRecordsRequest, opts ...gax.CallOption) *AnswerRecordIterator { + return c.internalClient.ListAnswerRecords(ctx, req, opts...) +} + +// UpdateAnswerRecord updates the specified answer record. +func (c *AnswerRecordsClient) UpdateAnswerRecord(ctx context.Context, req *dialogflowpb.UpdateAnswerRecordRequest, opts ...gax.CallOption) (*dialogflowpb.AnswerRecord, error) { + return c.internalClient.UpdateAnswerRecord(ctx, req, opts...) +} + +// answerRecordsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type answerRecordsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing AnswerRecordsClient + CallOptions **AnswerRecordsCallOptions + // The gRPC API client. answerRecordsClient dialogflowpb.AnswerRecordsClient - // The call options for this service. - CallOptions *AnswerRecordsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewAnswerRecordsClient creates a new answer records client. +// NewAnswerRecordsClient creates a new answer records client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing AnswerRecords. func NewAnswerRecordsClient(ctx context.Context, opts ...option.ClientOption) (*AnswerRecordsClient, error) { - clientOpts := defaultAnswerRecordsClientOptions() - + clientOpts := defaultAnswerRecordsGRPCClientOptions() if newAnswerRecordsClientHook != nil { hookOpts, err := newAnswerRecordsClientHook(ctx, clientHookParams{}) if err != nil { @@ -125,46 +179,47 @@ func NewAnswerRecordsClient(ctx context.Context, opts ...option.ClientOption) (* if err != nil { return nil, err } - c := &AnswerRecordsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultAnswerRecordsCallOptions(), + client := AnswerRecordsClient{CallOptions: defaultAnswerRecordsCallOptions()} + c := &answerRecordsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, answerRecordsClient: dialogflowpb.NewAnswerRecordsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *AnswerRecordsClient) Connection() *grpc.ClientConn { +func (c *answerRecordsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *AnswerRecordsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *AnswerRecordsClient) setGoogleClientInfo(keyval ...string) { +func (c *answerRecordsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListAnswerRecords returns the list of all answer records in the specified project in reverse -// chronological order. -func (c *AnswerRecordsClient) ListAnswerRecords(ctx context.Context, req *dialogflowpb.ListAnswerRecordsRequest, opts ...gax.CallOption) *AnswerRecordIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *answerRecordsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *answerRecordsGRPCClient) ListAnswerRecords(ctx context.Context, req *dialogflowpb.ListAnswerRecordsRequest, opts ...gax.CallOption) *AnswerRecordIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAnswerRecords[0:len(c.CallOptions.ListAnswerRecords):len(c.CallOptions.ListAnswerRecords)], opts...) + opts = append((*c.CallOptions).ListAnswerRecords[0:len((*c.CallOptions).ListAnswerRecords):len((*c.CallOptions).ListAnswerRecords)], opts...) it := &AnswerRecordIterator{} req = proto.Clone(req).(*dialogflowpb.ListAnswerRecordsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.AnswerRecord, string, error) { @@ -201,8 +256,7 @@ func (c *AnswerRecordsClient) ListAnswerRecords(ctx context.Context, req *dialog return it } -// UpdateAnswerRecord updates the specified answer record. -func (c *AnswerRecordsClient) UpdateAnswerRecord(ctx context.Context, req *dialogflowpb.UpdateAnswerRecordRequest, opts ...gax.CallOption) (*dialogflowpb.AnswerRecord, error) { +func (c *answerRecordsGRPCClient) UpdateAnswerRecord(ctx context.Context, req *dialogflowpb.UpdateAnswerRecordRequest, opts ...gax.CallOption) (*dialogflowpb.AnswerRecord, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -210,7 +264,7 @@ func (c *AnswerRecordsClient) UpdateAnswerRecord(ctx context.Context, req *dialo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "answer_record.name", url.QueryEscape(req.GetAnswerRecord().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateAnswerRecord[0:len(c.CallOptions.UpdateAnswerRecord):len(c.CallOptions.UpdateAnswerRecord)], opts...) + opts = append((*c.CallOptions).UpdateAnswerRecord[0:len((*c.CallOptions).UpdateAnswerRecord):len((*c.CallOptions).UpdateAnswerRecord)], opts...) var resp *dialogflowpb.AnswerRecord err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/dialogflow/apiv2/answer_records_client_example_test.go b/dialogflow/apiv2/answer_records_client_example_test.go index c8497a53066c..3ccd98a5d72c 100644 --- a/dialogflow/apiv2/answer_records_client_example_test.go +++ b/dialogflow/apiv2/answer_records_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewAnswerRecordsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleAnswerRecordsClient_ListAnswerRecords() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewAnswerRecordsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListAnswerRecordsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleAnswerRecordsClient_ListAnswerRecords() { } func ExampleAnswerRecordsClient_UpdateAnswerRecord() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewAnswerRecordsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateAnswerRecordRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/apiv2/contexts_client.go b/dialogflow/apiv2/contexts_client.go index b1b617d8f1a0..1172e9165268 100644 --- a/dialogflow/apiv2/contexts_client.go +++ b/dialogflow/apiv2/contexts_client.go @@ -47,7 +47,7 @@ type ContextsCallOptions struct { DeleteAllContexts []gax.CallOption } -func defaultContextsClientOptions() []option.ClientOption { +func defaultContextsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -130,32 +130,111 @@ func defaultContextsCallOptions() *ContextsCallOptions { } } +// internalContextsClient is an interface that defines the methods availaible from Dialogflow API. +type internalContextsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListContexts(context.Context, *dialogflowpb.ListContextsRequest, ...gax.CallOption) *ContextIterator + GetContext(context.Context, *dialogflowpb.GetContextRequest, ...gax.CallOption) (*dialogflowpb.Context, error) + CreateContext(context.Context, *dialogflowpb.CreateContextRequest, ...gax.CallOption) (*dialogflowpb.Context, error) + UpdateContext(context.Context, *dialogflowpb.UpdateContextRequest, ...gax.CallOption) (*dialogflowpb.Context, error) + DeleteContext(context.Context, *dialogflowpb.DeleteContextRequest, ...gax.CallOption) error + DeleteAllContexts(context.Context, *dialogflowpb.DeleteAllContextsRequest, ...gax.CallOption) error +} + // ContextsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Contexts. type ContextsClient struct { + // The internal transport-dependent client. + internalClient internalContextsClient + + // The call options for this service. + CallOptions *ContextsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ContextsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ContextsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ContextsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListContexts returns the list of all contexts in the specified session. +func (c *ContextsClient) ListContexts(ctx context.Context, req *dialogflowpb.ListContextsRequest, opts ...gax.CallOption) *ContextIterator { + return c.internalClient.ListContexts(ctx, req, opts...) +} + +// GetContext retrieves the specified context. +func (c *ContextsClient) GetContext(ctx context.Context, req *dialogflowpb.GetContextRequest, opts ...gax.CallOption) (*dialogflowpb.Context, error) { + return c.internalClient.GetContext(ctx, req, opts...) +} + +// CreateContext creates a context. +// +// If the specified context already exists, overrides the context. +func (c *ContextsClient) CreateContext(ctx context.Context, req *dialogflowpb.CreateContextRequest, opts ...gax.CallOption) (*dialogflowpb.Context, error) { + return c.internalClient.CreateContext(ctx, req, opts...) +} + +// UpdateContext updates the specified context. +func (c *ContextsClient) UpdateContext(ctx context.Context, req *dialogflowpb.UpdateContextRequest, opts ...gax.CallOption) (*dialogflowpb.Context, error) { + return c.internalClient.UpdateContext(ctx, req, opts...) +} + +// DeleteContext deletes the specified context. +func (c *ContextsClient) DeleteContext(ctx context.Context, req *dialogflowpb.DeleteContextRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteContext(ctx, req, opts...) +} + +// DeleteAllContexts deletes all active contexts in the specified session. +func (c *ContextsClient) DeleteAllContexts(ctx context.Context, req *dialogflowpb.DeleteAllContextsRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteAllContexts(ctx, req, opts...) +} + +// contextsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type contextsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ContextsClient + CallOptions **ContextsCallOptions + // The gRPC API client. contextsClient dialogflowpb.ContextsClient - // The call options for this service. - CallOptions *ContextsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewContextsClient creates a new contexts client. +// NewContextsClient creates a new contexts client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Contexts. func NewContextsClient(ctx context.Context, opts ...option.ClientOption) (*ContextsClient, error) { - clientOpts := defaultContextsClientOptions() - + clientOpts := defaultContextsGRPCClientOptions() if newContextsClientHook != nil { hookOpts, err := newContextsClientHook(ctx, clientHookParams{}) if err != nil { @@ -173,45 +252,47 @@ func NewContextsClient(ctx context.Context, opts ...option.ClientOption) (*Conte if err != nil { return nil, err } - c := &ContextsClient{ + client := ContextsClient{CallOptions: defaultContextsCallOptions()} + + c := &contextsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultContextsCallOptions(), - - contextsClient: dialogflowpb.NewContextsClient(connPool), + contextsClient: dialogflowpb.NewContextsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ContextsClient) Connection() *grpc.ClientConn { +func (c *contextsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ContextsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ContextsClient) setGoogleClientInfo(keyval ...string) { +func (c *contextsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListContexts returns the list of all contexts in the specified session. -func (c *ContextsClient) ListContexts(ctx context.Context, req *dialogflowpb.ListContextsRequest, opts ...gax.CallOption) *ContextIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *contextsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *contextsGRPCClient) ListContexts(ctx context.Context, req *dialogflowpb.ListContextsRequest, opts ...gax.CallOption) *ContextIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListContexts[0:len(c.CallOptions.ListContexts):len(c.CallOptions.ListContexts)], opts...) + opts = append((*c.CallOptions).ListContexts[0:len((*c.CallOptions).ListContexts):len((*c.CallOptions).ListContexts)], opts...) it := &ContextIterator{} req = proto.Clone(req).(*dialogflowpb.ListContextsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Context, string, error) { @@ -248,8 +329,7 @@ func (c *ContextsClient) ListContexts(ctx context.Context, req *dialogflowpb.Lis return it } -// GetContext retrieves the specified context. -func (c *ContextsClient) GetContext(ctx context.Context, req *dialogflowpb.GetContextRequest, opts ...gax.CallOption) (*dialogflowpb.Context, error) { +func (c *contextsGRPCClient) GetContext(ctx context.Context, req *dialogflowpb.GetContextRequest, opts ...gax.CallOption) (*dialogflowpb.Context, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -257,7 +337,7 @@ func (c *ContextsClient) GetContext(ctx context.Context, req *dialogflowpb.GetCo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetContext[0:len(c.CallOptions.GetContext):len(c.CallOptions.GetContext)], opts...) + opts = append((*c.CallOptions).GetContext[0:len((*c.CallOptions).GetContext):len((*c.CallOptions).GetContext)], opts...) var resp *dialogflowpb.Context err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -270,10 +350,7 @@ func (c *ContextsClient) GetContext(ctx context.Context, req *dialogflowpb.GetCo return resp, nil } -// CreateContext creates a context. -// -// If the specified context already exists, overrides the context. -func (c *ContextsClient) CreateContext(ctx context.Context, req *dialogflowpb.CreateContextRequest, opts ...gax.CallOption) (*dialogflowpb.Context, error) { +func (c *contextsGRPCClient) CreateContext(ctx context.Context, req *dialogflowpb.CreateContextRequest, opts ...gax.CallOption) (*dialogflowpb.Context, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -281,7 +358,7 @@ func (c *ContextsClient) CreateContext(ctx context.Context, req *dialogflowpb.Cr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateContext[0:len(c.CallOptions.CreateContext):len(c.CallOptions.CreateContext)], opts...) + opts = append((*c.CallOptions).CreateContext[0:len((*c.CallOptions).CreateContext):len((*c.CallOptions).CreateContext)], opts...) var resp *dialogflowpb.Context err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -294,8 +371,7 @@ func (c *ContextsClient) CreateContext(ctx context.Context, req *dialogflowpb.Cr return resp, nil } -// UpdateContext updates the specified context. -func (c *ContextsClient) UpdateContext(ctx context.Context, req *dialogflowpb.UpdateContextRequest, opts ...gax.CallOption) (*dialogflowpb.Context, error) { +func (c *contextsGRPCClient) UpdateContext(ctx context.Context, req *dialogflowpb.UpdateContextRequest, opts ...gax.CallOption) (*dialogflowpb.Context, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -303,7 +379,7 @@ func (c *ContextsClient) UpdateContext(ctx context.Context, req *dialogflowpb.Up } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "context.name", url.QueryEscape(req.GetContext().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateContext[0:len(c.CallOptions.UpdateContext):len(c.CallOptions.UpdateContext)], opts...) + opts = append((*c.CallOptions).UpdateContext[0:len((*c.CallOptions).UpdateContext):len((*c.CallOptions).UpdateContext)], opts...) var resp *dialogflowpb.Context err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -316,8 +392,7 @@ func (c *ContextsClient) UpdateContext(ctx context.Context, req *dialogflowpb.Up return resp, nil } -// DeleteContext deletes the specified context. -func (c *ContextsClient) DeleteContext(ctx context.Context, req *dialogflowpb.DeleteContextRequest, opts ...gax.CallOption) error { +func (c *contextsGRPCClient) DeleteContext(ctx context.Context, req *dialogflowpb.DeleteContextRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -325,7 +400,7 @@ func (c *ContextsClient) DeleteContext(ctx context.Context, req *dialogflowpb.De } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteContext[0:len(c.CallOptions.DeleteContext):len(c.CallOptions.DeleteContext)], opts...) + opts = append((*c.CallOptions).DeleteContext[0:len((*c.CallOptions).DeleteContext):len((*c.CallOptions).DeleteContext)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.contextsClient.DeleteContext(ctx, req, settings.GRPC...) @@ -334,8 +409,7 @@ func (c *ContextsClient) DeleteContext(ctx context.Context, req *dialogflowpb.De return err } -// DeleteAllContexts deletes all active contexts in the specified session. -func (c *ContextsClient) DeleteAllContexts(ctx context.Context, req *dialogflowpb.DeleteAllContextsRequest, opts ...gax.CallOption) error { +func (c *contextsGRPCClient) DeleteAllContexts(ctx context.Context, req *dialogflowpb.DeleteAllContextsRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -343,7 +417,7 @@ func (c *ContextsClient) DeleteAllContexts(ctx context.Context, req *dialogflowp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteAllContexts[0:len(c.CallOptions.DeleteAllContexts):len(c.CallOptions.DeleteAllContexts)], opts...) + opts = append((*c.CallOptions).DeleteAllContexts[0:len((*c.CallOptions).DeleteAllContexts):len((*c.CallOptions).DeleteAllContexts)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.contextsClient.DeleteAllContexts(ctx, req, settings.GRPC...) diff --git a/dialogflow/apiv2/contexts_client_example_test.go b/dialogflow/apiv2/contexts_client_example_test.go index c69d460fe282..c562805990cd 100644 --- a/dialogflow/apiv2/contexts_client_example_test.go +++ b/dialogflow/apiv2/contexts_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewContextsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleContextsClient_ListContexts() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewContextsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListContextsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleContextsClient_ListContexts() { } func ExampleContextsClient_GetContext() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewContextsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetContextRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleContextsClient_GetContext() { } func ExampleContextsClient_CreateContext() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewContextsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateContextRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleContextsClient_CreateContext() { } func ExampleContextsClient_UpdateContext() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewContextsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateContextRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleContextsClient_DeleteContext() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteContextRequest{ // TODO: Fill request struct fields. @@ -143,6 +141,7 @@ func ExampleContextsClient_DeleteAllContexts() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteAllContextsRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/apiv2/conversation_profiles_client.go b/dialogflow/apiv2/conversation_profiles_client.go index 27d0a64b0fc4..ef87dd9fc2d8 100644 --- a/dialogflow/apiv2/conversation_profiles_client.go +++ b/dialogflow/apiv2/conversation_profiles_client.go @@ -46,7 +46,7 @@ type ConversationProfilesCallOptions struct { DeleteConversationProfile []gax.CallOption } -func defaultConversationProfilesClientOptions() []option.ClientOption { +func defaultConversationProfilesGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,111 @@ func defaultConversationProfilesCallOptions() *ConversationProfilesCallOptions { } } +// internalConversationProfilesClient is an interface that defines the methods availaible from Dialogflow API. +type internalConversationProfilesClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListConversationProfiles(context.Context, *dialogflowpb.ListConversationProfilesRequest, ...gax.CallOption) *ConversationProfileIterator + GetConversationProfile(context.Context, *dialogflowpb.GetConversationProfileRequest, ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) + CreateConversationProfile(context.Context, *dialogflowpb.CreateConversationProfileRequest, ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) + UpdateConversationProfile(context.Context, *dialogflowpb.UpdateConversationProfileRequest, ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) + DeleteConversationProfile(context.Context, *dialogflowpb.DeleteConversationProfileRequest, ...gax.CallOption) error +} + // ConversationProfilesClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing ConversationProfiles. type ConversationProfilesClient struct { + // The internal transport-dependent client. + internalClient internalConversationProfilesClient + + // The call options for this service. + CallOptions *ConversationProfilesCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ConversationProfilesClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ConversationProfilesClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ConversationProfilesClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListConversationProfiles returns the list of all conversation profiles in the specified project. +func (c *ConversationProfilesClient) ListConversationProfiles(ctx context.Context, req *dialogflowpb.ListConversationProfilesRequest, opts ...gax.CallOption) *ConversationProfileIterator { + return c.internalClient.ListConversationProfiles(ctx, req, opts...) +} + +// GetConversationProfile retrieves the specified conversation profile. +func (c *ConversationProfilesClient) GetConversationProfile(ctx context.Context, req *dialogflowpb.GetConversationProfileRequest, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { + return c.internalClient.GetConversationProfile(ctx, req, opts...) +} + +// CreateConversationProfile creates a conversation profile in the specified project. +// +// ConversationProfile.CreateTime and ConversationProfile.UpdateTime +// aren’t populated in the response. You can retrieve them via +// GetConversationProfile API. +func (c *ConversationProfilesClient) CreateConversationProfile(ctx context.Context, req *dialogflowpb.CreateConversationProfileRequest, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { + return c.internalClient.CreateConversationProfile(ctx, req, opts...) +} + +// UpdateConversationProfile updates the specified conversation profile. +// +// ConversationProfile.CreateTime and ConversationProfile.UpdateTime +// aren’t populated in the response. You can retrieve them via +// GetConversationProfile API. +func (c *ConversationProfilesClient) UpdateConversationProfile(ctx context.Context, req *dialogflowpb.UpdateConversationProfileRequest, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { + return c.internalClient.UpdateConversationProfile(ctx, req, opts...) +} + +// DeleteConversationProfile deletes the specified conversation profile. +func (c *ConversationProfilesClient) DeleteConversationProfile(ctx context.Context, req *dialogflowpb.DeleteConversationProfileRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteConversationProfile(ctx, req, opts...) +} + +// conversationProfilesGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type conversationProfilesGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ConversationProfilesClient + CallOptions **ConversationProfilesCallOptions + // The gRPC API client. conversationProfilesClient dialogflowpb.ConversationProfilesClient - // The call options for this service. - CallOptions *ConversationProfilesCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewConversationProfilesClient creates a new conversation profiles client. +// NewConversationProfilesClient creates a new conversation profiles client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing ConversationProfiles. func NewConversationProfilesClient(ctx context.Context, opts ...option.ClientOption) (*ConversationProfilesClient, error) { - clientOpts := defaultConversationProfilesClientOptions() - + clientOpts := defaultConversationProfilesGRPCClientOptions() if newConversationProfilesClientHook != nil { hookOpts, err := newConversationProfilesClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,45 +240,47 @@ func NewConversationProfilesClient(ctx context.Context, opts ...option.ClientOpt if err != nil { return nil, err } - c := &ConversationProfilesClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultConversationProfilesCallOptions(), + client := ConversationProfilesClient{CallOptions: defaultConversationProfilesCallOptions()} + c := &conversationProfilesGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, conversationProfilesClient: dialogflowpb.NewConversationProfilesClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ConversationProfilesClient) Connection() *grpc.ClientConn { +func (c *conversationProfilesGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ConversationProfilesClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ConversationProfilesClient) setGoogleClientInfo(keyval ...string) { +func (c *conversationProfilesGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListConversationProfiles returns the list of all conversation profiles in the specified project. -func (c *ConversationProfilesClient) ListConversationProfiles(ctx context.Context, req *dialogflowpb.ListConversationProfilesRequest, opts ...gax.CallOption) *ConversationProfileIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *conversationProfilesGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *conversationProfilesGRPCClient) ListConversationProfiles(ctx context.Context, req *dialogflowpb.ListConversationProfilesRequest, opts ...gax.CallOption) *ConversationProfileIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListConversationProfiles[0:len(c.CallOptions.ListConversationProfiles):len(c.CallOptions.ListConversationProfiles)], opts...) + opts = append((*c.CallOptions).ListConversationProfiles[0:len((*c.CallOptions).ListConversationProfiles):len((*c.CallOptions).ListConversationProfiles)], opts...) it := &ConversationProfileIterator{} req = proto.Clone(req).(*dialogflowpb.ListConversationProfilesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.ConversationProfile, string, error) { @@ -236,8 +317,7 @@ func (c *ConversationProfilesClient) ListConversationProfiles(ctx context.Contex return it } -// GetConversationProfile retrieves the specified conversation profile. -func (c *ConversationProfilesClient) GetConversationProfile(ctx context.Context, req *dialogflowpb.GetConversationProfileRequest, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { +func (c *conversationProfilesGRPCClient) GetConversationProfile(ctx context.Context, req *dialogflowpb.GetConversationProfileRequest, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -245,7 +325,7 @@ func (c *ConversationProfilesClient) GetConversationProfile(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetConversationProfile[0:len(c.CallOptions.GetConversationProfile):len(c.CallOptions.GetConversationProfile)], opts...) + opts = append((*c.CallOptions).GetConversationProfile[0:len((*c.CallOptions).GetConversationProfile):len((*c.CallOptions).GetConversationProfile)], opts...) var resp *dialogflowpb.ConversationProfile err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -258,12 +338,7 @@ func (c *ConversationProfilesClient) GetConversationProfile(ctx context.Context, return resp, nil } -// CreateConversationProfile creates a conversation profile in the specified project. -// -// ConversationProfile.CreateTime and ConversationProfile.UpdateTime -// aren’t populated in the response. You can retrieve them via -// GetConversationProfile API. -func (c *ConversationProfilesClient) CreateConversationProfile(ctx context.Context, req *dialogflowpb.CreateConversationProfileRequest, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { +func (c *conversationProfilesGRPCClient) CreateConversationProfile(ctx context.Context, req *dialogflowpb.CreateConversationProfileRequest, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -271,7 +346,7 @@ func (c *ConversationProfilesClient) CreateConversationProfile(ctx context.Conte } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateConversationProfile[0:len(c.CallOptions.CreateConversationProfile):len(c.CallOptions.CreateConversationProfile)], opts...) + opts = append((*c.CallOptions).CreateConversationProfile[0:len((*c.CallOptions).CreateConversationProfile):len((*c.CallOptions).CreateConversationProfile)], opts...) var resp *dialogflowpb.ConversationProfile err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -284,12 +359,7 @@ func (c *ConversationProfilesClient) CreateConversationProfile(ctx context.Conte return resp, nil } -// UpdateConversationProfile updates the specified conversation profile. -// -// ConversationProfile.CreateTime and ConversationProfile.UpdateTime -// aren’t populated in the response. You can retrieve them via -// GetConversationProfile API. -func (c *ConversationProfilesClient) UpdateConversationProfile(ctx context.Context, req *dialogflowpb.UpdateConversationProfileRequest, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { +func (c *conversationProfilesGRPCClient) UpdateConversationProfile(ctx context.Context, req *dialogflowpb.UpdateConversationProfileRequest, opts ...gax.CallOption) (*dialogflowpb.ConversationProfile, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -297,7 +367,7 @@ func (c *ConversationProfilesClient) UpdateConversationProfile(ctx context.Conte } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "conversation_profile.name", url.QueryEscape(req.GetConversationProfile().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateConversationProfile[0:len(c.CallOptions.UpdateConversationProfile):len(c.CallOptions.UpdateConversationProfile)], opts...) + opts = append((*c.CallOptions).UpdateConversationProfile[0:len((*c.CallOptions).UpdateConversationProfile):len((*c.CallOptions).UpdateConversationProfile)], opts...) var resp *dialogflowpb.ConversationProfile err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -310,8 +380,7 @@ func (c *ConversationProfilesClient) UpdateConversationProfile(ctx context.Conte return resp, nil } -// DeleteConversationProfile deletes the specified conversation profile. -func (c *ConversationProfilesClient) DeleteConversationProfile(ctx context.Context, req *dialogflowpb.DeleteConversationProfileRequest, opts ...gax.CallOption) error { +func (c *conversationProfilesGRPCClient) DeleteConversationProfile(ctx context.Context, req *dialogflowpb.DeleteConversationProfileRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -319,7 +388,7 @@ func (c *ConversationProfilesClient) DeleteConversationProfile(ctx context.Conte } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteConversationProfile[0:len(c.CallOptions.DeleteConversationProfile):len(c.CallOptions.DeleteConversationProfile)], opts...) + opts = append((*c.CallOptions).DeleteConversationProfile[0:len((*c.CallOptions).DeleteConversationProfile):len((*c.CallOptions).DeleteConversationProfile)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.conversationProfilesClient.DeleteConversationProfile(ctx, req, settings.GRPC...) diff --git a/dialogflow/apiv2/conversation_profiles_client_example_test.go b/dialogflow/apiv2/conversation_profiles_client_example_test.go index 36bacbed383e..7aeaea1cbf1c 100644 --- a/dialogflow/apiv2/conversation_profiles_client_example_test.go +++ b/dialogflow/apiv2/conversation_profiles_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewConversationProfilesClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleConversationProfilesClient_ListConversationProfiles() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewConversationProfilesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListConversationProfilesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleConversationProfilesClient_ListConversationProfiles() { } func ExampleConversationProfilesClient_GetConversationProfile() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewConversationProfilesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetConversationProfileRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleConversationProfilesClient_GetConversationProfile() { } func ExampleConversationProfilesClient_CreateConversationProfile() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewConversationProfilesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateConversationProfileRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleConversationProfilesClient_CreateConversationProfile() { } func ExampleConversationProfilesClient_UpdateConversationProfile() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewConversationProfilesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateConversationProfileRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleConversationProfilesClient_DeleteConversationProfile() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteConversationProfileRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/apiv2/conversations_client.go b/dialogflow/apiv2/conversations_client.go index d93718870f3e..56c45b6c4662 100644 --- a/dialogflow/apiv2/conversations_client.go +++ b/dialogflow/apiv2/conversations_client.go @@ -46,7 +46,7 @@ type ConversationsCallOptions struct { ListMessages []gax.CallOption } -func defaultConversationsClientOptions() []option.ClientOption { +func defaultConversationsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,124 @@ func defaultConversationsCallOptions() *ConversationsCallOptions { } } +// internalConversationsClient is an interface that defines the methods availaible from Dialogflow API. +type internalConversationsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateConversation(context.Context, *dialogflowpb.CreateConversationRequest, ...gax.CallOption) (*dialogflowpb.Conversation, error) + ListConversations(context.Context, *dialogflowpb.ListConversationsRequest, ...gax.CallOption) *ConversationIterator + GetConversation(context.Context, *dialogflowpb.GetConversationRequest, ...gax.CallOption) (*dialogflowpb.Conversation, error) + CompleteConversation(context.Context, *dialogflowpb.CompleteConversationRequest, ...gax.CallOption) (*dialogflowpb.Conversation, error) + ListMessages(context.Context, *dialogflowpb.ListMessagesRequest, ...gax.CallOption) *MessageIterator +} + // ConversationsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Conversations. type ConversationsClient struct { + // The internal transport-dependent client. + internalClient internalConversationsClient + + // The call options for this service. + CallOptions *ConversationsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ConversationsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ConversationsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ConversationsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateConversation creates a new conversation. Conversations are auto-completed after 24 +// hours. +// +// Conversation Lifecycle: +// There are two stages during a conversation: Automated Agent Stage and +// Assist Stage. +// +// For Automated Agent Stage, there will be a dialogflow agent responding to +// user queries. +// +// For Assist Stage, there’s no dialogflow agent responding to user queries. +// But we will provide suggestions which are generated from conversation. +// +// If Conversation.conversation_profile is configured for a dialogflow +// agent, conversation will start from Automated Agent Stage, otherwise, it +// will start from Assist Stage. And during Automated Agent Stage, once an +// Intent with Intent.live_agent_handoff is triggered, conversation +// will transfer to Assist Stage. +func (c *ConversationsClient) CreateConversation(ctx context.Context, req *dialogflowpb.CreateConversationRequest, opts ...gax.CallOption) (*dialogflowpb.Conversation, error) { + return c.internalClient.CreateConversation(ctx, req, opts...) +} + +// ListConversations returns the list of all conversations in the specified project. +func (c *ConversationsClient) ListConversations(ctx context.Context, req *dialogflowpb.ListConversationsRequest, opts ...gax.CallOption) *ConversationIterator { + return c.internalClient.ListConversations(ctx, req, opts...) +} + +// GetConversation retrieves the specific conversation. +func (c *ConversationsClient) GetConversation(ctx context.Context, req *dialogflowpb.GetConversationRequest, opts ...gax.CallOption) (*dialogflowpb.Conversation, error) { + return c.internalClient.GetConversation(ctx, req, opts...) +} + +// CompleteConversation completes the specified conversation. Finished conversations are purged +// from the database after 30 days. +func (c *ConversationsClient) CompleteConversation(ctx context.Context, req *dialogflowpb.CompleteConversationRequest, opts ...gax.CallOption) (*dialogflowpb.Conversation, error) { + return c.internalClient.CompleteConversation(ctx, req, opts...) +} + +// ListMessages lists messages that belong to a given conversation. +// messages are ordered by create_time in descending order. To fetch +// updates without duplication, send request with filter +// create_time_epoch_microseconds > [first item's create_time of previous request] and empty page_token. +func (c *ConversationsClient) ListMessages(ctx context.Context, req *dialogflowpb.ListMessagesRequest, opts ...gax.CallOption) *MessageIterator { + return c.internalClient.ListMessages(ctx, req, opts...) +} + +// conversationsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type conversationsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ConversationsClient + CallOptions **ConversationsCallOptions + // The gRPC API client. conversationsClient dialogflowpb.ConversationsClient - // The call options for this service. - CallOptions *ConversationsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewConversationsClient creates a new conversations client. +// NewConversationsClient creates a new conversations client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Conversations. func NewConversationsClient(ctx context.Context, opts ...option.ClientOption) (*ConversationsClient, error) { - clientOpts := defaultConversationsClientOptions() - + clientOpts := defaultConversationsGRPCClientOptions() if newConversationsClientHook != nil { hookOpts, err := newConversationsClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,59 +253,44 @@ func NewConversationsClient(ctx context.Context, opts ...option.ClientOption) (* if err != nil { return nil, err } - c := &ConversationsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultConversationsCallOptions(), + client := ConversationsClient{CallOptions: defaultConversationsCallOptions()} + c := &conversationsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, conversationsClient: dialogflowpb.NewConversationsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ConversationsClient) Connection() *grpc.ClientConn { +func (c *conversationsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ConversationsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ConversationsClient) setGoogleClientInfo(keyval ...string) { +func (c *conversationsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateConversation creates a new conversation. Conversations are auto-completed after 24 -// hours. -// -// Conversation Lifecycle: -// There are two stages during a conversation: Automated Agent Stage and -// Assist Stage. -// -// For Automated Agent Stage, there will be a dialogflow agent responding to -// user queries. -// -// For Assist Stage, there’s no dialogflow agent responding to user queries. -// But we will provide suggestions which are generated from conversation. -// -// If Conversation.conversation_profile is configured for a dialogflow -// agent, conversation will start from Automated Agent Stage, otherwise, it -// will start from Assist Stage. And during Automated Agent Stage, once an -// Intent with Intent.live_agent_handoff is triggered, conversation -// will transfer to Assist Stage. -func (c *ConversationsClient) CreateConversation(ctx context.Context, req *dialogflowpb.CreateConversationRequest, opts ...gax.CallOption) (*dialogflowpb.Conversation, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *conversationsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *conversationsGRPCClient) CreateConversation(ctx context.Context, req *dialogflowpb.CreateConversationRequest, opts ...gax.CallOption) (*dialogflowpb.Conversation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -221,7 +298,7 @@ func (c *ConversationsClient) CreateConversation(ctx context.Context, req *dialo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateConversation[0:len(c.CallOptions.CreateConversation):len(c.CallOptions.CreateConversation)], opts...) + opts = append((*c.CallOptions).CreateConversation[0:len((*c.CallOptions).CreateConversation):len((*c.CallOptions).CreateConversation)], opts...) var resp *dialogflowpb.Conversation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -234,11 +311,10 @@ func (c *ConversationsClient) CreateConversation(ctx context.Context, req *dialo return resp, nil } -// ListConversations returns the list of all conversations in the specified project. -func (c *ConversationsClient) ListConversations(ctx context.Context, req *dialogflowpb.ListConversationsRequest, opts ...gax.CallOption) *ConversationIterator { +func (c *conversationsGRPCClient) ListConversations(ctx context.Context, req *dialogflowpb.ListConversationsRequest, opts ...gax.CallOption) *ConversationIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListConversations[0:len(c.CallOptions.ListConversations):len(c.CallOptions.ListConversations)], opts...) + opts = append((*c.CallOptions).ListConversations[0:len((*c.CallOptions).ListConversations):len((*c.CallOptions).ListConversations)], opts...) it := &ConversationIterator{} req = proto.Clone(req).(*dialogflowpb.ListConversationsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Conversation, string, error) { @@ -275,8 +351,7 @@ func (c *ConversationsClient) ListConversations(ctx context.Context, req *dialog return it } -// GetConversation retrieves the specific conversation. -func (c *ConversationsClient) GetConversation(ctx context.Context, req *dialogflowpb.GetConversationRequest, opts ...gax.CallOption) (*dialogflowpb.Conversation, error) { +func (c *conversationsGRPCClient) GetConversation(ctx context.Context, req *dialogflowpb.GetConversationRequest, opts ...gax.CallOption) (*dialogflowpb.Conversation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -284,7 +359,7 @@ func (c *ConversationsClient) GetConversation(ctx context.Context, req *dialogfl } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetConversation[0:len(c.CallOptions.GetConversation):len(c.CallOptions.GetConversation)], opts...) + opts = append((*c.CallOptions).GetConversation[0:len((*c.CallOptions).GetConversation):len((*c.CallOptions).GetConversation)], opts...) var resp *dialogflowpb.Conversation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -297,9 +372,7 @@ func (c *ConversationsClient) GetConversation(ctx context.Context, req *dialogfl return resp, nil } -// CompleteConversation completes the specified conversation. Finished conversations are purged -// from the database after 30 days. -func (c *ConversationsClient) CompleteConversation(ctx context.Context, req *dialogflowpb.CompleteConversationRequest, opts ...gax.CallOption) (*dialogflowpb.Conversation, error) { +func (c *conversationsGRPCClient) CompleteConversation(ctx context.Context, req *dialogflowpb.CompleteConversationRequest, opts ...gax.CallOption) (*dialogflowpb.Conversation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -307,7 +380,7 @@ func (c *ConversationsClient) CompleteConversation(ctx context.Context, req *dia } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CompleteConversation[0:len(c.CallOptions.CompleteConversation):len(c.CallOptions.CompleteConversation)], opts...) + opts = append((*c.CallOptions).CompleteConversation[0:len((*c.CallOptions).CompleteConversation):len((*c.CallOptions).CompleteConversation)], opts...) var resp *dialogflowpb.Conversation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -320,14 +393,10 @@ func (c *ConversationsClient) CompleteConversation(ctx context.Context, req *dia return resp, nil } -// ListMessages lists messages that belong to a given conversation. -// messages are ordered by create_time in descending order. To fetch -// updates without duplication, send request with filter -// create_time_epoch_microseconds > [first item's create_time of previous request] and empty page_token. -func (c *ConversationsClient) ListMessages(ctx context.Context, req *dialogflowpb.ListMessagesRequest, opts ...gax.CallOption) *MessageIterator { +func (c *conversationsGRPCClient) ListMessages(ctx context.Context, req *dialogflowpb.ListMessagesRequest, opts ...gax.CallOption) *MessageIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListMessages[0:len(c.CallOptions.ListMessages):len(c.CallOptions.ListMessages)], opts...) + opts = append((*c.CallOptions).ListMessages[0:len((*c.CallOptions).ListMessages):len((*c.CallOptions).ListMessages)], opts...) it := &MessageIterator{} req = proto.Clone(req).(*dialogflowpb.ListMessagesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Message, string, error) { diff --git a/dialogflow/apiv2/conversations_client_example_test.go b/dialogflow/apiv2/conversations_client_example_test.go index dc7051c68d36..aaacf3ae01a7 100644 --- a/dialogflow/apiv2/conversations_client_example_test.go +++ b/dialogflow/apiv2/conversations_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewConversationsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleConversationsClient_CreateConversation() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewConversationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateConversationRequest{ // TODO: Fill request struct fields. @@ -55,14 +56,12 @@ func ExampleConversationsClient_CreateConversation() { } func ExampleConversationsClient_ListConversations() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewConversationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListConversationsRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleConversationsClient_ListConversations() { } func ExampleConversationsClient_GetConversation() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewConversationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetConversationRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleConversationsClient_GetConversation() { } func ExampleConversationsClient_CompleteConversation() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewConversationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CompleteConversationRequest{ // TODO: Fill request struct fields. @@ -122,14 +119,12 @@ func ExampleConversationsClient_CompleteConversation() { } func ExampleConversationsClient_ListMessages() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewConversationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListMessagesRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/apiv2/doc.go b/dialogflow/apiv2/doc.go index 155ba3a48c8a..82c31b85329c 100644 --- a/dialogflow/apiv2/doc.go +++ b/dialogflow/apiv2/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package dialogflow // import "cloud.google.com/go/dialogflow/apiv2" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/dialogflow/apiv2/documents_client.go b/dialogflow/apiv2/documents_client.go index d267c7e507af..f01800f60ac0 100644 --- a/dialogflow/apiv2/documents_client.go +++ b/dialogflow/apiv2/documents_client.go @@ -50,7 +50,7 @@ type DocumentsCallOptions struct { ReloadDocument []gax.CallOption } -func defaultDocumentsClientOptions() []option.ClientOption { +func defaultDocumentsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -133,37 +133,165 @@ func defaultDocumentsCallOptions() *DocumentsCallOptions { } } +// internalDocumentsClient is an interface that defines the methods availaible from Dialogflow API. +type internalDocumentsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListDocuments(context.Context, *dialogflowpb.ListDocumentsRequest, ...gax.CallOption) *DocumentIterator + GetDocument(context.Context, *dialogflowpb.GetDocumentRequest, ...gax.CallOption) (*dialogflowpb.Document, error) + CreateDocument(context.Context, *dialogflowpb.CreateDocumentRequest, ...gax.CallOption) (*CreateDocumentOperation, error) + CreateDocumentOperation(name string) *CreateDocumentOperation + DeleteDocument(context.Context, *dialogflowpb.DeleteDocumentRequest, ...gax.CallOption) (*DeleteDocumentOperation, error) + DeleteDocumentOperation(name string) *DeleteDocumentOperation + UpdateDocument(context.Context, *dialogflowpb.UpdateDocumentRequest, ...gax.CallOption) (*UpdateDocumentOperation, error) + UpdateDocumentOperation(name string) *UpdateDocumentOperation + ReloadDocument(context.Context, *dialogflowpb.ReloadDocumentRequest, ...gax.CallOption) (*ReloadDocumentOperation, error) + ReloadDocumentOperation(name string) *ReloadDocumentOperation +} + // DocumentsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing knowledge Documents. type DocumentsClient struct { + // The internal transport-dependent client. + internalClient internalDocumentsClient + + // The call options for this service. + CallOptions *DocumentsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *DocumentsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *DocumentsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *DocumentsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListDocuments returns the list of all documents of the knowledge base. +func (c *DocumentsClient) ListDocuments(ctx context.Context, req *dialogflowpb.ListDocumentsRequest, opts ...gax.CallOption) *DocumentIterator { + return c.internalClient.ListDocuments(ctx, req, opts...) +} + +// GetDocument retrieves the specified document. +func (c *DocumentsClient) GetDocument(ctx context.Context, req *dialogflowpb.GetDocumentRequest, opts ...gax.CallOption) (*dialogflowpb.Document, error) { + return c.internalClient.GetDocument(ctx, req, opts...) +} + +// CreateDocument creates a new document. +// +// Operation +func (c *DocumentsClient) CreateDocument(ctx context.Context, req *dialogflowpb.CreateDocumentRequest, opts ...gax.CallOption) (*CreateDocumentOperation, error) { + return c.internalClient.CreateDocument(ctx, req, opts...) +} + +// CreateDocumentOperation returns a new CreateDocumentOperation from a given name. +// The name must be that of a previously created CreateDocumentOperation, possibly from a different process. +func (c *DocumentsClient) CreateDocumentOperation(name string) *CreateDocumentOperation { + return c.internalClient.CreateDocumentOperation(name) +} + +// DeleteDocument deletes the specified document. +// +// Operation +func (c *DocumentsClient) DeleteDocument(ctx context.Context, req *dialogflowpb.DeleteDocumentRequest, opts ...gax.CallOption) (*DeleteDocumentOperation, error) { + return c.internalClient.DeleteDocument(ctx, req, opts...) +} + +// DeleteDocumentOperation returns a new DeleteDocumentOperation from a given name. +// The name must be that of a previously created DeleteDocumentOperation, possibly from a different process. +func (c *DocumentsClient) DeleteDocumentOperation(name string) *DeleteDocumentOperation { + return c.internalClient.DeleteDocumentOperation(name) +} + +// UpdateDocument updates the specified document. +// +// Operation +func (c *DocumentsClient) UpdateDocument(ctx context.Context, req *dialogflowpb.UpdateDocumentRequest, opts ...gax.CallOption) (*UpdateDocumentOperation, error) { + return c.internalClient.UpdateDocument(ctx, req, opts...) +} + +// UpdateDocumentOperation returns a new UpdateDocumentOperation from a given name. +// The name must be that of a previously created UpdateDocumentOperation, possibly from a different process. +func (c *DocumentsClient) UpdateDocumentOperation(name string) *UpdateDocumentOperation { + return c.internalClient.UpdateDocumentOperation(name) +} + +// ReloadDocument reloads the specified document from its specified source, content_uri or +// content. The previously loaded content of the document will be deleted. +// Note: Even when the content of the document has not changed, there still +// may be side effects because of internal implementation changes. +// +// Note: The projects.agent.knowledgeBases.documents resource is deprecated; +// only use projects.knowledgeBases.documents. +// +// Operation +func (c *DocumentsClient) ReloadDocument(ctx context.Context, req *dialogflowpb.ReloadDocumentRequest, opts ...gax.CallOption) (*ReloadDocumentOperation, error) { + return c.internalClient.ReloadDocument(ctx, req, opts...) +} + +// ReloadDocumentOperation returns a new ReloadDocumentOperation from a given name. +// The name must be that of a previously created ReloadDocumentOperation, possibly from a different process. +func (c *DocumentsClient) ReloadDocumentOperation(name string) *ReloadDocumentOperation { + return c.internalClient.ReloadDocumentOperation(name) +} + +// documentsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type documentsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing DocumentsClient + CallOptions **DocumentsCallOptions + // The gRPC API client. documentsClient dialogflowpb.DocumentsClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *DocumentsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewDocumentsClient creates a new documents client. +// NewDocumentsClient creates a new documents client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing knowledge Documents. func NewDocumentsClient(ctx context.Context, opts ...option.ClientOption) (*DocumentsClient, error) { - clientOpts := defaultDocumentsClientOptions() - + clientOpts := defaultDocumentsGRPCClientOptions() if newDocumentsClientHook != nil { hookOpts, err := newDocumentsClientHook(ctx, clientHookParams{}) if err != nil { @@ -181,16 +309,19 @@ func NewDocumentsClient(ctx context.Context, opts ...option.ClientOption) (*Docu if err != nil { return nil, err } - c := &DocumentsClient{ + client := DocumentsClient{CallOptions: defaultDocumentsCallOptions()} + + c := &documentsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultDocumentsCallOptions(), - - documentsClient: dialogflowpb.NewDocumentsClient(connPool), + documentsClient: dialogflowpb.NewDocumentsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -200,36 +331,36 @@ func NewDocumentsClient(ctx context.Context, opts ...option.ClientOption) (*Docu // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *DocumentsClient) Connection() *grpc.ClientConn { +func (c *documentsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *DocumentsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *DocumentsClient) setGoogleClientInfo(keyval ...string) { +func (c *documentsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListDocuments returns the list of all documents of the knowledge base. -func (c *DocumentsClient) ListDocuments(ctx context.Context, req *dialogflowpb.ListDocumentsRequest, opts ...gax.CallOption) *DocumentIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *documentsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *documentsGRPCClient) ListDocuments(ctx context.Context, req *dialogflowpb.ListDocumentsRequest, opts ...gax.CallOption) *DocumentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDocuments[0:len(c.CallOptions.ListDocuments):len(c.CallOptions.ListDocuments)], opts...) + opts = append((*c.CallOptions).ListDocuments[0:len((*c.CallOptions).ListDocuments):len((*c.CallOptions).ListDocuments)], opts...) it := &DocumentIterator{} req = proto.Clone(req).(*dialogflowpb.ListDocumentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Document, string, error) { @@ -266,8 +397,7 @@ func (c *DocumentsClient) ListDocuments(ctx context.Context, req *dialogflowpb.L return it } -// GetDocument retrieves the specified document. -func (c *DocumentsClient) GetDocument(ctx context.Context, req *dialogflowpb.GetDocumentRequest, opts ...gax.CallOption) (*dialogflowpb.Document, error) { +func (c *documentsGRPCClient) GetDocument(ctx context.Context, req *dialogflowpb.GetDocumentRequest, opts ...gax.CallOption) (*dialogflowpb.Document, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -275,7 +405,7 @@ func (c *DocumentsClient) GetDocument(ctx context.Context, req *dialogflowpb.Get } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetDocument[0:len(c.CallOptions.GetDocument):len(c.CallOptions.GetDocument)], opts...) + opts = append((*c.CallOptions).GetDocument[0:len((*c.CallOptions).GetDocument):len((*c.CallOptions).GetDocument)], opts...) var resp *dialogflowpb.Document err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -288,11 +418,7 @@ func (c *DocumentsClient) GetDocument(ctx context.Context, req *dialogflowpb.Get return resp, nil } -// CreateDocument creates a new document. -// -// Operation -func (c *DocumentsClient) CreateDocument(ctx context.Context, req *dialogflowpb.CreateDocumentRequest, opts ...gax.CallOption) (*CreateDocumentOperation, error) { +func (c *documentsGRPCClient) CreateDocument(ctx context.Context, req *dialogflowpb.CreateDocumentRequest, opts ...gax.CallOption) (*CreateDocumentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -300,7 +426,7 @@ func (c *DocumentsClient) CreateDocument(ctx context.Context, req *dialogflowpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateDocument[0:len(c.CallOptions.CreateDocument):len(c.CallOptions.CreateDocument)], opts...) + opts = append((*c.CallOptions).CreateDocument[0:len((*c.CallOptions).CreateDocument):len((*c.CallOptions).CreateDocument)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -311,15 +437,11 @@ func (c *DocumentsClient) CreateDocument(ctx context.Context, req *dialogflowpb. return nil, err } return &CreateDocumentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteDocument deletes the specified document. -// -// Operation -func (c *DocumentsClient) DeleteDocument(ctx context.Context, req *dialogflowpb.DeleteDocumentRequest, opts ...gax.CallOption) (*DeleteDocumentOperation, error) { +func (c *documentsGRPCClient) DeleteDocument(ctx context.Context, req *dialogflowpb.DeleteDocumentRequest, opts ...gax.CallOption) (*DeleteDocumentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -327,7 +449,7 @@ func (c *DocumentsClient) DeleteDocument(ctx context.Context, req *dialogflowpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteDocument[0:len(c.CallOptions.DeleteDocument):len(c.CallOptions.DeleteDocument)], opts...) + opts = append((*c.CallOptions).DeleteDocument[0:len((*c.CallOptions).DeleteDocument):len((*c.CallOptions).DeleteDocument)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -338,15 +460,11 @@ func (c *DocumentsClient) DeleteDocument(ctx context.Context, req *dialogflowpb. return nil, err } return &DeleteDocumentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateDocument updates the specified document. -// -// Operation -func (c *DocumentsClient) UpdateDocument(ctx context.Context, req *dialogflowpb.UpdateDocumentRequest, opts ...gax.CallOption) (*UpdateDocumentOperation, error) { +func (c *documentsGRPCClient) UpdateDocument(ctx context.Context, req *dialogflowpb.UpdateDocumentRequest, opts ...gax.CallOption) (*UpdateDocumentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -354,7 +472,7 @@ func (c *DocumentsClient) UpdateDocument(ctx context.Context, req *dialogflowpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "document.name", url.QueryEscape(req.GetDocument().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateDocument[0:len(c.CallOptions.UpdateDocument):len(c.CallOptions.UpdateDocument)], opts...) + opts = append((*c.CallOptions).UpdateDocument[0:len((*c.CallOptions).UpdateDocument):len((*c.CallOptions).UpdateDocument)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -365,21 +483,11 @@ func (c *DocumentsClient) UpdateDocument(ctx context.Context, req *dialogflowpb. return nil, err } return &UpdateDocumentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ReloadDocument reloads the specified document from its specified source, content_uri or -// content. The previously loaded content of the document will be deleted. -// Note: Even when the content of the document has not changed, there still -// may be side effects because of internal implementation changes. -// -// Note: The projects.agent.knowledgeBases.documents resource is deprecated; -// only use projects.knowledgeBases.documents. -// -// Operation -func (c *DocumentsClient) ReloadDocument(ctx context.Context, req *dialogflowpb.ReloadDocumentRequest, opts ...gax.CallOption) (*ReloadDocumentOperation, error) { +func (c *documentsGRPCClient) ReloadDocument(ctx context.Context, req *dialogflowpb.ReloadDocumentRequest, opts ...gax.CallOption) (*ReloadDocumentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -387,7 +495,7 @@ func (c *DocumentsClient) ReloadDocument(ctx context.Context, req *dialogflowpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ReloadDocument[0:len(c.CallOptions.ReloadDocument):len(c.CallOptions.ReloadDocument)], opts...) + opts = append((*c.CallOptions).ReloadDocument[0:len((*c.CallOptions).ReloadDocument):len((*c.CallOptions).ReloadDocument)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -398,7 +506,7 @@ func (c *DocumentsClient) ReloadDocument(ctx context.Context, req *dialogflowpb. return nil, err } return &ReloadDocumentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -409,9 +517,9 @@ type CreateDocumentOperation struct { // CreateDocumentOperation returns a new CreateDocumentOperation from a given name. // The name must be that of a previously created CreateDocumentOperation, possibly from a different process. -func (c *DocumentsClient) CreateDocumentOperation(name string) *CreateDocumentOperation { +func (c *documentsGRPCClient) CreateDocumentOperation(name string) *CreateDocumentOperation { return &CreateDocumentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -478,9 +586,9 @@ type DeleteDocumentOperation struct { // DeleteDocumentOperation returns a new DeleteDocumentOperation from a given name. // The name must be that of a previously created DeleteDocumentOperation, possibly from a different process. -func (c *DocumentsClient) DeleteDocumentOperation(name string) *DeleteDocumentOperation { +func (c *documentsGRPCClient) DeleteDocumentOperation(name string) *DeleteDocumentOperation { return &DeleteDocumentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -536,9 +644,9 @@ type ReloadDocumentOperation struct { // ReloadDocumentOperation returns a new ReloadDocumentOperation from a given name. // The name must be that of a previously created ReloadDocumentOperation, possibly from a different process. -func (c *DocumentsClient) ReloadDocumentOperation(name string) *ReloadDocumentOperation { +func (c *documentsGRPCClient) ReloadDocumentOperation(name string) *ReloadDocumentOperation { return &ReloadDocumentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -605,9 +713,9 @@ type UpdateDocumentOperation struct { // UpdateDocumentOperation returns a new UpdateDocumentOperation from a given name. // The name must be that of a previously created UpdateDocumentOperation, possibly from a different process. -func (c *DocumentsClient) UpdateDocumentOperation(name string) *UpdateDocumentOperation { +func (c *documentsGRPCClient) UpdateDocumentOperation(name string) *UpdateDocumentOperation { return &UpdateDocumentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dialogflow/apiv2/documents_client_example_test.go b/dialogflow/apiv2/documents_client_example_test.go index 0a31650a548b..a23ae09ac4e7 100644 --- a/dialogflow/apiv2/documents_client_example_test.go +++ b/dialogflow/apiv2/documents_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewDocumentsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleDocumentsClient_ListDocuments() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewDocumentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListDocumentsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleDocumentsClient_ListDocuments() { } func ExampleDocumentsClient_GetDocument() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewDocumentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetDocumentRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleDocumentsClient_GetDocument() { } func ExampleDocumentsClient_CreateDocument() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewDocumentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateDocumentRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleDocumentsClient_CreateDocument() { } func ExampleDocumentsClient_DeleteDocument() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewDocumentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteDocumentRequest{ // TODO: Fill request struct fields. @@ -130,13 +127,12 @@ func ExampleDocumentsClient_DeleteDocument() { } func ExampleDocumentsClient_UpdateDocument() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewDocumentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateDocumentRequest{ // TODO: Fill request struct fields. @@ -155,13 +151,12 @@ func ExampleDocumentsClient_UpdateDocument() { } func ExampleDocumentsClient_ReloadDocument() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewDocumentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ReloadDocumentRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/apiv2/entity_types_client.go b/dialogflow/apiv2/entity_types_client.go index 3b9fc2fcdcf7..6ed73c76775b 100644 --- a/dialogflow/apiv2/entity_types_client.go +++ b/dialogflow/apiv2/entity_types_client.go @@ -55,7 +55,7 @@ type EntityTypesCallOptions struct { BatchDeleteEntities []gax.CallOption } -func defaultEntityTypesClientOptions() []option.ClientOption { +func defaultEntityTypesGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -182,37 +182,190 @@ func defaultEntityTypesCallOptions() *EntityTypesCallOptions { } } +// internalEntityTypesClient is an interface that defines the methods availaible from Dialogflow API. +type internalEntityTypesClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListEntityTypes(context.Context, *dialogflowpb.ListEntityTypesRequest, ...gax.CallOption) *EntityTypeIterator + GetEntityType(context.Context, *dialogflowpb.GetEntityTypeRequest, ...gax.CallOption) (*dialogflowpb.EntityType, error) + CreateEntityType(context.Context, *dialogflowpb.CreateEntityTypeRequest, ...gax.CallOption) (*dialogflowpb.EntityType, error) + UpdateEntityType(context.Context, *dialogflowpb.UpdateEntityTypeRequest, ...gax.CallOption) (*dialogflowpb.EntityType, error) + DeleteEntityType(context.Context, *dialogflowpb.DeleteEntityTypeRequest, ...gax.CallOption) error + BatchUpdateEntityTypes(context.Context, *dialogflowpb.BatchUpdateEntityTypesRequest, ...gax.CallOption) (*BatchUpdateEntityTypesOperation, error) + BatchUpdateEntityTypesOperation(name string) *BatchUpdateEntityTypesOperation + BatchDeleteEntityTypes(context.Context, *dialogflowpb.BatchDeleteEntityTypesRequest, ...gax.CallOption) (*BatchDeleteEntityTypesOperation, error) + BatchDeleteEntityTypesOperation(name string) *BatchDeleteEntityTypesOperation + BatchCreateEntities(context.Context, *dialogflowpb.BatchCreateEntitiesRequest, ...gax.CallOption) (*BatchCreateEntitiesOperation, error) + BatchCreateEntitiesOperation(name string) *BatchCreateEntitiesOperation + BatchUpdateEntities(context.Context, *dialogflowpb.BatchUpdateEntitiesRequest, ...gax.CallOption) (*BatchUpdateEntitiesOperation, error) + BatchUpdateEntitiesOperation(name string) *BatchUpdateEntitiesOperation + BatchDeleteEntities(context.Context, *dialogflowpb.BatchDeleteEntitiesRequest, ...gax.CallOption) (*BatchDeleteEntitiesOperation, error) + BatchDeleteEntitiesOperation(name string) *BatchDeleteEntitiesOperation +} + // EntityTypesClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing EntityTypes. type EntityTypesClient struct { + // The internal transport-dependent client. + internalClient internalEntityTypesClient + + // The call options for this service. + CallOptions *EntityTypesCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *EntityTypesClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *EntityTypesClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *EntityTypesClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListEntityTypes returns the list of all entity types in the specified agent. +func (c *EntityTypesClient) ListEntityTypes(ctx context.Context, req *dialogflowpb.ListEntityTypesRequest, opts ...gax.CallOption) *EntityTypeIterator { + return c.internalClient.ListEntityTypes(ctx, req, opts...) +} + +// GetEntityType retrieves the specified entity type. +func (c *EntityTypesClient) GetEntityType(ctx context.Context, req *dialogflowpb.GetEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.EntityType, error) { + return c.internalClient.GetEntityType(ctx, req, opts...) +} + +// CreateEntityType creates an entity type in the specified agent. +func (c *EntityTypesClient) CreateEntityType(ctx context.Context, req *dialogflowpb.CreateEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.EntityType, error) { + return c.internalClient.CreateEntityType(ctx, req, opts...) +} + +// UpdateEntityType updates the specified entity type. +func (c *EntityTypesClient) UpdateEntityType(ctx context.Context, req *dialogflowpb.UpdateEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.EntityType, error) { + return c.internalClient.UpdateEntityType(ctx, req, opts...) +} + +// DeleteEntityType deletes the specified entity type. +func (c *EntityTypesClient) DeleteEntityType(ctx context.Context, req *dialogflowpb.DeleteEntityTypeRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteEntityType(ctx, req, opts...) +} + +// BatchUpdateEntityTypes updates/Creates multiple entity types in the specified agent. +// +// Operation +func (c *EntityTypesClient) BatchUpdateEntityTypes(ctx context.Context, req *dialogflowpb.BatchUpdateEntityTypesRequest, opts ...gax.CallOption) (*BatchUpdateEntityTypesOperation, error) { + return c.internalClient.BatchUpdateEntityTypes(ctx, req, opts...) +} + +// BatchUpdateEntityTypesOperation returns a new BatchUpdateEntityTypesOperation from a given name. +// The name must be that of a previously created BatchUpdateEntityTypesOperation, possibly from a different process. +func (c *EntityTypesClient) BatchUpdateEntityTypesOperation(name string) *BatchUpdateEntityTypesOperation { + return c.internalClient.BatchUpdateEntityTypesOperation(name) +} + +// BatchDeleteEntityTypes deletes entity types in the specified agent. +// +// Operation +func (c *EntityTypesClient) BatchDeleteEntityTypes(ctx context.Context, req *dialogflowpb.BatchDeleteEntityTypesRequest, opts ...gax.CallOption) (*BatchDeleteEntityTypesOperation, error) { + return c.internalClient.BatchDeleteEntityTypes(ctx, req, opts...) +} + +// BatchDeleteEntityTypesOperation returns a new BatchDeleteEntityTypesOperation from a given name. +// The name must be that of a previously created BatchDeleteEntityTypesOperation, possibly from a different process. +func (c *EntityTypesClient) BatchDeleteEntityTypesOperation(name string) *BatchDeleteEntityTypesOperation { + return c.internalClient.BatchDeleteEntityTypesOperation(name) +} + +// BatchCreateEntities creates multiple new entities in the specified entity type. +// +// Operation +func (c *EntityTypesClient) BatchCreateEntities(ctx context.Context, req *dialogflowpb.BatchCreateEntitiesRequest, opts ...gax.CallOption) (*BatchCreateEntitiesOperation, error) { + return c.internalClient.BatchCreateEntities(ctx, req, opts...) +} + +// BatchCreateEntitiesOperation returns a new BatchCreateEntitiesOperation from a given name. +// The name must be that of a previously created BatchCreateEntitiesOperation, possibly from a different process. +func (c *EntityTypesClient) BatchCreateEntitiesOperation(name string) *BatchCreateEntitiesOperation { + return c.internalClient.BatchCreateEntitiesOperation(name) +} + +// BatchUpdateEntities updates or creates multiple entities in the specified entity type. This +// method does not affect entities in the entity type that aren’t explicitly +// specified in the request. +// +// Operation +func (c *EntityTypesClient) BatchUpdateEntities(ctx context.Context, req *dialogflowpb.BatchUpdateEntitiesRequest, opts ...gax.CallOption) (*BatchUpdateEntitiesOperation, error) { + return c.internalClient.BatchUpdateEntities(ctx, req, opts...) +} + +// BatchUpdateEntitiesOperation returns a new BatchUpdateEntitiesOperation from a given name. +// The name must be that of a previously created BatchUpdateEntitiesOperation, possibly from a different process. +func (c *EntityTypesClient) BatchUpdateEntitiesOperation(name string) *BatchUpdateEntitiesOperation { + return c.internalClient.BatchUpdateEntitiesOperation(name) +} + +// BatchDeleteEntities deletes entities in the specified entity type. +// +// Operation +func (c *EntityTypesClient) BatchDeleteEntities(ctx context.Context, req *dialogflowpb.BatchDeleteEntitiesRequest, opts ...gax.CallOption) (*BatchDeleteEntitiesOperation, error) { + return c.internalClient.BatchDeleteEntities(ctx, req, opts...) +} + +// BatchDeleteEntitiesOperation returns a new BatchDeleteEntitiesOperation from a given name. +// The name must be that of a previously created BatchDeleteEntitiesOperation, possibly from a different process. +func (c *EntityTypesClient) BatchDeleteEntitiesOperation(name string) *BatchDeleteEntitiesOperation { + return c.internalClient.BatchDeleteEntitiesOperation(name) +} + +// entityTypesGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type entityTypesGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing EntityTypesClient + CallOptions **EntityTypesCallOptions + // The gRPC API client. entityTypesClient dialogflowpb.EntityTypesClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *EntityTypesCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewEntityTypesClient creates a new entity types client. +// NewEntityTypesClient creates a new entity types client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing EntityTypes. func NewEntityTypesClient(ctx context.Context, opts ...option.ClientOption) (*EntityTypesClient, error) { - clientOpts := defaultEntityTypesClientOptions() - + clientOpts := defaultEntityTypesGRPCClientOptions() if newEntityTypesClientHook != nil { hookOpts, err := newEntityTypesClientHook(ctx, clientHookParams{}) if err != nil { @@ -230,16 +383,19 @@ func NewEntityTypesClient(ctx context.Context, opts ...option.ClientOption) (*En if err != nil { return nil, err } - c := &EntityTypesClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultEntityTypesCallOptions(), + client := EntityTypesClient{CallOptions: defaultEntityTypesCallOptions()} + c := &entityTypesGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, entityTypesClient: dialogflowpb.NewEntityTypesClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -249,36 +405,36 @@ func NewEntityTypesClient(ctx context.Context, opts ...option.ClientOption) (*En // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *EntityTypesClient) Connection() *grpc.ClientConn { +func (c *entityTypesGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *EntityTypesClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *EntityTypesClient) setGoogleClientInfo(keyval ...string) { +func (c *entityTypesGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListEntityTypes returns the list of all entity types in the specified agent. -func (c *EntityTypesClient) ListEntityTypes(ctx context.Context, req *dialogflowpb.ListEntityTypesRequest, opts ...gax.CallOption) *EntityTypeIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *entityTypesGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *entityTypesGRPCClient) ListEntityTypes(ctx context.Context, req *dialogflowpb.ListEntityTypesRequest, opts ...gax.CallOption) *EntityTypeIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListEntityTypes[0:len(c.CallOptions.ListEntityTypes):len(c.CallOptions.ListEntityTypes)], opts...) + opts = append((*c.CallOptions).ListEntityTypes[0:len((*c.CallOptions).ListEntityTypes):len((*c.CallOptions).ListEntityTypes)], opts...) it := &EntityTypeIterator{} req = proto.Clone(req).(*dialogflowpb.ListEntityTypesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.EntityType, string, error) { @@ -315,8 +471,7 @@ func (c *EntityTypesClient) ListEntityTypes(ctx context.Context, req *dialogflow return it } -// GetEntityType retrieves the specified entity type. -func (c *EntityTypesClient) GetEntityType(ctx context.Context, req *dialogflowpb.GetEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.EntityType, error) { +func (c *entityTypesGRPCClient) GetEntityType(ctx context.Context, req *dialogflowpb.GetEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.EntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -324,7 +479,7 @@ func (c *EntityTypesClient) GetEntityType(ctx context.Context, req *dialogflowpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEntityType[0:len(c.CallOptions.GetEntityType):len(c.CallOptions.GetEntityType)], opts...) + opts = append((*c.CallOptions).GetEntityType[0:len((*c.CallOptions).GetEntityType):len((*c.CallOptions).GetEntityType)], opts...) var resp *dialogflowpb.EntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -337,8 +492,7 @@ func (c *EntityTypesClient) GetEntityType(ctx context.Context, req *dialogflowpb return resp, nil } -// CreateEntityType creates an entity type in the specified agent. -func (c *EntityTypesClient) CreateEntityType(ctx context.Context, req *dialogflowpb.CreateEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.EntityType, error) { +func (c *entityTypesGRPCClient) CreateEntityType(ctx context.Context, req *dialogflowpb.CreateEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.EntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -346,7 +500,7 @@ func (c *EntityTypesClient) CreateEntityType(ctx context.Context, req *dialogflo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateEntityType[0:len(c.CallOptions.CreateEntityType):len(c.CallOptions.CreateEntityType)], opts...) + opts = append((*c.CallOptions).CreateEntityType[0:len((*c.CallOptions).CreateEntityType):len((*c.CallOptions).CreateEntityType)], opts...) var resp *dialogflowpb.EntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -359,8 +513,7 @@ func (c *EntityTypesClient) CreateEntityType(ctx context.Context, req *dialogflo return resp, nil } -// UpdateEntityType updates the specified entity type. -func (c *EntityTypesClient) UpdateEntityType(ctx context.Context, req *dialogflowpb.UpdateEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.EntityType, error) { +func (c *entityTypesGRPCClient) UpdateEntityType(ctx context.Context, req *dialogflowpb.UpdateEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.EntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -368,7 +521,7 @@ func (c *EntityTypesClient) UpdateEntityType(ctx context.Context, req *dialogflo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "entity_type.name", url.QueryEscape(req.GetEntityType().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateEntityType[0:len(c.CallOptions.UpdateEntityType):len(c.CallOptions.UpdateEntityType)], opts...) + opts = append((*c.CallOptions).UpdateEntityType[0:len((*c.CallOptions).UpdateEntityType):len((*c.CallOptions).UpdateEntityType)], opts...) var resp *dialogflowpb.EntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -381,8 +534,7 @@ func (c *EntityTypesClient) UpdateEntityType(ctx context.Context, req *dialogflo return resp, nil } -// DeleteEntityType deletes the specified entity type. -func (c *EntityTypesClient) DeleteEntityType(ctx context.Context, req *dialogflowpb.DeleteEntityTypeRequest, opts ...gax.CallOption) error { +func (c *entityTypesGRPCClient) DeleteEntityType(ctx context.Context, req *dialogflowpb.DeleteEntityTypeRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -390,7 +542,7 @@ func (c *EntityTypesClient) DeleteEntityType(ctx context.Context, req *dialogflo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteEntityType[0:len(c.CallOptions.DeleteEntityType):len(c.CallOptions.DeleteEntityType)], opts...) + opts = append((*c.CallOptions).DeleteEntityType[0:len((*c.CallOptions).DeleteEntityType):len((*c.CallOptions).DeleteEntityType)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.entityTypesClient.DeleteEntityType(ctx, req, settings.GRPC...) @@ -399,10 +551,7 @@ func (c *EntityTypesClient) DeleteEntityType(ctx context.Context, req *dialogflo return err } -// BatchUpdateEntityTypes updates/Creates multiple entity types in the specified agent. -// -// Operation -func (c *EntityTypesClient) BatchUpdateEntityTypes(ctx context.Context, req *dialogflowpb.BatchUpdateEntityTypesRequest, opts ...gax.CallOption) (*BatchUpdateEntityTypesOperation, error) { +func (c *entityTypesGRPCClient) BatchUpdateEntityTypes(ctx context.Context, req *dialogflowpb.BatchUpdateEntityTypesRequest, opts ...gax.CallOption) (*BatchUpdateEntityTypesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -410,7 +559,7 @@ func (c *EntityTypesClient) BatchUpdateEntityTypes(ctx context.Context, req *dia } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchUpdateEntityTypes[0:len(c.CallOptions.BatchUpdateEntityTypes):len(c.CallOptions.BatchUpdateEntityTypes)], opts...) + opts = append((*c.CallOptions).BatchUpdateEntityTypes[0:len((*c.CallOptions).BatchUpdateEntityTypes):len((*c.CallOptions).BatchUpdateEntityTypes)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -421,14 +570,11 @@ func (c *EntityTypesClient) BatchUpdateEntityTypes(ctx context.Context, req *dia return nil, err } return &BatchUpdateEntityTypesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// BatchDeleteEntityTypes deletes entity types in the specified agent. -// -// Operation -func (c *EntityTypesClient) BatchDeleteEntityTypes(ctx context.Context, req *dialogflowpb.BatchDeleteEntityTypesRequest, opts ...gax.CallOption) (*BatchDeleteEntityTypesOperation, error) { +func (c *entityTypesGRPCClient) BatchDeleteEntityTypes(ctx context.Context, req *dialogflowpb.BatchDeleteEntityTypesRequest, opts ...gax.CallOption) (*BatchDeleteEntityTypesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -436,7 +582,7 @@ func (c *EntityTypesClient) BatchDeleteEntityTypes(ctx context.Context, req *dia } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchDeleteEntityTypes[0:len(c.CallOptions.BatchDeleteEntityTypes):len(c.CallOptions.BatchDeleteEntityTypes)], opts...) + opts = append((*c.CallOptions).BatchDeleteEntityTypes[0:len((*c.CallOptions).BatchDeleteEntityTypes):len((*c.CallOptions).BatchDeleteEntityTypes)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -447,14 +593,11 @@ func (c *EntityTypesClient) BatchDeleteEntityTypes(ctx context.Context, req *dia return nil, err } return &BatchDeleteEntityTypesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// BatchCreateEntities creates multiple new entities in the specified entity type. -// -// Operation -func (c *EntityTypesClient) BatchCreateEntities(ctx context.Context, req *dialogflowpb.BatchCreateEntitiesRequest, opts ...gax.CallOption) (*BatchCreateEntitiesOperation, error) { +func (c *entityTypesGRPCClient) BatchCreateEntities(ctx context.Context, req *dialogflowpb.BatchCreateEntitiesRequest, opts ...gax.CallOption) (*BatchCreateEntitiesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -462,7 +605,7 @@ func (c *EntityTypesClient) BatchCreateEntities(ctx context.Context, req *dialog } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchCreateEntities[0:len(c.CallOptions.BatchCreateEntities):len(c.CallOptions.BatchCreateEntities)], opts...) + opts = append((*c.CallOptions).BatchCreateEntities[0:len((*c.CallOptions).BatchCreateEntities):len((*c.CallOptions).BatchCreateEntities)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -473,16 +616,11 @@ func (c *EntityTypesClient) BatchCreateEntities(ctx context.Context, req *dialog return nil, err } return &BatchCreateEntitiesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// BatchUpdateEntities updates or creates multiple entities in the specified entity type. This -// method does not affect entities in the entity type that aren’t explicitly -// specified in the request. -// -// Operation -func (c *EntityTypesClient) BatchUpdateEntities(ctx context.Context, req *dialogflowpb.BatchUpdateEntitiesRequest, opts ...gax.CallOption) (*BatchUpdateEntitiesOperation, error) { +func (c *entityTypesGRPCClient) BatchUpdateEntities(ctx context.Context, req *dialogflowpb.BatchUpdateEntitiesRequest, opts ...gax.CallOption) (*BatchUpdateEntitiesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -490,7 +628,7 @@ func (c *EntityTypesClient) BatchUpdateEntities(ctx context.Context, req *dialog } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchUpdateEntities[0:len(c.CallOptions.BatchUpdateEntities):len(c.CallOptions.BatchUpdateEntities)], opts...) + opts = append((*c.CallOptions).BatchUpdateEntities[0:len((*c.CallOptions).BatchUpdateEntities):len((*c.CallOptions).BatchUpdateEntities)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -501,14 +639,11 @@ func (c *EntityTypesClient) BatchUpdateEntities(ctx context.Context, req *dialog return nil, err } return &BatchUpdateEntitiesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// BatchDeleteEntities deletes entities in the specified entity type. -// -// Operation -func (c *EntityTypesClient) BatchDeleteEntities(ctx context.Context, req *dialogflowpb.BatchDeleteEntitiesRequest, opts ...gax.CallOption) (*BatchDeleteEntitiesOperation, error) { +func (c *entityTypesGRPCClient) BatchDeleteEntities(ctx context.Context, req *dialogflowpb.BatchDeleteEntitiesRequest, opts ...gax.CallOption) (*BatchDeleteEntitiesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -516,7 +651,7 @@ func (c *EntityTypesClient) BatchDeleteEntities(ctx context.Context, req *dialog } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchDeleteEntities[0:len(c.CallOptions.BatchDeleteEntities):len(c.CallOptions.BatchDeleteEntities)], opts...) + opts = append((*c.CallOptions).BatchDeleteEntities[0:len((*c.CallOptions).BatchDeleteEntities):len((*c.CallOptions).BatchDeleteEntities)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -527,7 +662,7 @@ func (c *EntityTypesClient) BatchDeleteEntities(ctx context.Context, req *dialog return nil, err } return &BatchDeleteEntitiesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -538,9 +673,9 @@ type BatchCreateEntitiesOperation struct { // BatchCreateEntitiesOperation returns a new BatchCreateEntitiesOperation from a given name. // The name must be that of a previously created BatchCreateEntitiesOperation, possibly from a different process. -func (c *EntityTypesClient) BatchCreateEntitiesOperation(name string) *BatchCreateEntitiesOperation { +func (c *entityTypesGRPCClient) BatchCreateEntitiesOperation(name string) *BatchCreateEntitiesOperation { return &BatchCreateEntitiesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -596,9 +731,9 @@ type BatchDeleteEntitiesOperation struct { // BatchDeleteEntitiesOperation returns a new BatchDeleteEntitiesOperation from a given name. // The name must be that of a previously created BatchDeleteEntitiesOperation, possibly from a different process. -func (c *EntityTypesClient) BatchDeleteEntitiesOperation(name string) *BatchDeleteEntitiesOperation { +func (c *entityTypesGRPCClient) BatchDeleteEntitiesOperation(name string) *BatchDeleteEntitiesOperation { return &BatchDeleteEntitiesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -654,9 +789,9 @@ type BatchDeleteEntityTypesOperation struct { // BatchDeleteEntityTypesOperation returns a new BatchDeleteEntityTypesOperation from a given name. // The name must be that of a previously created BatchDeleteEntityTypesOperation, possibly from a different process. -func (c *EntityTypesClient) BatchDeleteEntityTypesOperation(name string) *BatchDeleteEntityTypesOperation { +func (c *entityTypesGRPCClient) BatchDeleteEntityTypesOperation(name string) *BatchDeleteEntityTypesOperation { return &BatchDeleteEntityTypesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -712,9 +847,9 @@ type BatchUpdateEntitiesOperation struct { // BatchUpdateEntitiesOperation returns a new BatchUpdateEntitiesOperation from a given name. // The name must be that of a previously created BatchUpdateEntitiesOperation, possibly from a different process. -func (c *EntityTypesClient) BatchUpdateEntitiesOperation(name string) *BatchUpdateEntitiesOperation { +func (c *entityTypesGRPCClient) BatchUpdateEntitiesOperation(name string) *BatchUpdateEntitiesOperation { return &BatchUpdateEntitiesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -770,9 +905,9 @@ type BatchUpdateEntityTypesOperation struct { // BatchUpdateEntityTypesOperation returns a new BatchUpdateEntityTypesOperation from a given name. // The name must be that of a previously created BatchUpdateEntityTypesOperation, possibly from a different process. -func (c *EntityTypesClient) BatchUpdateEntityTypesOperation(name string) *BatchUpdateEntityTypesOperation { +func (c *entityTypesGRPCClient) BatchUpdateEntityTypesOperation(name string) *BatchUpdateEntityTypesOperation { return &BatchUpdateEntityTypesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dialogflow/apiv2/entity_types_client_example_test.go b/dialogflow/apiv2/entity_types_client_example_test.go index 28cb0e3177b7..02f4025f6a51 100644 --- a/dialogflow/apiv2/entity_types_client_example_test.go +++ b/dialogflow/apiv2/entity_types_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewEntityTypesClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleEntityTypesClient_ListEntityTypes() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListEntityTypesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleEntityTypesClient_ListEntityTypes() { } func ExampleEntityTypesClient_GetEntityType() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetEntityTypeRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleEntityTypesClient_GetEntityType() { } func ExampleEntityTypesClient_CreateEntityType() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateEntityTypeRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleEntityTypesClient_CreateEntityType() { } func ExampleEntityTypesClient_UpdateEntityType() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateEntityTypeRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleEntityTypesClient_DeleteEntityType() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteEntityTypeRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleEntityTypesClient_DeleteEntityType() { } func ExampleEntityTypesClient_BatchUpdateEntityTypes() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.BatchUpdateEntityTypesRequest{ // TODO: Fill request struct fields. @@ -163,13 +160,12 @@ func ExampleEntityTypesClient_BatchUpdateEntityTypes() { } func ExampleEntityTypesClient_BatchDeleteEntityTypes() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.BatchDeleteEntityTypesRequest{ // TODO: Fill request struct fields. @@ -186,13 +182,12 @@ func ExampleEntityTypesClient_BatchDeleteEntityTypes() { } func ExampleEntityTypesClient_BatchCreateEntities() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.BatchCreateEntitiesRequest{ // TODO: Fill request struct fields. @@ -209,13 +204,12 @@ func ExampleEntityTypesClient_BatchCreateEntities() { } func ExampleEntityTypesClient_BatchUpdateEntities() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.BatchUpdateEntitiesRequest{ // TODO: Fill request struct fields. @@ -232,13 +226,12 @@ func ExampleEntityTypesClient_BatchUpdateEntities() { } func ExampleEntityTypesClient_BatchDeleteEntities() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.BatchDeleteEntitiesRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/apiv2/environments_client.go b/dialogflow/apiv2/environments_client.go index 06d20f586495..cf4d6343ee0b 100644 --- a/dialogflow/apiv2/environments_client.go +++ b/dialogflow/apiv2/environments_client.go @@ -47,7 +47,7 @@ type EnvironmentsCallOptions struct { GetEnvironmentHistory []gax.CallOption } -func defaultEnvironmentsClientOptions() []option.ClientOption { +func defaultEnvironmentsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -130,32 +130,120 @@ func defaultEnvironmentsCallOptions() *EnvironmentsCallOptions { } } +// internalEnvironmentsClient is an interface that defines the methods availaible from Dialogflow API. +type internalEnvironmentsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListEnvironments(context.Context, *dialogflowpb.ListEnvironmentsRequest, ...gax.CallOption) *EnvironmentIterator + GetEnvironment(context.Context, *dialogflowpb.GetEnvironmentRequest, ...gax.CallOption) (*dialogflowpb.Environment, error) + CreateEnvironment(context.Context, *dialogflowpb.CreateEnvironmentRequest, ...gax.CallOption) (*dialogflowpb.Environment, error) + UpdateEnvironment(context.Context, *dialogflowpb.UpdateEnvironmentRequest, ...gax.CallOption) (*dialogflowpb.Environment, error) + DeleteEnvironment(context.Context, *dialogflowpb.DeleteEnvironmentRequest, ...gax.CallOption) error + GetEnvironmentHistory(context.Context, *dialogflowpb.GetEnvironmentHistoryRequest, ...gax.CallOption) *EnvironmentHistory_EntryIterator +} + // EnvironmentsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Environments. type EnvironmentsClient struct { + // The internal transport-dependent client. + internalClient internalEnvironmentsClient + + // The call options for this service. + CallOptions *EnvironmentsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *EnvironmentsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *EnvironmentsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *EnvironmentsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListEnvironments returns the list of all non-draft environments of the specified agent. +func (c *EnvironmentsClient) ListEnvironments(ctx context.Context, req *dialogflowpb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { + return c.internalClient.ListEnvironments(ctx, req, opts...) +} + +// GetEnvironment retrieves the specified agent environment. +func (c *EnvironmentsClient) GetEnvironment(ctx context.Context, req *dialogflowpb.GetEnvironmentRequest, opts ...gax.CallOption) (*dialogflowpb.Environment, error) { + return c.internalClient.GetEnvironment(ctx, req, opts...) +} + +// CreateEnvironment creates an agent environment. +func (c *EnvironmentsClient) CreateEnvironment(ctx context.Context, req *dialogflowpb.CreateEnvironmentRequest, opts ...gax.CallOption) (*dialogflowpb.Environment, error) { + return c.internalClient.CreateEnvironment(ctx, req, opts...) +} + +// UpdateEnvironment updates the specified agent environment. +// +// This method allows you to deploy new agent versions into the environment. +// When an environment is pointed to a new agent version by setting +// environment.agent_version, the environment is temporarily set to the +// LOADING state. During that time, the environment keeps on serving the +// previous version of the agent. After the new agent version is done loading, +// the environment is set back to the RUNNING state. +// You can use “-” as Environment ID in environment name to update version +// in “draft” environment. WARNING: this will negate all recent changes to +// draft and can’t be undone. You may want to save the draft to a version +// before calling this function. +func (c *EnvironmentsClient) UpdateEnvironment(ctx context.Context, req *dialogflowpb.UpdateEnvironmentRequest, opts ...gax.CallOption) (*dialogflowpb.Environment, error) { + return c.internalClient.UpdateEnvironment(ctx, req, opts...) +} + +// DeleteEnvironment deletes the specified agent environment. +func (c *EnvironmentsClient) DeleteEnvironment(ctx context.Context, req *dialogflowpb.DeleteEnvironmentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteEnvironment(ctx, req, opts...) +} + +// GetEnvironmentHistory gets the history of the specified environment. +func (c *EnvironmentsClient) GetEnvironmentHistory(ctx context.Context, req *dialogflowpb.GetEnvironmentHistoryRequest, opts ...gax.CallOption) *EnvironmentHistory_EntryIterator { + return c.internalClient.GetEnvironmentHistory(ctx, req, opts...) +} + +// environmentsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type environmentsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing EnvironmentsClient + CallOptions **EnvironmentsCallOptions + // The gRPC API client. environmentsClient dialogflowpb.EnvironmentsClient - // The call options for this service. - CallOptions *EnvironmentsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewEnvironmentsClient creates a new environments client. +// NewEnvironmentsClient creates a new environments client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Environments. func NewEnvironmentsClient(ctx context.Context, opts ...option.ClientOption) (*EnvironmentsClient, error) { - clientOpts := defaultEnvironmentsClientOptions() - + clientOpts := defaultEnvironmentsGRPCClientOptions() if newEnvironmentsClientHook != nil { hookOpts, err := newEnvironmentsClientHook(ctx, clientHookParams{}) if err != nil { @@ -173,45 +261,47 @@ func NewEnvironmentsClient(ctx context.Context, opts ...option.ClientOption) (*E if err != nil { return nil, err } - c := &EnvironmentsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultEnvironmentsCallOptions(), + client := EnvironmentsClient{CallOptions: defaultEnvironmentsCallOptions()} + c := &environmentsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, environmentsClient: dialogflowpb.NewEnvironmentsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *EnvironmentsClient) Connection() *grpc.ClientConn { +func (c *environmentsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *EnvironmentsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *EnvironmentsClient) setGoogleClientInfo(keyval ...string) { +func (c *environmentsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListEnvironments returns the list of all non-draft environments of the specified agent. -func (c *EnvironmentsClient) ListEnvironments(ctx context.Context, req *dialogflowpb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *environmentsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *environmentsGRPCClient) ListEnvironments(ctx context.Context, req *dialogflowpb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListEnvironments[0:len(c.CallOptions.ListEnvironments):len(c.CallOptions.ListEnvironments)], opts...) + opts = append((*c.CallOptions).ListEnvironments[0:len((*c.CallOptions).ListEnvironments):len((*c.CallOptions).ListEnvironments)], opts...) it := &EnvironmentIterator{} req = proto.Clone(req).(*dialogflowpb.ListEnvironmentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Environment, string, error) { @@ -248,8 +338,7 @@ func (c *EnvironmentsClient) ListEnvironments(ctx context.Context, req *dialogfl return it } -// GetEnvironment retrieves the specified agent environment. -func (c *EnvironmentsClient) GetEnvironment(ctx context.Context, req *dialogflowpb.GetEnvironmentRequest, opts ...gax.CallOption) (*dialogflowpb.Environment, error) { +func (c *environmentsGRPCClient) GetEnvironment(ctx context.Context, req *dialogflowpb.GetEnvironmentRequest, opts ...gax.CallOption) (*dialogflowpb.Environment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -257,7 +346,7 @@ func (c *EnvironmentsClient) GetEnvironment(ctx context.Context, req *dialogflow } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEnvironment[0:len(c.CallOptions.GetEnvironment):len(c.CallOptions.GetEnvironment)], opts...) + opts = append((*c.CallOptions).GetEnvironment[0:len((*c.CallOptions).GetEnvironment):len((*c.CallOptions).GetEnvironment)], opts...) var resp *dialogflowpb.Environment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -270,8 +359,7 @@ func (c *EnvironmentsClient) GetEnvironment(ctx context.Context, req *dialogflow return resp, nil } -// CreateEnvironment creates an agent environment. -func (c *EnvironmentsClient) CreateEnvironment(ctx context.Context, req *dialogflowpb.CreateEnvironmentRequest, opts ...gax.CallOption) (*dialogflowpb.Environment, error) { +func (c *environmentsGRPCClient) CreateEnvironment(ctx context.Context, req *dialogflowpb.CreateEnvironmentRequest, opts ...gax.CallOption) (*dialogflowpb.Environment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -279,7 +367,7 @@ func (c *EnvironmentsClient) CreateEnvironment(ctx context.Context, req *dialogf } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateEnvironment[0:len(c.CallOptions.CreateEnvironment):len(c.CallOptions.CreateEnvironment)], opts...) + opts = append((*c.CallOptions).CreateEnvironment[0:len((*c.CallOptions).CreateEnvironment):len((*c.CallOptions).CreateEnvironment)], opts...) var resp *dialogflowpb.Environment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -292,19 +380,7 @@ func (c *EnvironmentsClient) CreateEnvironment(ctx context.Context, req *dialogf return resp, nil } -// UpdateEnvironment updates the specified agent environment. -// -// This method allows you to deploy new agent versions into the environment. -// When an environment is pointed to a new agent version by setting -// environment.agent_version, the environment is temporarily set to the -// LOADING state. During that time, the environment keeps on serving the -// previous version of the agent. After the new agent version is done loading, -// the environment is set back to the RUNNING state. -// You can use “-” as Environment ID in environment name to update version -// in “draft” environment. WARNING: this will negate all recent changes to -// draft and can’t be undone. You may want to save the draft to a version -// before calling this function. -func (c *EnvironmentsClient) UpdateEnvironment(ctx context.Context, req *dialogflowpb.UpdateEnvironmentRequest, opts ...gax.CallOption) (*dialogflowpb.Environment, error) { +func (c *environmentsGRPCClient) UpdateEnvironment(ctx context.Context, req *dialogflowpb.UpdateEnvironmentRequest, opts ...gax.CallOption) (*dialogflowpb.Environment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -312,7 +388,7 @@ func (c *EnvironmentsClient) UpdateEnvironment(ctx context.Context, req *dialogf } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "environment.name", url.QueryEscape(req.GetEnvironment().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateEnvironment[0:len(c.CallOptions.UpdateEnvironment):len(c.CallOptions.UpdateEnvironment)], opts...) + opts = append((*c.CallOptions).UpdateEnvironment[0:len((*c.CallOptions).UpdateEnvironment):len((*c.CallOptions).UpdateEnvironment)], opts...) var resp *dialogflowpb.Environment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -325,8 +401,7 @@ func (c *EnvironmentsClient) UpdateEnvironment(ctx context.Context, req *dialogf return resp, nil } -// DeleteEnvironment deletes the specified agent environment. -func (c *EnvironmentsClient) DeleteEnvironment(ctx context.Context, req *dialogflowpb.DeleteEnvironmentRequest, opts ...gax.CallOption) error { +func (c *environmentsGRPCClient) DeleteEnvironment(ctx context.Context, req *dialogflowpb.DeleteEnvironmentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -334,7 +409,7 @@ func (c *EnvironmentsClient) DeleteEnvironment(ctx context.Context, req *dialogf } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteEnvironment[0:len(c.CallOptions.DeleteEnvironment):len(c.CallOptions.DeleteEnvironment)], opts...) + opts = append((*c.CallOptions).DeleteEnvironment[0:len((*c.CallOptions).DeleteEnvironment):len((*c.CallOptions).DeleteEnvironment)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.environmentsClient.DeleteEnvironment(ctx, req, settings.GRPC...) @@ -343,11 +418,10 @@ func (c *EnvironmentsClient) DeleteEnvironment(ctx context.Context, req *dialogf return err } -// GetEnvironmentHistory gets the history of the specified environment. -func (c *EnvironmentsClient) GetEnvironmentHistory(ctx context.Context, req *dialogflowpb.GetEnvironmentHistoryRequest, opts ...gax.CallOption) *EnvironmentHistory_EntryIterator { +func (c *environmentsGRPCClient) GetEnvironmentHistory(ctx context.Context, req *dialogflowpb.GetEnvironmentHistoryRequest, opts ...gax.CallOption) *EnvironmentHistory_EntryIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEnvironmentHistory[0:len(c.CallOptions.GetEnvironmentHistory):len(c.CallOptions.GetEnvironmentHistory)], opts...) + opts = append((*c.CallOptions).GetEnvironmentHistory[0:len((*c.CallOptions).GetEnvironmentHistory):len((*c.CallOptions).GetEnvironmentHistory)], opts...) it := &EnvironmentHistory_EntryIterator{} req = proto.Clone(req).(*dialogflowpb.GetEnvironmentHistoryRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.EnvironmentHistory_Entry, string, error) { diff --git a/dialogflow/apiv2/environments_client_example_test.go b/dialogflow/apiv2/environments_client_example_test.go index ff319f3ead9c..9731150d713c 100644 --- a/dialogflow/apiv2/environments_client_example_test.go +++ b/dialogflow/apiv2/environments_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewEnvironmentsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleEnvironmentsClient_ListEnvironments() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListEnvironmentsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleEnvironmentsClient_ListEnvironments() { } func ExampleEnvironmentsClient_GetEnvironment() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetEnvironmentRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleEnvironmentsClient_GetEnvironment() { } func ExampleEnvironmentsClient_CreateEnvironment() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateEnvironmentRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleEnvironmentsClient_CreateEnvironment() { } func ExampleEnvironmentsClient_UpdateEnvironment() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateEnvironmentRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleEnvironmentsClient_DeleteEnvironment() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteEnvironmentRequest{ // TODO: Fill request struct fields. @@ -138,14 +136,12 @@ func ExampleEnvironmentsClient_DeleteEnvironment() { } func ExampleEnvironmentsClient_GetEnvironmentHistory() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetEnvironmentHistoryRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/apiv2/fulfillments_client.go b/dialogflow/apiv2/fulfillments_client.go index e12e88551a8e..99e161b70abc 100644 --- a/dialogflow/apiv2/fulfillments_client.go +++ b/dialogflow/apiv2/fulfillments_client.go @@ -41,7 +41,7 @@ type FulfillmentsCallOptions struct { UpdateFulfillment []gax.CallOption } -func defaultFulfillmentsClientOptions() []option.ClientOption { +func defaultFulfillmentsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -80,32 +80,85 @@ func defaultFulfillmentsCallOptions() *FulfillmentsCallOptions { } } +// internalFulfillmentsClient is an interface that defines the methods availaible from Dialogflow API. +type internalFulfillmentsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + GetFulfillment(context.Context, *dialogflowpb.GetFulfillmentRequest, ...gax.CallOption) (*dialogflowpb.Fulfillment, error) + UpdateFulfillment(context.Context, *dialogflowpb.UpdateFulfillmentRequest, ...gax.CallOption) (*dialogflowpb.Fulfillment, error) +} + // FulfillmentsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Fulfillments. type FulfillmentsClient struct { + // The internal transport-dependent client. + internalClient internalFulfillmentsClient + + // The call options for this service. + CallOptions *FulfillmentsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *FulfillmentsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *FulfillmentsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *FulfillmentsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// GetFulfillment retrieves the fulfillment. +func (c *FulfillmentsClient) GetFulfillment(ctx context.Context, req *dialogflowpb.GetFulfillmentRequest, opts ...gax.CallOption) (*dialogflowpb.Fulfillment, error) { + return c.internalClient.GetFulfillment(ctx, req, opts...) +} + +// UpdateFulfillment updates the fulfillment. +func (c *FulfillmentsClient) UpdateFulfillment(ctx context.Context, req *dialogflowpb.UpdateFulfillmentRequest, opts ...gax.CallOption) (*dialogflowpb.Fulfillment, error) { + return c.internalClient.UpdateFulfillment(ctx, req, opts...) +} + +// fulfillmentsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type fulfillmentsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing FulfillmentsClient + CallOptions **FulfillmentsCallOptions + // The gRPC API client. fulfillmentsClient dialogflowpb.FulfillmentsClient - // The call options for this service. - CallOptions *FulfillmentsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewFulfillmentsClient creates a new fulfillments client. +// NewFulfillmentsClient creates a new fulfillments client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Fulfillments. func NewFulfillmentsClient(ctx context.Context, opts ...option.ClientOption) (*FulfillmentsClient, error) { - clientOpts := defaultFulfillmentsClientOptions() - + clientOpts := defaultFulfillmentsGRPCClientOptions() if newFulfillmentsClientHook != nil { hookOpts, err := newFulfillmentsClientHook(ctx, clientHookParams{}) if err != nil { @@ -123,42 +176,44 @@ func NewFulfillmentsClient(ctx context.Context, opts ...option.ClientOption) (*F if err != nil { return nil, err } - c := &FulfillmentsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultFulfillmentsCallOptions(), + client := FulfillmentsClient{CallOptions: defaultFulfillmentsCallOptions()} + c := &fulfillmentsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, fulfillmentsClient: dialogflowpb.NewFulfillmentsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *FulfillmentsClient) Connection() *grpc.ClientConn { +func (c *fulfillmentsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *FulfillmentsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *FulfillmentsClient) setGoogleClientInfo(keyval ...string) { +func (c *fulfillmentsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// GetFulfillment retrieves the fulfillment. -func (c *FulfillmentsClient) GetFulfillment(ctx context.Context, req *dialogflowpb.GetFulfillmentRequest, opts ...gax.CallOption) (*dialogflowpb.Fulfillment, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *fulfillmentsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *fulfillmentsGRPCClient) GetFulfillment(ctx context.Context, req *dialogflowpb.GetFulfillmentRequest, opts ...gax.CallOption) (*dialogflowpb.Fulfillment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -166,7 +221,7 @@ func (c *FulfillmentsClient) GetFulfillment(ctx context.Context, req *dialogflow } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetFulfillment[0:len(c.CallOptions.GetFulfillment):len(c.CallOptions.GetFulfillment)], opts...) + opts = append((*c.CallOptions).GetFulfillment[0:len((*c.CallOptions).GetFulfillment):len((*c.CallOptions).GetFulfillment)], opts...) var resp *dialogflowpb.Fulfillment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -179,8 +234,7 @@ func (c *FulfillmentsClient) GetFulfillment(ctx context.Context, req *dialogflow return resp, nil } -// UpdateFulfillment updates the fulfillment. -func (c *FulfillmentsClient) UpdateFulfillment(ctx context.Context, req *dialogflowpb.UpdateFulfillmentRequest, opts ...gax.CallOption) (*dialogflowpb.Fulfillment, error) { +func (c *fulfillmentsGRPCClient) UpdateFulfillment(ctx context.Context, req *dialogflowpb.UpdateFulfillmentRequest, opts ...gax.CallOption) (*dialogflowpb.Fulfillment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -188,7 +242,7 @@ func (c *FulfillmentsClient) UpdateFulfillment(ctx context.Context, req *dialogf } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "fulfillment.name", url.QueryEscape(req.GetFulfillment().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateFulfillment[0:len(c.CallOptions.UpdateFulfillment):len(c.CallOptions.UpdateFulfillment)], opts...) + opts = append((*c.CallOptions).UpdateFulfillment[0:len((*c.CallOptions).UpdateFulfillment):len((*c.CallOptions).UpdateFulfillment)], opts...) var resp *dialogflowpb.Fulfillment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/dialogflow/apiv2/fulfillments_client_example_test.go b/dialogflow/apiv2/fulfillments_client_example_test.go index 0dac4c5f3480..61d314f293b9 100644 --- a/dialogflow/apiv2/fulfillments_client_example_test.go +++ b/dialogflow/apiv2/fulfillments_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewFulfillmentsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleFulfillmentsClient_GetFulfillment() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewFulfillmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetFulfillmentRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleFulfillmentsClient_GetFulfillment() { } func ExampleFulfillmentsClient_UpdateFulfillment() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewFulfillmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateFulfillmentRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/apiv2/intents_client.go b/dialogflow/apiv2/intents_client.go index dcf461bc7124..32f35d30b238 100644 --- a/dialogflow/apiv2/intents_client.go +++ b/dialogflow/apiv2/intents_client.go @@ -52,7 +52,7 @@ type IntentsCallOptions struct { BatchDeleteIntents []gax.CallOption } -func defaultIntentsClientOptions() []option.ClientOption { +func defaultIntentsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -146,37 +146,143 @@ func defaultIntentsCallOptions() *IntentsCallOptions { } } +// internalIntentsClient is an interface that defines the methods availaible from Dialogflow API. +type internalIntentsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListIntents(context.Context, *dialogflowpb.ListIntentsRequest, ...gax.CallOption) *IntentIterator + GetIntent(context.Context, *dialogflowpb.GetIntentRequest, ...gax.CallOption) (*dialogflowpb.Intent, error) + CreateIntent(context.Context, *dialogflowpb.CreateIntentRequest, ...gax.CallOption) (*dialogflowpb.Intent, error) + UpdateIntent(context.Context, *dialogflowpb.UpdateIntentRequest, ...gax.CallOption) (*dialogflowpb.Intent, error) + DeleteIntent(context.Context, *dialogflowpb.DeleteIntentRequest, ...gax.CallOption) error + BatchUpdateIntents(context.Context, *dialogflowpb.BatchUpdateIntentsRequest, ...gax.CallOption) (*BatchUpdateIntentsOperation, error) + BatchUpdateIntentsOperation(name string) *BatchUpdateIntentsOperation + BatchDeleteIntents(context.Context, *dialogflowpb.BatchDeleteIntentsRequest, ...gax.CallOption) (*BatchDeleteIntentsOperation, error) + BatchDeleteIntentsOperation(name string) *BatchDeleteIntentsOperation +} + // IntentsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Intents. type IntentsClient struct { + // The internal transport-dependent client. + internalClient internalIntentsClient + + // The call options for this service. + CallOptions *IntentsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *IntentsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *IntentsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *IntentsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListIntents returns the list of all intents in the specified agent. +func (c *IntentsClient) ListIntents(ctx context.Context, req *dialogflowpb.ListIntentsRequest, opts ...gax.CallOption) *IntentIterator { + return c.internalClient.ListIntents(ctx, req, opts...) +} + +// GetIntent retrieves the specified intent. +func (c *IntentsClient) GetIntent(ctx context.Context, req *dialogflowpb.GetIntentRequest, opts ...gax.CallOption) (*dialogflowpb.Intent, error) { + return c.internalClient.GetIntent(ctx, req, opts...) +} + +// CreateIntent creates an intent in the specified agent. +func (c *IntentsClient) CreateIntent(ctx context.Context, req *dialogflowpb.CreateIntentRequest, opts ...gax.CallOption) (*dialogflowpb.Intent, error) { + return c.internalClient.CreateIntent(ctx, req, opts...) +} + +// UpdateIntent updates the specified intent. +func (c *IntentsClient) UpdateIntent(ctx context.Context, req *dialogflowpb.UpdateIntentRequest, opts ...gax.CallOption) (*dialogflowpb.Intent, error) { + return c.internalClient.UpdateIntent(ctx, req, opts...) +} + +// DeleteIntent deletes the specified intent and its direct or indirect followup intents. +func (c *IntentsClient) DeleteIntent(ctx context.Context, req *dialogflowpb.DeleteIntentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteIntent(ctx, req, opts...) +} + +// BatchUpdateIntents updates/Creates multiple intents in the specified agent. +// +// Operation +func (c *IntentsClient) BatchUpdateIntents(ctx context.Context, req *dialogflowpb.BatchUpdateIntentsRequest, opts ...gax.CallOption) (*BatchUpdateIntentsOperation, error) { + return c.internalClient.BatchUpdateIntents(ctx, req, opts...) +} + +// BatchUpdateIntentsOperation returns a new BatchUpdateIntentsOperation from a given name. +// The name must be that of a previously created BatchUpdateIntentsOperation, possibly from a different process. +func (c *IntentsClient) BatchUpdateIntentsOperation(name string) *BatchUpdateIntentsOperation { + return c.internalClient.BatchUpdateIntentsOperation(name) +} + +// BatchDeleteIntents deletes intents in the specified agent. +// +// Operation +func (c *IntentsClient) BatchDeleteIntents(ctx context.Context, req *dialogflowpb.BatchDeleteIntentsRequest, opts ...gax.CallOption) (*BatchDeleteIntentsOperation, error) { + return c.internalClient.BatchDeleteIntents(ctx, req, opts...) +} + +// BatchDeleteIntentsOperation returns a new BatchDeleteIntentsOperation from a given name. +// The name must be that of a previously created BatchDeleteIntentsOperation, possibly from a different process. +func (c *IntentsClient) BatchDeleteIntentsOperation(name string) *BatchDeleteIntentsOperation { + return c.internalClient.BatchDeleteIntentsOperation(name) +} + +// intentsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type intentsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing IntentsClient + CallOptions **IntentsCallOptions + // The gRPC API client. intentsClient dialogflowpb.IntentsClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *IntentsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewIntentsClient creates a new intents client. +// NewIntentsClient creates a new intents client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Intents. func NewIntentsClient(ctx context.Context, opts ...option.ClientOption) (*IntentsClient, error) { - clientOpts := defaultIntentsClientOptions() - + clientOpts := defaultIntentsGRPCClientOptions() if newIntentsClientHook != nil { hookOpts, err := newIntentsClientHook(ctx, clientHookParams{}) if err != nil { @@ -194,16 +300,19 @@ func NewIntentsClient(ctx context.Context, opts ...option.ClientOption) (*Intent if err != nil { return nil, err } - c := &IntentsClient{ + client := IntentsClient{CallOptions: defaultIntentsCallOptions()} + + c := &intentsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultIntentsCallOptions(), - - intentsClient: dialogflowpb.NewIntentsClient(connPool), + intentsClient: dialogflowpb.NewIntentsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -213,36 +322,36 @@ func NewIntentsClient(ctx context.Context, opts ...option.ClientOption) (*Intent // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *IntentsClient) Connection() *grpc.ClientConn { +func (c *intentsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *IntentsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *IntentsClient) setGoogleClientInfo(keyval ...string) { +func (c *intentsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListIntents returns the list of all intents in the specified agent. -func (c *IntentsClient) ListIntents(ctx context.Context, req *dialogflowpb.ListIntentsRequest, opts ...gax.CallOption) *IntentIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *intentsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *intentsGRPCClient) ListIntents(ctx context.Context, req *dialogflowpb.ListIntentsRequest, opts ...gax.CallOption) *IntentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListIntents[0:len(c.CallOptions.ListIntents):len(c.CallOptions.ListIntents)], opts...) + opts = append((*c.CallOptions).ListIntents[0:len((*c.CallOptions).ListIntents):len((*c.CallOptions).ListIntents)], opts...) it := &IntentIterator{} req = proto.Clone(req).(*dialogflowpb.ListIntentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Intent, string, error) { @@ -279,8 +388,7 @@ func (c *IntentsClient) ListIntents(ctx context.Context, req *dialogflowpb.ListI return it } -// GetIntent retrieves the specified intent. -func (c *IntentsClient) GetIntent(ctx context.Context, req *dialogflowpb.GetIntentRequest, opts ...gax.CallOption) (*dialogflowpb.Intent, error) { +func (c *intentsGRPCClient) GetIntent(ctx context.Context, req *dialogflowpb.GetIntentRequest, opts ...gax.CallOption) (*dialogflowpb.Intent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -288,7 +396,7 @@ func (c *IntentsClient) GetIntent(ctx context.Context, req *dialogflowpb.GetInte } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIntent[0:len(c.CallOptions.GetIntent):len(c.CallOptions.GetIntent)], opts...) + opts = append((*c.CallOptions).GetIntent[0:len((*c.CallOptions).GetIntent):len((*c.CallOptions).GetIntent)], opts...) var resp *dialogflowpb.Intent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -301,8 +409,7 @@ func (c *IntentsClient) GetIntent(ctx context.Context, req *dialogflowpb.GetInte return resp, nil } -// CreateIntent creates an intent in the specified agent. -func (c *IntentsClient) CreateIntent(ctx context.Context, req *dialogflowpb.CreateIntentRequest, opts ...gax.CallOption) (*dialogflowpb.Intent, error) { +func (c *intentsGRPCClient) CreateIntent(ctx context.Context, req *dialogflowpb.CreateIntentRequest, opts ...gax.CallOption) (*dialogflowpb.Intent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -310,7 +417,7 @@ func (c *IntentsClient) CreateIntent(ctx context.Context, req *dialogflowpb.Crea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateIntent[0:len(c.CallOptions.CreateIntent):len(c.CallOptions.CreateIntent)], opts...) + opts = append((*c.CallOptions).CreateIntent[0:len((*c.CallOptions).CreateIntent):len((*c.CallOptions).CreateIntent)], opts...) var resp *dialogflowpb.Intent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -323,8 +430,7 @@ func (c *IntentsClient) CreateIntent(ctx context.Context, req *dialogflowpb.Crea return resp, nil } -// UpdateIntent updates the specified intent. -func (c *IntentsClient) UpdateIntent(ctx context.Context, req *dialogflowpb.UpdateIntentRequest, opts ...gax.CallOption) (*dialogflowpb.Intent, error) { +func (c *intentsGRPCClient) UpdateIntent(ctx context.Context, req *dialogflowpb.UpdateIntentRequest, opts ...gax.CallOption) (*dialogflowpb.Intent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -332,7 +438,7 @@ func (c *IntentsClient) UpdateIntent(ctx context.Context, req *dialogflowpb.Upda } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "intent.name", url.QueryEscape(req.GetIntent().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateIntent[0:len(c.CallOptions.UpdateIntent):len(c.CallOptions.UpdateIntent)], opts...) + opts = append((*c.CallOptions).UpdateIntent[0:len((*c.CallOptions).UpdateIntent):len((*c.CallOptions).UpdateIntent)], opts...) var resp *dialogflowpb.Intent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -345,8 +451,7 @@ func (c *IntentsClient) UpdateIntent(ctx context.Context, req *dialogflowpb.Upda return resp, nil } -// DeleteIntent deletes the specified intent and its direct or indirect followup intents. -func (c *IntentsClient) DeleteIntent(ctx context.Context, req *dialogflowpb.DeleteIntentRequest, opts ...gax.CallOption) error { +func (c *intentsGRPCClient) DeleteIntent(ctx context.Context, req *dialogflowpb.DeleteIntentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -354,7 +459,7 @@ func (c *IntentsClient) DeleteIntent(ctx context.Context, req *dialogflowpb.Dele } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteIntent[0:len(c.CallOptions.DeleteIntent):len(c.CallOptions.DeleteIntent)], opts...) + opts = append((*c.CallOptions).DeleteIntent[0:len((*c.CallOptions).DeleteIntent):len((*c.CallOptions).DeleteIntent)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.intentsClient.DeleteIntent(ctx, req, settings.GRPC...) @@ -363,10 +468,7 @@ func (c *IntentsClient) DeleteIntent(ctx context.Context, req *dialogflowpb.Dele return err } -// BatchUpdateIntents updates/Creates multiple intents in the specified agent. -// -// Operation -func (c *IntentsClient) BatchUpdateIntents(ctx context.Context, req *dialogflowpb.BatchUpdateIntentsRequest, opts ...gax.CallOption) (*BatchUpdateIntentsOperation, error) { +func (c *intentsGRPCClient) BatchUpdateIntents(ctx context.Context, req *dialogflowpb.BatchUpdateIntentsRequest, opts ...gax.CallOption) (*BatchUpdateIntentsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -374,7 +476,7 @@ func (c *IntentsClient) BatchUpdateIntents(ctx context.Context, req *dialogflowp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchUpdateIntents[0:len(c.CallOptions.BatchUpdateIntents):len(c.CallOptions.BatchUpdateIntents)], opts...) + opts = append((*c.CallOptions).BatchUpdateIntents[0:len((*c.CallOptions).BatchUpdateIntents):len((*c.CallOptions).BatchUpdateIntents)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -385,14 +487,11 @@ func (c *IntentsClient) BatchUpdateIntents(ctx context.Context, req *dialogflowp return nil, err } return &BatchUpdateIntentsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// BatchDeleteIntents deletes intents in the specified agent. -// -// Operation -func (c *IntentsClient) BatchDeleteIntents(ctx context.Context, req *dialogflowpb.BatchDeleteIntentsRequest, opts ...gax.CallOption) (*BatchDeleteIntentsOperation, error) { +func (c *intentsGRPCClient) BatchDeleteIntents(ctx context.Context, req *dialogflowpb.BatchDeleteIntentsRequest, opts ...gax.CallOption) (*BatchDeleteIntentsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -400,7 +499,7 @@ func (c *IntentsClient) BatchDeleteIntents(ctx context.Context, req *dialogflowp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchDeleteIntents[0:len(c.CallOptions.BatchDeleteIntents):len(c.CallOptions.BatchDeleteIntents)], opts...) + opts = append((*c.CallOptions).BatchDeleteIntents[0:len((*c.CallOptions).BatchDeleteIntents):len((*c.CallOptions).BatchDeleteIntents)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -411,7 +510,7 @@ func (c *IntentsClient) BatchDeleteIntents(ctx context.Context, req *dialogflowp return nil, err } return &BatchDeleteIntentsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -422,9 +521,9 @@ type BatchDeleteIntentsOperation struct { // BatchDeleteIntentsOperation returns a new BatchDeleteIntentsOperation from a given name. // The name must be that of a previously created BatchDeleteIntentsOperation, possibly from a different process. -func (c *IntentsClient) BatchDeleteIntentsOperation(name string) *BatchDeleteIntentsOperation { +func (c *intentsGRPCClient) BatchDeleteIntentsOperation(name string) *BatchDeleteIntentsOperation { return &BatchDeleteIntentsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -480,9 +579,9 @@ type BatchUpdateIntentsOperation struct { // BatchUpdateIntentsOperation returns a new BatchUpdateIntentsOperation from a given name. // The name must be that of a previously created BatchUpdateIntentsOperation, possibly from a different process. -func (c *IntentsClient) BatchUpdateIntentsOperation(name string) *BatchUpdateIntentsOperation { +func (c *intentsGRPCClient) BatchUpdateIntentsOperation(name string) *BatchUpdateIntentsOperation { return &BatchUpdateIntentsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dialogflow/apiv2/intents_client_example_test.go b/dialogflow/apiv2/intents_client_example_test.go index 508e3d4ddd24..838d771e8f2f 100644 --- a/dialogflow/apiv2/intents_client_example_test.go +++ b/dialogflow/apiv2/intents_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewIntentsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleIntentsClient_ListIntents() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListIntentsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleIntentsClient_ListIntents() { } func ExampleIntentsClient_GetIntent() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetIntentRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleIntentsClient_GetIntent() { } func ExampleIntentsClient_CreateIntent() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateIntentRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleIntentsClient_CreateIntent() { } func ExampleIntentsClient_UpdateIntent() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateIntentRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleIntentsClient_DeleteIntent() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteIntentRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleIntentsClient_DeleteIntent() { } func ExampleIntentsClient_BatchUpdateIntents() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.BatchUpdateIntentsRequest{ // TODO: Fill request struct fields. @@ -163,13 +160,12 @@ func ExampleIntentsClient_BatchUpdateIntents() { } func ExampleIntentsClient_BatchDeleteIntents() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.BatchDeleteIntentsRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/apiv2/knowledge_bases_client.go b/dialogflow/apiv2/knowledge_bases_client.go index 7f5b5ef0e959..52505358a459 100644 --- a/dialogflow/apiv2/knowledge_bases_client.go +++ b/dialogflow/apiv2/knowledge_bases_client.go @@ -46,7 +46,7 @@ type KnowledgeBasesCallOptions struct { UpdateKnowledgeBase []gax.CallOption } -func defaultKnowledgeBasesClientOptions() []option.ClientOption { +func defaultKnowledgeBasesGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,103 @@ func defaultKnowledgeBasesCallOptions() *KnowledgeBasesCallOptions { } } +// internalKnowledgeBasesClient is an interface that defines the methods availaible from Dialogflow API. +type internalKnowledgeBasesClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListKnowledgeBases(context.Context, *dialogflowpb.ListKnowledgeBasesRequest, ...gax.CallOption) *KnowledgeBaseIterator + GetKnowledgeBase(context.Context, *dialogflowpb.GetKnowledgeBaseRequest, ...gax.CallOption) (*dialogflowpb.KnowledgeBase, error) + CreateKnowledgeBase(context.Context, *dialogflowpb.CreateKnowledgeBaseRequest, ...gax.CallOption) (*dialogflowpb.KnowledgeBase, error) + DeleteKnowledgeBase(context.Context, *dialogflowpb.DeleteKnowledgeBaseRequest, ...gax.CallOption) error + UpdateKnowledgeBase(context.Context, *dialogflowpb.UpdateKnowledgeBaseRequest, ...gax.CallOption) (*dialogflowpb.KnowledgeBase, error) +} + // KnowledgeBasesClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing KnowledgeBases. type KnowledgeBasesClient struct { + // The internal transport-dependent client. + internalClient internalKnowledgeBasesClient + + // The call options for this service. + CallOptions *KnowledgeBasesCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *KnowledgeBasesClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *KnowledgeBasesClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *KnowledgeBasesClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListKnowledgeBases returns the list of all knowledge bases of the specified agent. +func (c *KnowledgeBasesClient) ListKnowledgeBases(ctx context.Context, req *dialogflowpb.ListKnowledgeBasesRequest, opts ...gax.CallOption) *KnowledgeBaseIterator { + return c.internalClient.ListKnowledgeBases(ctx, req, opts...) +} + +// GetKnowledgeBase retrieves the specified knowledge base. +func (c *KnowledgeBasesClient) GetKnowledgeBase(ctx context.Context, req *dialogflowpb.GetKnowledgeBaseRequest, opts ...gax.CallOption) (*dialogflowpb.KnowledgeBase, error) { + return c.internalClient.GetKnowledgeBase(ctx, req, opts...) +} + +// CreateKnowledgeBase creates a knowledge base. +func (c *KnowledgeBasesClient) CreateKnowledgeBase(ctx context.Context, req *dialogflowpb.CreateKnowledgeBaseRequest, opts ...gax.CallOption) (*dialogflowpb.KnowledgeBase, error) { + return c.internalClient.CreateKnowledgeBase(ctx, req, opts...) +} + +// DeleteKnowledgeBase deletes the specified knowledge base. +func (c *KnowledgeBasesClient) DeleteKnowledgeBase(ctx context.Context, req *dialogflowpb.DeleteKnowledgeBaseRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteKnowledgeBase(ctx, req, opts...) +} + +// UpdateKnowledgeBase updates the specified knowledge base. +func (c *KnowledgeBasesClient) UpdateKnowledgeBase(ctx context.Context, req *dialogflowpb.UpdateKnowledgeBaseRequest, opts ...gax.CallOption) (*dialogflowpb.KnowledgeBase, error) { + return c.internalClient.UpdateKnowledgeBase(ctx, req, opts...) +} + +// knowledgeBasesGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type knowledgeBasesGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing KnowledgeBasesClient + CallOptions **KnowledgeBasesCallOptions + // The gRPC API client. knowledgeBasesClient dialogflowpb.KnowledgeBasesClient - // The call options for this service. - CallOptions *KnowledgeBasesCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewKnowledgeBasesClient creates a new knowledge bases client. +// NewKnowledgeBasesClient creates a new knowledge bases client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing KnowledgeBases. func NewKnowledgeBasesClient(ctx context.Context, opts ...option.ClientOption) (*KnowledgeBasesClient, error) { - clientOpts := defaultKnowledgeBasesClientOptions() - + clientOpts := defaultKnowledgeBasesGRPCClientOptions() if newKnowledgeBasesClientHook != nil { hookOpts, err := newKnowledgeBasesClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,45 +232,47 @@ func NewKnowledgeBasesClient(ctx context.Context, opts ...option.ClientOption) ( if err != nil { return nil, err } - c := &KnowledgeBasesClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultKnowledgeBasesCallOptions(), + client := KnowledgeBasesClient{CallOptions: defaultKnowledgeBasesCallOptions()} + c := &knowledgeBasesGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, knowledgeBasesClient: dialogflowpb.NewKnowledgeBasesClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *KnowledgeBasesClient) Connection() *grpc.ClientConn { +func (c *knowledgeBasesGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *KnowledgeBasesClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *KnowledgeBasesClient) setGoogleClientInfo(keyval ...string) { +func (c *knowledgeBasesGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListKnowledgeBases returns the list of all knowledge bases of the specified agent. -func (c *KnowledgeBasesClient) ListKnowledgeBases(ctx context.Context, req *dialogflowpb.ListKnowledgeBasesRequest, opts ...gax.CallOption) *KnowledgeBaseIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *knowledgeBasesGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *knowledgeBasesGRPCClient) ListKnowledgeBases(ctx context.Context, req *dialogflowpb.ListKnowledgeBasesRequest, opts ...gax.CallOption) *KnowledgeBaseIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListKnowledgeBases[0:len(c.CallOptions.ListKnowledgeBases):len(c.CallOptions.ListKnowledgeBases)], opts...) + opts = append((*c.CallOptions).ListKnowledgeBases[0:len((*c.CallOptions).ListKnowledgeBases):len((*c.CallOptions).ListKnowledgeBases)], opts...) it := &KnowledgeBaseIterator{} req = proto.Clone(req).(*dialogflowpb.ListKnowledgeBasesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.KnowledgeBase, string, error) { @@ -236,8 +309,7 @@ func (c *KnowledgeBasesClient) ListKnowledgeBases(ctx context.Context, req *dial return it } -// GetKnowledgeBase retrieves the specified knowledge base. -func (c *KnowledgeBasesClient) GetKnowledgeBase(ctx context.Context, req *dialogflowpb.GetKnowledgeBaseRequest, opts ...gax.CallOption) (*dialogflowpb.KnowledgeBase, error) { +func (c *knowledgeBasesGRPCClient) GetKnowledgeBase(ctx context.Context, req *dialogflowpb.GetKnowledgeBaseRequest, opts ...gax.CallOption) (*dialogflowpb.KnowledgeBase, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -245,7 +317,7 @@ func (c *KnowledgeBasesClient) GetKnowledgeBase(ctx context.Context, req *dialog } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetKnowledgeBase[0:len(c.CallOptions.GetKnowledgeBase):len(c.CallOptions.GetKnowledgeBase)], opts...) + opts = append((*c.CallOptions).GetKnowledgeBase[0:len((*c.CallOptions).GetKnowledgeBase):len((*c.CallOptions).GetKnowledgeBase)], opts...) var resp *dialogflowpb.KnowledgeBase err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -258,8 +330,7 @@ func (c *KnowledgeBasesClient) GetKnowledgeBase(ctx context.Context, req *dialog return resp, nil } -// CreateKnowledgeBase creates a knowledge base. -func (c *KnowledgeBasesClient) CreateKnowledgeBase(ctx context.Context, req *dialogflowpb.CreateKnowledgeBaseRequest, opts ...gax.CallOption) (*dialogflowpb.KnowledgeBase, error) { +func (c *knowledgeBasesGRPCClient) CreateKnowledgeBase(ctx context.Context, req *dialogflowpb.CreateKnowledgeBaseRequest, opts ...gax.CallOption) (*dialogflowpb.KnowledgeBase, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -267,7 +338,7 @@ func (c *KnowledgeBasesClient) CreateKnowledgeBase(ctx context.Context, req *dia } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateKnowledgeBase[0:len(c.CallOptions.CreateKnowledgeBase):len(c.CallOptions.CreateKnowledgeBase)], opts...) + opts = append((*c.CallOptions).CreateKnowledgeBase[0:len((*c.CallOptions).CreateKnowledgeBase):len((*c.CallOptions).CreateKnowledgeBase)], opts...) var resp *dialogflowpb.KnowledgeBase err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -280,8 +351,7 @@ func (c *KnowledgeBasesClient) CreateKnowledgeBase(ctx context.Context, req *dia return resp, nil } -// DeleteKnowledgeBase deletes the specified knowledge base. -func (c *KnowledgeBasesClient) DeleteKnowledgeBase(ctx context.Context, req *dialogflowpb.DeleteKnowledgeBaseRequest, opts ...gax.CallOption) error { +func (c *knowledgeBasesGRPCClient) DeleteKnowledgeBase(ctx context.Context, req *dialogflowpb.DeleteKnowledgeBaseRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -289,7 +359,7 @@ func (c *KnowledgeBasesClient) DeleteKnowledgeBase(ctx context.Context, req *dia } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteKnowledgeBase[0:len(c.CallOptions.DeleteKnowledgeBase):len(c.CallOptions.DeleteKnowledgeBase)], opts...) + opts = append((*c.CallOptions).DeleteKnowledgeBase[0:len((*c.CallOptions).DeleteKnowledgeBase):len((*c.CallOptions).DeleteKnowledgeBase)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.knowledgeBasesClient.DeleteKnowledgeBase(ctx, req, settings.GRPC...) @@ -298,8 +368,7 @@ func (c *KnowledgeBasesClient) DeleteKnowledgeBase(ctx context.Context, req *dia return err } -// UpdateKnowledgeBase updates the specified knowledge base. -func (c *KnowledgeBasesClient) UpdateKnowledgeBase(ctx context.Context, req *dialogflowpb.UpdateKnowledgeBaseRequest, opts ...gax.CallOption) (*dialogflowpb.KnowledgeBase, error) { +func (c *knowledgeBasesGRPCClient) UpdateKnowledgeBase(ctx context.Context, req *dialogflowpb.UpdateKnowledgeBaseRequest, opts ...gax.CallOption) (*dialogflowpb.KnowledgeBase, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -307,7 +376,7 @@ func (c *KnowledgeBasesClient) UpdateKnowledgeBase(ctx context.Context, req *dia } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "knowledge_base.name", url.QueryEscape(req.GetKnowledgeBase().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateKnowledgeBase[0:len(c.CallOptions.UpdateKnowledgeBase):len(c.CallOptions.UpdateKnowledgeBase)], opts...) + opts = append((*c.CallOptions).UpdateKnowledgeBase[0:len((*c.CallOptions).UpdateKnowledgeBase):len((*c.CallOptions).UpdateKnowledgeBase)], opts...) var resp *dialogflowpb.KnowledgeBase err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/dialogflow/apiv2/knowledge_bases_client_example_test.go b/dialogflow/apiv2/knowledge_bases_client_example_test.go index 2f8fabe8b415..b317e14a7fc5 100644 --- a/dialogflow/apiv2/knowledge_bases_client_example_test.go +++ b/dialogflow/apiv2/knowledge_bases_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewKnowledgeBasesClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleKnowledgeBasesClient_ListKnowledgeBases() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewKnowledgeBasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListKnowledgeBasesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleKnowledgeBasesClient_ListKnowledgeBases() { } func ExampleKnowledgeBasesClient_GetKnowledgeBase() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewKnowledgeBasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetKnowledgeBaseRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleKnowledgeBasesClient_GetKnowledgeBase() { } func ExampleKnowledgeBasesClient_CreateKnowledgeBase() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewKnowledgeBasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateKnowledgeBaseRequest{ // TODO: Fill request struct fields. @@ -107,6 +105,7 @@ func ExampleKnowledgeBasesClient_DeleteKnowledgeBase() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteKnowledgeBaseRequest{ // TODO: Fill request struct fields. @@ -118,13 +117,12 @@ func ExampleKnowledgeBasesClient_DeleteKnowledgeBase() { } func ExampleKnowledgeBasesClient_UpdateKnowledgeBase() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewKnowledgeBasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateKnowledgeBaseRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/apiv2/participants_client.go b/dialogflow/apiv2/participants_client.go index 966527ab8ac2..39e4349f7bce 100644 --- a/dialogflow/apiv2/participants_client.go +++ b/dialogflow/apiv2/participants_client.go @@ -48,7 +48,7 @@ type ParticipantsCallOptions struct { SuggestFaqAnswers []gax.CallOption } -func defaultParticipantsClientOptions() []option.ClientOption { +func defaultParticipantsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -142,32 +142,122 @@ func defaultParticipantsCallOptions() *ParticipantsCallOptions { } } +// internalParticipantsClient is an interface that defines the methods availaible from Dialogflow API. +type internalParticipantsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateParticipant(context.Context, *dialogflowpb.CreateParticipantRequest, ...gax.CallOption) (*dialogflowpb.Participant, error) + GetParticipant(context.Context, *dialogflowpb.GetParticipantRequest, ...gax.CallOption) (*dialogflowpb.Participant, error) + ListParticipants(context.Context, *dialogflowpb.ListParticipantsRequest, ...gax.CallOption) *ParticipantIterator + UpdateParticipant(context.Context, *dialogflowpb.UpdateParticipantRequest, ...gax.CallOption) (*dialogflowpb.Participant, error) + AnalyzeContent(context.Context, *dialogflowpb.AnalyzeContentRequest, ...gax.CallOption) (*dialogflowpb.AnalyzeContentResponse, error) + SuggestArticles(context.Context, *dialogflowpb.SuggestArticlesRequest, ...gax.CallOption) (*dialogflowpb.SuggestArticlesResponse, error) + SuggestFaqAnswers(context.Context, *dialogflowpb.SuggestFaqAnswersRequest, ...gax.CallOption) (*dialogflowpb.SuggestFaqAnswersResponse, error) +} + // ParticipantsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Participants. type ParticipantsClient struct { + // The internal transport-dependent client. + internalClient internalParticipantsClient + + // The call options for this service. + CallOptions *ParticipantsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ParticipantsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ParticipantsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ParticipantsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateParticipant creates a new participant in a conversation. +func (c *ParticipantsClient) CreateParticipant(ctx context.Context, req *dialogflowpb.CreateParticipantRequest, opts ...gax.CallOption) (*dialogflowpb.Participant, error) { + return c.internalClient.CreateParticipant(ctx, req, opts...) +} + +// GetParticipant retrieves a conversation participant. +func (c *ParticipantsClient) GetParticipant(ctx context.Context, req *dialogflowpb.GetParticipantRequest, opts ...gax.CallOption) (*dialogflowpb.Participant, error) { + return c.internalClient.GetParticipant(ctx, req, opts...) +} + +// ListParticipants returns the list of all participants in the specified conversation. +func (c *ParticipantsClient) ListParticipants(ctx context.Context, req *dialogflowpb.ListParticipantsRequest, opts ...gax.CallOption) *ParticipantIterator { + return c.internalClient.ListParticipants(ctx, req, opts...) +} + +// UpdateParticipant updates the specified participant. +func (c *ParticipantsClient) UpdateParticipant(ctx context.Context, req *dialogflowpb.UpdateParticipantRequest, opts ...gax.CallOption) (*dialogflowpb.Participant, error) { + return c.internalClient.UpdateParticipant(ctx, req, opts...) +} + +// AnalyzeContent adds a text (chat, for example), or audio (phone recording, for example) +// message from a participant into the conversation. +// +// Note: Always use agent versions for production traffic +// sent to virtual agents. See Versions and +// environments (at https://cloud.google.com/dialogflow/es/docs/agents-versions). +func (c *ParticipantsClient) AnalyzeContent(ctx context.Context, req *dialogflowpb.AnalyzeContentRequest, opts ...gax.CallOption) (*dialogflowpb.AnalyzeContentResponse, error) { + return c.internalClient.AnalyzeContent(ctx, req, opts...) +} + +// SuggestArticles gets suggested articles for a participant based on specific historical +// messages. +func (c *ParticipantsClient) SuggestArticles(ctx context.Context, req *dialogflowpb.SuggestArticlesRequest, opts ...gax.CallOption) (*dialogflowpb.SuggestArticlesResponse, error) { + return c.internalClient.SuggestArticles(ctx, req, opts...) +} + +// SuggestFaqAnswers gets suggested faq answers for a participant based on specific historical +// messages. +func (c *ParticipantsClient) SuggestFaqAnswers(ctx context.Context, req *dialogflowpb.SuggestFaqAnswersRequest, opts ...gax.CallOption) (*dialogflowpb.SuggestFaqAnswersResponse, error) { + return c.internalClient.SuggestFaqAnswers(ctx, req, opts...) +} + +// participantsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type participantsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ParticipantsClient + CallOptions **ParticipantsCallOptions + // The gRPC API client. participantsClient dialogflowpb.ParticipantsClient - // The call options for this service. - CallOptions *ParticipantsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewParticipantsClient creates a new participants client. +// NewParticipantsClient creates a new participants client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Participants. func NewParticipantsClient(ctx context.Context, opts ...option.ClientOption) (*ParticipantsClient, error) { - clientOpts := defaultParticipantsClientOptions() - + clientOpts := defaultParticipantsGRPCClientOptions() if newParticipantsClientHook != nil { hookOpts, err := newParticipantsClientHook(ctx, clientHookParams{}) if err != nil { @@ -185,42 +275,44 @@ func NewParticipantsClient(ctx context.Context, opts ...option.ClientOption) (*P if err != nil { return nil, err } - c := &ParticipantsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultParticipantsCallOptions(), + client := ParticipantsClient{CallOptions: defaultParticipantsCallOptions()} + c := &participantsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, participantsClient: dialogflowpb.NewParticipantsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ParticipantsClient) Connection() *grpc.ClientConn { +func (c *participantsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ParticipantsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ParticipantsClient) setGoogleClientInfo(keyval ...string) { +func (c *participantsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateParticipant creates a new participant in a conversation. -func (c *ParticipantsClient) CreateParticipant(ctx context.Context, req *dialogflowpb.CreateParticipantRequest, opts ...gax.CallOption) (*dialogflowpb.Participant, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *participantsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *participantsGRPCClient) CreateParticipant(ctx context.Context, req *dialogflowpb.CreateParticipantRequest, opts ...gax.CallOption) (*dialogflowpb.Participant, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -228,7 +320,7 @@ func (c *ParticipantsClient) CreateParticipant(ctx context.Context, req *dialogf } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateParticipant[0:len(c.CallOptions.CreateParticipant):len(c.CallOptions.CreateParticipant)], opts...) + opts = append((*c.CallOptions).CreateParticipant[0:len((*c.CallOptions).CreateParticipant):len((*c.CallOptions).CreateParticipant)], opts...) var resp *dialogflowpb.Participant err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -241,8 +333,7 @@ func (c *ParticipantsClient) CreateParticipant(ctx context.Context, req *dialogf return resp, nil } -// GetParticipant retrieves a conversation participant. -func (c *ParticipantsClient) GetParticipant(ctx context.Context, req *dialogflowpb.GetParticipantRequest, opts ...gax.CallOption) (*dialogflowpb.Participant, error) { +func (c *participantsGRPCClient) GetParticipant(ctx context.Context, req *dialogflowpb.GetParticipantRequest, opts ...gax.CallOption) (*dialogflowpb.Participant, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -250,7 +341,7 @@ func (c *ParticipantsClient) GetParticipant(ctx context.Context, req *dialogflow } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetParticipant[0:len(c.CallOptions.GetParticipant):len(c.CallOptions.GetParticipant)], opts...) + opts = append((*c.CallOptions).GetParticipant[0:len((*c.CallOptions).GetParticipant):len((*c.CallOptions).GetParticipant)], opts...) var resp *dialogflowpb.Participant err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -263,11 +354,10 @@ func (c *ParticipantsClient) GetParticipant(ctx context.Context, req *dialogflow return resp, nil } -// ListParticipants returns the list of all participants in the specified conversation. -func (c *ParticipantsClient) ListParticipants(ctx context.Context, req *dialogflowpb.ListParticipantsRequest, opts ...gax.CallOption) *ParticipantIterator { +func (c *participantsGRPCClient) ListParticipants(ctx context.Context, req *dialogflowpb.ListParticipantsRequest, opts ...gax.CallOption) *ParticipantIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListParticipants[0:len(c.CallOptions.ListParticipants):len(c.CallOptions.ListParticipants)], opts...) + opts = append((*c.CallOptions).ListParticipants[0:len((*c.CallOptions).ListParticipants):len((*c.CallOptions).ListParticipants)], opts...) it := &ParticipantIterator{} req = proto.Clone(req).(*dialogflowpb.ListParticipantsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Participant, string, error) { @@ -304,8 +394,7 @@ func (c *ParticipantsClient) ListParticipants(ctx context.Context, req *dialogfl return it } -// UpdateParticipant updates the specified participant. -func (c *ParticipantsClient) UpdateParticipant(ctx context.Context, req *dialogflowpb.UpdateParticipantRequest, opts ...gax.CallOption) (*dialogflowpb.Participant, error) { +func (c *participantsGRPCClient) UpdateParticipant(ctx context.Context, req *dialogflowpb.UpdateParticipantRequest, opts ...gax.CallOption) (*dialogflowpb.Participant, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -313,7 +402,7 @@ func (c *ParticipantsClient) UpdateParticipant(ctx context.Context, req *dialogf } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "participant.name", url.QueryEscape(req.GetParticipant().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateParticipant[0:len(c.CallOptions.UpdateParticipant):len(c.CallOptions.UpdateParticipant)], opts...) + opts = append((*c.CallOptions).UpdateParticipant[0:len((*c.CallOptions).UpdateParticipant):len((*c.CallOptions).UpdateParticipant)], opts...) var resp *dialogflowpb.Participant err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -326,13 +415,7 @@ func (c *ParticipantsClient) UpdateParticipant(ctx context.Context, req *dialogf return resp, nil } -// AnalyzeContent adds a text (chat, for example), or audio (phone recording, for example) -// message from a participant into the conversation. -// -// Note: Always use agent versions for production traffic -// sent to virtual agents. See Versions and -// environments (at https://cloud.google.com/dialogflow/es/docs/agents-versions). -func (c *ParticipantsClient) AnalyzeContent(ctx context.Context, req *dialogflowpb.AnalyzeContentRequest, opts ...gax.CallOption) (*dialogflowpb.AnalyzeContentResponse, error) { +func (c *participantsGRPCClient) AnalyzeContent(ctx context.Context, req *dialogflowpb.AnalyzeContentRequest, opts ...gax.CallOption) (*dialogflowpb.AnalyzeContentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 220000*time.Millisecond) defer cancel() @@ -340,7 +423,7 @@ func (c *ParticipantsClient) AnalyzeContent(ctx context.Context, req *dialogflow } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "participant", url.QueryEscape(req.GetParticipant()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AnalyzeContent[0:len(c.CallOptions.AnalyzeContent):len(c.CallOptions.AnalyzeContent)], opts...) + opts = append((*c.CallOptions).AnalyzeContent[0:len((*c.CallOptions).AnalyzeContent):len((*c.CallOptions).AnalyzeContent)], opts...) var resp *dialogflowpb.AnalyzeContentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -353,9 +436,7 @@ func (c *ParticipantsClient) AnalyzeContent(ctx context.Context, req *dialogflow return resp, nil } -// SuggestArticles gets suggested articles for a participant based on specific historical -// messages. -func (c *ParticipantsClient) SuggestArticles(ctx context.Context, req *dialogflowpb.SuggestArticlesRequest, opts ...gax.CallOption) (*dialogflowpb.SuggestArticlesResponse, error) { +func (c *participantsGRPCClient) SuggestArticles(ctx context.Context, req *dialogflowpb.SuggestArticlesRequest, opts ...gax.CallOption) (*dialogflowpb.SuggestArticlesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -363,7 +444,7 @@ func (c *ParticipantsClient) SuggestArticles(ctx context.Context, req *dialogflo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SuggestArticles[0:len(c.CallOptions.SuggestArticles):len(c.CallOptions.SuggestArticles)], opts...) + opts = append((*c.CallOptions).SuggestArticles[0:len((*c.CallOptions).SuggestArticles):len((*c.CallOptions).SuggestArticles)], opts...) var resp *dialogflowpb.SuggestArticlesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -376,9 +457,7 @@ func (c *ParticipantsClient) SuggestArticles(ctx context.Context, req *dialogflo return resp, nil } -// SuggestFaqAnswers gets suggested faq answers for a participant based on specific historical -// messages. -func (c *ParticipantsClient) SuggestFaqAnswers(ctx context.Context, req *dialogflowpb.SuggestFaqAnswersRequest, opts ...gax.CallOption) (*dialogflowpb.SuggestFaqAnswersResponse, error) { +func (c *participantsGRPCClient) SuggestFaqAnswers(ctx context.Context, req *dialogflowpb.SuggestFaqAnswersRequest, opts ...gax.CallOption) (*dialogflowpb.SuggestFaqAnswersResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -386,7 +465,7 @@ func (c *ParticipantsClient) SuggestFaqAnswers(ctx context.Context, req *dialogf } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SuggestFaqAnswers[0:len(c.CallOptions.SuggestFaqAnswers):len(c.CallOptions.SuggestFaqAnswers)], opts...) + opts = append((*c.CallOptions).SuggestFaqAnswers[0:len((*c.CallOptions).SuggestFaqAnswers):len((*c.CallOptions).SuggestFaqAnswers)], opts...) var resp *dialogflowpb.SuggestFaqAnswersResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/dialogflow/apiv2/participants_client_example_test.go b/dialogflow/apiv2/participants_client_example_test.go index 17723b206db3..34416f71ad94 100644 --- a/dialogflow/apiv2/participants_client_example_test.go +++ b/dialogflow/apiv2/participants_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewParticipantsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleParticipantsClient_CreateParticipant() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewParticipantsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateParticipantRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleParticipantsClient_CreateParticipant() { } func ExampleParticipantsClient_GetParticipant() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewParticipantsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetParticipantRequest{ // TODO: Fill request struct fields. @@ -75,14 +75,12 @@ func ExampleParticipantsClient_GetParticipant() { } func ExampleParticipantsClient_ListParticipants() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewParticipantsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListParticipantsRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleParticipantsClient_ListParticipants() { } func ExampleParticipantsClient_UpdateParticipant() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewParticipantsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateParticipantRequest{ // TODO: Fill request struct fields. @@ -122,13 +119,12 @@ func ExampleParticipantsClient_UpdateParticipant() { } func ExampleParticipantsClient_AnalyzeContent() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewParticipantsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.AnalyzeContentRequest{ // TODO: Fill request struct fields. @@ -142,13 +138,12 @@ func ExampleParticipantsClient_AnalyzeContent() { } func ExampleParticipantsClient_SuggestArticles() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewParticipantsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.SuggestArticlesRequest{ // TODO: Fill request struct fields. @@ -162,13 +157,12 @@ func ExampleParticipantsClient_SuggestArticles() { } func ExampleParticipantsClient_SuggestFaqAnswers() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewParticipantsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.SuggestFaqAnswersRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/apiv2/session_entity_types_client.go b/dialogflow/apiv2/session_entity_types_client.go index 17905c0140b3..96945eac8155 100644 --- a/dialogflow/apiv2/session_entity_types_client.go +++ b/dialogflow/apiv2/session_entity_types_client.go @@ -46,7 +46,7 @@ type SessionEntityTypesCallOptions struct { DeleteSessionEntityType []gax.CallOption } -func defaultSessionEntityTypesClientOptions() []option.ClientOption { +func defaultSessionEntityTypesGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,126 @@ func defaultSessionEntityTypesCallOptions() *SessionEntityTypesCallOptions { } } +// internalSessionEntityTypesClient is an interface that defines the methods availaible from Dialogflow API. +type internalSessionEntityTypesClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListSessionEntityTypes(context.Context, *dialogflowpb.ListSessionEntityTypesRequest, ...gax.CallOption) *SessionEntityTypeIterator + GetSessionEntityType(context.Context, *dialogflowpb.GetSessionEntityTypeRequest, ...gax.CallOption) (*dialogflowpb.SessionEntityType, error) + CreateSessionEntityType(context.Context, *dialogflowpb.CreateSessionEntityTypeRequest, ...gax.CallOption) (*dialogflowpb.SessionEntityType, error) + UpdateSessionEntityType(context.Context, *dialogflowpb.UpdateSessionEntityTypeRequest, ...gax.CallOption) (*dialogflowpb.SessionEntityType, error) + DeleteSessionEntityType(context.Context, *dialogflowpb.DeleteSessionEntityTypeRequest, ...gax.CallOption) error +} + // SessionEntityTypesClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing SessionEntityTypes. type SessionEntityTypesClient struct { + // The internal transport-dependent client. + internalClient internalSessionEntityTypesClient + + // The call options for this service. + CallOptions *SessionEntityTypesCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *SessionEntityTypesClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *SessionEntityTypesClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *SessionEntityTypesClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListSessionEntityTypes returns the list of all session entity types in the specified session. +// +// This method doesn’t work with Google Assistant integration. +// Contact Dialogflow support if you need to use session entities +// with Google Assistant integration. +func (c *SessionEntityTypesClient) ListSessionEntityTypes(ctx context.Context, req *dialogflowpb.ListSessionEntityTypesRequest, opts ...gax.CallOption) *SessionEntityTypeIterator { + return c.internalClient.ListSessionEntityTypes(ctx, req, opts...) +} + +// GetSessionEntityType retrieves the specified session entity type. +// +// This method doesn’t work with Google Assistant integration. +// Contact Dialogflow support if you need to use session entities +// with Google Assistant integration. +func (c *SessionEntityTypesClient) GetSessionEntityType(ctx context.Context, req *dialogflowpb.GetSessionEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.SessionEntityType, error) { + return c.internalClient.GetSessionEntityType(ctx, req, opts...) +} + +// CreateSessionEntityType creates a session entity type. +// +// If the specified session entity type already exists, overrides the session +// entity type. +// +// This method doesn’t work with Google Assistant integration. +// Contact Dialogflow support if you need to use session entities +// with Google Assistant integration. +func (c *SessionEntityTypesClient) CreateSessionEntityType(ctx context.Context, req *dialogflowpb.CreateSessionEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.SessionEntityType, error) { + return c.internalClient.CreateSessionEntityType(ctx, req, opts...) +} + +// UpdateSessionEntityType updates the specified session entity type. +// +// This method doesn’t work with Google Assistant integration. +// Contact Dialogflow support if you need to use session entities +// with Google Assistant integration. +func (c *SessionEntityTypesClient) UpdateSessionEntityType(ctx context.Context, req *dialogflowpb.UpdateSessionEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.SessionEntityType, error) { + return c.internalClient.UpdateSessionEntityType(ctx, req, opts...) +} + +// DeleteSessionEntityType deletes the specified session entity type. +// +// This method doesn’t work with Google Assistant integration. +// Contact Dialogflow support if you need to use session entities +// with Google Assistant integration. +func (c *SessionEntityTypesClient) DeleteSessionEntityType(ctx context.Context, req *dialogflowpb.DeleteSessionEntityTypeRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteSessionEntityType(ctx, req, opts...) +} + +// sessionEntityTypesGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type sessionEntityTypesGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing SessionEntityTypesClient + CallOptions **SessionEntityTypesCallOptions + // The gRPC API client. sessionEntityTypesClient dialogflowpb.SessionEntityTypesClient - // The call options for this service. - CallOptions *SessionEntityTypesCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewSessionEntityTypesClient creates a new session entity types client. +// NewSessionEntityTypesClient creates a new session entity types client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing SessionEntityTypes. func NewSessionEntityTypesClient(ctx context.Context, opts ...option.ClientOption) (*SessionEntityTypesClient, error) { - clientOpts := defaultSessionEntityTypesClientOptions() - + clientOpts := defaultSessionEntityTypesGRPCClientOptions() if newSessionEntityTypesClientHook != nil { hookOpts, err := newSessionEntityTypesClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,49 +255,47 @@ func NewSessionEntityTypesClient(ctx context.Context, opts ...option.ClientOptio if err != nil { return nil, err } - c := &SessionEntityTypesClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultSessionEntityTypesCallOptions(), + client := SessionEntityTypesClient{CallOptions: defaultSessionEntityTypesCallOptions()} + c := &sessionEntityTypesGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, sessionEntityTypesClient: dialogflowpb.NewSessionEntityTypesClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *SessionEntityTypesClient) Connection() *grpc.ClientConn { +func (c *sessionEntityTypesGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *SessionEntityTypesClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *SessionEntityTypesClient) setGoogleClientInfo(keyval ...string) { +func (c *sessionEntityTypesGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListSessionEntityTypes returns the list of all session entity types in the specified session. -// -// This method doesn’t work with Google Assistant integration. -// Contact Dialogflow support if you need to use session entities -// with Google Assistant integration. -func (c *SessionEntityTypesClient) ListSessionEntityTypes(ctx context.Context, req *dialogflowpb.ListSessionEntityTypesRequest, opts ...gax.CallOption) *SessionEntityTypeIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *sessionEntityTypesGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *sessionEntityTypesGRPCClient) ListSessionEntityTypes(ctx context.Context, req *dialogflowpb.ListSessionEntityTypesRequest, opts ...gax.CallOption) *SessionEntityTypeIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSessionEntityTypes[0:len(c.CallOptions.ListSessionEntityTypes):len(c.CallOptions.ListSessionEntityTypes)], opts...) + opts = append((*c.CallOptions).ListSessionEntityTypes[0:len((*c.CallOptions).ListSessionEntityTypes):len((*c.CallOptions).ListSessionEntityTypes)], opts...) it := &SessionEntityTypeIterator{} req = proto.Clone(req).(*dialogflowpb.ListSessionEntityTypesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.SessionEntityType, string, error) { @@ -240,12 +332,7 @@ func (c *SessionEntityTypesClient) ListSessionEntityTypes(ctx context.Context, r return it } -// GetSessionEntityType retrieves the specified session entity type. -// -// This method doesn’t work with Google Assistant integration. -// Contact Dialogflow support if you need to use session entities -// with Google Assistant integration. -func (c *SessionEntityTypesClient) GetSessionEntityType(ctx context.Context, req *dialogflowpb.GetSessionEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.SessionEntityType, error) { +func (c *sessionEntityTypesGRPCClient) GetSessionEntityType(ctx context.Context, req *dialogflowpb.GetSessionEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.SessionEntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -253,7 +340,7 @@ func (c *SessionEntityTypesClient) GetSessionEntityType(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSessionEntityType[0:len(c.CallOptions.GetSessionEntityType):len(c.CallOptions.GetSessionEntityType)], opts...) + opts = append((*c.CallOptions).GetSessionEntityType[0:len((*c.CallOptions).GetSessionEntityType):len((*c.CallOptions).GetSessionEntityType)], opts...) var resp *dialogflowpb.SessionEntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -266,15 +353,7 @@ func (c *SessionEntityTypesClient) GetSessionEntityType(ctx context.Context, req return resp, nil } -// CreateSessionEntityType creates a session entity type. -// -// If the specified session entity type already exists, overrides the session -// entity type. -// -// This method doesn’t work with Google Assistant integration. -// Contact Dialogflow support if you need to use session entities -// with Google Assistant integration. -func (c *SessionEntityTypesClient) CreateSessionEntityType(ctx context.Context, req *dialogflowpb.CreateSessionEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.SessionEntityType, error) { +func (c *sessionEntityTypesGRPCClient) CreateSessionEntityType(ctx context.Context, req *dialogflowpb.CreateSessionEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.SessionEntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -282,7 +361,7 @@ func (c *SessionEntityTypesClient) CreateSessionEntityType(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSessionEntityType[0:len(c.CallOptions.CreateSessionEntityType):len(c.CallOptions.CreateSessionEntityType)], opts...) + opts = append((*c.CallOptions).CreateSessionEntityType[0:len((*c.CallOptions).CreateSessionEntityType):len((*c.CallOptions).CreateSessionEntityType)], opts...) var resp *dialogflowpb.SessionEntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -295,12 +374,7 @@ func (c *SessionEntityTypesClient) CreateSessionEntityType(ctx context.Context, return resp, nil } -// UpdateSessionEntityType updates the specified session entity type. -// -// This method doesn’t work with Google Assistant integration. -// Contact Dialogflow support if you need to use session entities -// with Google Assistant integration. -func (c *SessionEntityTypesClient) UpdateSessionEntityType(ctx context.Context, req *dialogflowpb.UpdateSessionEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.SessionEntityType, error) { +func (c *sessionEntityTypesGRPCClient) UpdateSessionEntityType(ctx context.Context, req *dialogflowpb.UpdateSessionEntityTypeRequest, opts ...gax.CallOption) (*dialogflowpb.SessionEntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -308,7 +382,7 @@ func (c *SessionEntityTypesClient) UpdateSessionEntityType(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session_entity_type.name", url.QueryEscape(req.GetSessionEntityType().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSessionEntityType[0:len(c.CallOptions.UpdateSessionEntityType):len(c.CallOptions.UpdateSessionEntityType)], opts...) + opts = append((*c.CallOptions).UpdateSessionEntityType[0:len((*c.CallOptions).UpdateSessionEntityType):len((*c.CallOptions).UpdateSessionEntityType)], opts...) var resp *dialogflowpb.SessionEntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -321,12 +395,7 @@ func (c *SessionEntityTypesClient) UpdateSessionEntityType(ctx context.Context, return resp, nil } -// DeleteSessionEntityType deletes the specified session entity type. -// -// This method doesn’t work with Google Assistant integration. -// Contact Dialogflow support if you need to use session entities -// with Google Assistant integration. -func (c *SessionEntityTypesClient) DeleteSessionEntityType(ctx context.Context, req *dialogflowpb.DeleteSessionEntityTypeRequest, opts ...gax.CallOption) error { +func (c *sessionEntityTypesGRPCClient) DeleteSessionEntityType(ctx context.Context, req *dialogflowpb.DeleteSessionEntityTypeRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -334,7 +403,7 @@ func (c *SessionEntityTypesClient) DeleteSessionEntityType(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteSessionEntityType[0:len(c.CallOptions.DeleteSessionEntityType):len(c.CallOptions.DeleteSessionEntityType)], opts...) + opts = append((*c.CallOptions).DeleteSessionEntityType[0:len((*c.CallOptions).DeleteSessionEntityType):len((*c.CallOptions).DeleteSessionEntityType)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.sessionEntityTypesClient.DeleteSessionEntityType(ctx, req, settings.GRPC...) diff --git a/dialogflow/apiv2/session_entity_types_client_example_test.go b/dialogflow/apiv2/session_entity_types_client_example_test.go index 331163214b16..d9d9357fc6dc 100644 --- a/dialogflow/apiv2/session_entity_types_client_example_test.go +++ b/dialogflow/apiv2/session_entity_types_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewSessionEntityTypesClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleSessionEntityTypesClient_ListSessionEntityTypes() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListSessionEntityTypesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleSessionEntityTypesClient_ListSessionEntityTypes() { } func ExampleSessionEntityTypesClient_GetSessionEntityType() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetSessionEntityTypeRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleSessionEntityTypesClient_GetSessionEntityType() { } func ExampleSessionEntityTypesClient_CreateSessionEntityType() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateSessionEntityTypeRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleSessionEntityTypesClient_CreateSessionEntityType() { } func ExampleSessionEntityTypesClient_UpdateSessionEntityType() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateSessionEntityTypeRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleSessionEntityTypesClient_DeleteSessionEntityType() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteSessionEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/apiv2/sessions_client.go b/dialogflow/apiv2/sessions_client.go index 493fc5de6ee7..a47c465f1ef4 100644 --- a/dialogflow/apiv2/sessions_client.go +++ b/dialogflow/apiv2/sessions_client.go @@ -41,7 +41,7 @@ type SessionsCallOptions struct { StreamingDetectIntent []gax.CallOption } -func defaultSessionsClientOptions() []option.ClientOption { +func defaultSessionsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -70,35 +70,104 @@ func defaultSessionsCallOptions() *SessionsCallOptions { } } +// internalSessionsClient is an interface that defines the methods availaible from Dialogflow API. +type internalSessionsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + DetectIntent(context.Context, *dialogflowpb.DetectIntentRequest, ...gax.CallOption) (*dialogflowpb.DetectIntentResponse, error) + StreamingDetectIntent(context.Context, ...gax.CallOption) (dialogflowpb.Sessions_StreamingDetectIntentClient, error) +} + // SessionsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A service used for session interactions. +// +// For more information, see the API interactions +// guide (at https://cloud.google.com/dialogflow/docs/api-overview). type SessionsClient struct { + // The internal transport-dependent client. + internalClient internalSessionsClient + + // The call options for this service. + CallOptions *SessionsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *SessionsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *SessionsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *SessionsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// DetectIntent processes a natural language query and returns structured, actionable data +// as a result. This method is not idempotent, because it may cause contexts +// and session entity types to be updated, which in turn might affect +// results of future queries. +// +// Note: Always use agent versions for production traffic. +// See Versions and +// environments (at https://cloud.google.com/dialogflow/es/docs/agents-versions). +func (c *SessionsClient) DetectIntent(ctx context.Context, req *dialogflowpb.DetectIntentRequest, opts ...gax.CallOption) (*dialogflowpb.DetectIntentResponse, error) { + return c.internalClient.DetectIntent(ctx, req, opts...) +} + +// StreamingDetectIntent processes a natural language query in audio format in a streaming fashion +// and returns structured, actionable data as a result. This method is only +// available via the gRPC API (not REST). +// +// Note: Always use agent versions for production traffic. +// See Versions and +// environments (at https://cloud.google.com/dialogflow/es/docs/agents-versions). +func (c *SessionsClient) StreamingDetectIntent(ctx context.Context, opts ...gax.CallOption) (dialogflowpb.Sessions_StreamingDetectIntentClient, error) { + return c.internalClient.StreamingDetectIntent(ctx, opts...) +} + +// sessionsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type sessionsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing SessionsClient + CallOptions **SessionsCallOptions + // The gRPC API client. sessionsClient dialogflowpb.SessionsClient - // The call options for this service. - CallOptions *SessionsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewSessionsClient creates a new sessions client. +// NewSessionsClient creates a new sessions client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A service used for session interactions. // // For more information, see the API interactions // guide (at https://cloud.google.com/dialogflow/docs/api-overview). func NewSessionsClient(ctx context.Context, opts ...option.ClientOption) (*SessionsClient, error) { - clientOpts := defaultSessionsClientOptions() - + clientOpts := defaultSessionsGRPCClientOptions() if newSessionsClientHook != nil { hookOpts, err := newSessionsClientHook(ctx, clientHookParams{}) if err != nil { @@ -116,49 +185,44 @@ func NewSessionsClient(ctx context.Context, opts ...option.ClientOption) (*Sessi if err != nil { return nil, err } - c := &SessionsClient{ + client := SessionsClient{CallOptions: defaultSessionsCallOptions()} + + c := &sessionsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultSessionsCallOptions(), - - sessionsClient: dialogflowpb.NewSessionsClient(connPool), + sessionsClient: dialogflowpb.NewSessionsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *SessionsClient) Connection() *grpc.ClientConn { +func (c *sessionsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *SessionsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *SessionsClient) setGoogleClientInfo(keyval ...string) { +func (c *sessionsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// DetectIntent processes a natural language query and returns structured, actionable data -// as a result. This method is not idempotent, because it may cause contexts -// and session entity types to be updated, which in turn might affect -// results of future queries. -// -// Note: Always use agent versions for production traffic. -// See Versions and -// environments (at https://cloud.google.com/dialogflow/es/docs/agents-versions). -func (c *SessionsClient) DetectIntent(ctx context.Context, req *dialogflowpb.DetectIntentRequest, opts ...gax.CallOption) (*dialogflowpb.DetectIntentResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *sessionsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *sessionsGRPCClient) DetectIntent(ctx context.Context, req *dialogflowpb.DetectIntentRequest, opts ...gax.CallOption) (*dialogflowpb.DetectIntentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 220000*time.Millisecond) defer cancel() @@ -166,7 +230,7 @@ func (c *SessionsClient) DetectIntent(ctx context.Context, req *dialogflowpb.Det } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DetectIntent[0:len(c.CallOptions.DetectIntent):len(c.CallOptions.DetectIntent)], opts...) + opts = append((*c.CallOptions).DetectIntent[0:len((*c.CallOptions).DetectIntent):len((*c.CallOptions).DetectIntent)], opts...) var resp *dialogflowpb.DetectIntentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -179,17 +243,10 @@ func (c *SessionsClient) DetectIntent(ctx context.Context, req *dialogflowpb.Det return resp, nil } -// StreamingDetectIntent processes a natural language query in audio format in a streaming fashion -// and returns structured, actionable data as a result. This method is only -// available via the gRPC API (not REST). -// -// Note: Always use agent versions for production traffic. -// See Versions and -// environments (at https://cloud.google.com/dialogflow/es/docs/agents-versions). -func (c *SessionsClient) StreamingDetectIntent(ctx context.Context, opts ...gax.CallOption) (dialogflowpb.Sessions_StreamingDetectIntentClient, error) { +func (c *sessionsGRPCClient) StreamingDetectIntent(ctx context.Context, opts ...gax.CallOption) (dialogflowpb.Sessions_StreamingDetectIntentClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.StreamingDetectIntent[0:len(c.CallOptions.StreamingDetectIntent):len(c.CallOptions.StreamingDetectIntent)], opts...) var resp dialogflowpb.Sessions_StreamingDetectIntentClient + opts = append((*c.CallOptions).StreamingDetectIntent[0:len((*c.CallOptions).StreamingDetectIntent):len((*c.CallOptions).StreamingDetectIntent)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.sessionsClient.StreamingDetectIntent(ctx, settings.GRPC...) diff --git a/dialogflow/apiv2/sessions_client_example_test.go b/dialogflow/apiv2/sessions_client_example_test.go index ba72f9794405..6d668cdaf985 100644 --- a/dialogflow/apiv2/sessions_client_example_test.go +++ b/dialogflow/apiv2/sessions_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewSessionsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleSessionsClient_DetectIntent() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DetectIntentRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleSessionsClient_DetectIntent() { } func ExampleSessionsClient_StreamingDetectIntent() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.StreamingDetectIntent(ctx) if err != nil { // TODO: Handle error. diff --git a/dialogflow/apiv2/versions_client.go b/dialogflow/apiv2/versions_client.go index 9f7220001a3b..683c84fbed05 100644 --- a/dialogflow/apiv2/versions_client.go +++ b/dialogflow/apiv2/versions_client.go @@ -46,7 +46,7 @@ type VersionsCallOptions struct { DeleteVersion []gax.CallOption } -func defaultVersionsClientOptions() []option.ClientOption { +func defaultVersionsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,109 @@ func defaultVersionsCallOptions() *VersionsCallOptions { } } +// internalVersionsClient is an interface that defines the methods availaible from Dialogflow API. +type internalVersionsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListVersions(context.Context, *dialogflowpb.ListVersionsRequest, ...gax.CallOption) *VersionIterator + GetVersion(context.Context, *dialogflowpb.GetVersionRequest, ...gax.CallOption) (*dialogflowpb.Version, error) + CreateVersion(context.Context, *dialogflowpb.CreateVersionRequest, ...gax.CallOption) (*dialogflowpb.Version, error) + UpdateVersion(context.Context, *dialogflowpb.UpdateVersionRequest, ...gax.CallOption) (*dialogflowpb.Version, error) + DeleteVersion(context.Context, *dialogflowpb.DeleteVersionRequest, ...gax.CallOption) error +} + // VersionsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Versions. type VersionsClient struct { + // The internal transport-dependent client. + internalClient internalVersionsClient + + // The call options for this service. + CallOptions *VersionsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *VersionsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *VersionsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *VersionsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListVersions returns the list of all versions of the specified agent. +func (c *VersionsClient) ListVersions(ctx context.Context, req *dialogflowpb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { + return c.internalClient.ListVersions(ctx, req, opts...) +} + +// GetVersion retrieves the specified agent version. +func (c *VersionsClient) GetVersion(ctx context.Context, req *dialogflowpb.GetVersionRequest, opts ...gax.CallOption) (*dialogflowpb.Version, error) { + return c.internalClient.GetVersion(ctx, req, opts...) +} + +// CreateVersion creates an agent version. +// +// The new version points to the agent instance in the “default” environment. +func (c *VersionsClient) CreateVersion(ctx context.Context, req *dialogflowpb.CreateVersionRequest, opts ...gax.CallOption) (*dialogflowpb.Version, error) { + return c.internalClient.CreateVersion(ctx, req, opts...) +} + +// UpdateVersion updates the specified agent version. +// +// Note that this method does not allow you to update the state of the agent +// the given version points to. It allows you to update only mutable +// properties of the version resource. +func (c *VersionsClient) UpdateVersion(ctx context.Context, req *dialogflowpb.UpdateVersionRequest, opts ...gax.CallOption) (*dialogflowpb.Version, error) { + return c.internalClient.UpdateVersion(ctx, req, opts...) +} + +// DeleteVersion delete the specified agent version. +func (c *VersionsClient) DeleteVersion(ctx context.Context, req *dialogflowpb.DeleteVersionRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteVersion(ctx, req, opts...) +} + +// versionsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type versionsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing VersionsClient + CallOptions **VersionsCallOptions + // The gRPC API client. versionsClient dialogflowpb.VersionsClient - // The call options for this service. - CallOptions *VersionsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewVersionsClient creates a new versions client. +// NewVersionsClient creates a new versions client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Versions. func NewVersionsClient(ctx context.Context, opts ...option.ClientOption) (*VersionsClient, error) { - clientOpts := defaultVersionsClientOptions() - + clientOpts := defaultVersionsGRPCClientOptions() if newVersionsClientHook != nil { hookOpts, err := newVersionsClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,45 +238,47 @@ func NewVersionsClient(ctx context.Context, opts ...option.ClientOption) (*Versi if err != nil { return nil, err } - c := &VersionsClient{ + client := VersionsClient{CallOptions: defaultVersionsCallOptions()} + + c := &versionsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultVersionsCallOptions(), - - versionsClient: dialogflowpb.NewVersionsClient(connPool), + versionsClient: dialogflowpb.NewVersionsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *VersionsClient) Connection() *grpc.ClientConn { +func (c *versionsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *VersionsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *VersionsClient) setGoogleClientInfo(keyval ...string) { +func (c *versionsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListVersions returns the list of all versions of the specified agent. -func (c *VersionsClient) ListVersions(ctx context.Context, req *dialogflowpb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *versionsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *versionsGRPCClient) ListVersions(ctx context.Context, req *dialogflowpb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListVersions[0:len(c.CallOptions.ListVersions):len(c.CallOptions.ListVersions)], opts...) + opts = append((*c.CallOptions).ListVersions[0:len((*c.CallOptions).ListVersions):len((*c.CallOptions).ListVersions)], opts...) it := &VersionIterator{} req = proto.Clone(req).(*dialogflowpb.ListVersionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Version, string, error) { @@ -236,8 +315,7 @@ func (c *VersionsClient) ListVersions(ctx context.Context, req *dialogflowpb.Lis return it } -// GetVersion retrieves the specified agent version. -func (c *VersionsClient) GetVersion(ctx context.Context, req *dialogflowpb.GetVersionRequest, opts ...gax.CallOption) (*dialogflowpb.Version, error) { +func (c *versionsGRPCClient) GetVersion(ctx context.Context, req *dialogflowpb.GetVersionRequest, opts ...gax.CallOption) (*dialogflowpb.Version, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -245,7 +323,7 @@ func (c *VersionsClient) GetVersion(ctx context.Context, req *dialogflowpb.GetVe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetVersion[0:len(c.CallOptions.GetVersion):len(c.CallOptions.GetVersion)], opts...) + opts = append((*c.CallOptions).GetVersion[0:len((*c.CallOptions).GetVersion):len((*c.CallOptions).GetVersion)], opts...) var resp *dialogflowpb.Version err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -258,10 +336,7 @@ func (c *VersionsClient) GetVersion(ctx context.Context, req *dialogflowpb.GetVe return resp, nil } -// CreateVersion creates an agent version. -// -// The new version points to the agent instance in the “default” environment. -func (c *VersionsClient) CreateVersion(ctx context.Context, req *dialogflowpb.CreateVersionRequest, opts ...gax.CallOption) (*dialogflowpb.Version, error) { +func (c *versionsGRPCClient) CreateVersion(ctx context.Context, req *dialogflowpb.CreateVersionRequest, opts ...gax.CallOption) (*dialogflowpb.Version, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -269,7 +344,7 @@ func (c *VersionsClient) CreateVersion(ctx context.Context, req *dialogflowpb.Cr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateVersion[0:len(c.CallOptions.CreateVersion):len(c.CallOptions.CreateVersion)], opts...) + opts = append((*c.CallOptions).CreateVersion[0:len((*c.CallOptions).CreateVersion):len((*c.CallOptions).CreateVersion)], opts...) var resp *dialogflowpb.Version err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -282,12 +357,7 @@ func (c *VersionsClient) CreateVersion(ctx context.Context, req *dialogflowpb.Cr return resp, nil } -// UpdateVersion updates the specified agent version. -// -// Note that this method does not allow you to update the state of the agent -// the given version points to. It allows you to update only mutable -// properties of the version resource. -func (c *VersionsClient) UpdateVersion(ctx context.Context, req *dialogflowpb.UpdateVersionRequest, opts ...gax.CallOption) (*dialogflowpb.Version, error) { +func (c *versionsGRPCClient) UpdateVersion(ctx context.Context, req *dialogflowpb.UpdateVersionRequest, opts ...gax.CallOption) (*dialogflowpb.Version, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -295,7 +365,7 @@ func (c *VersionsClient) UpdateVersion(ctx context.Context, req *dialogflowpb.Up } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "version.name", url.QueryEscape(req.GetVersion().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateVersion[0:len(c.CallOptions.UpdateVersion):len(c.CallOptions.UpdateVersion)], opts...) + opts = append((*c.CallOptions).UpdateVersion[0:len((*c.CallOptions).UpdateVersion):len((*c.CallOptions).UpdateVersion)], opts...) var resp *dialogflowpb.Version err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -308,8 +378,7 @@ func (c *VersionsClient) UpdateVersion(ctx context.Context, req *dialogflowpb.Up return resp, nil } -// DeleteVersion delete the specified agent version. -func (c *VersionsClient) DeleteVersion(ctx context.Context, req *dialogflowpb.DeleteVersionRequest, opts ...gax.CallOption) error { +func (c *versionsGRPCClient) DeleteVersion(ctx context.Context, req *dialogflowpb.DeleteVersionRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -317,7 +386,7 @@ func (c *VersionsClient) DeleteVersion(ctx context.Context, req *dialogflowpb.De } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteVersion[0:len(c.CallOptions.DeleteVersion):len(c.CallOptions.DeleteVersion)], opts...) + opts = append((*c.CallOptions).DeleteVersion[0:len((*c.CallOptions).DeleteVersion):len((*c.CallOptions).DeleteVersion)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.versionsClient.DeleteVersion(ctx, req, settings.GRPC...) diff --git a/dialogflow/apiv2/versions_client_example_test.go b/dialogflow/apiv2/versions_client_example_test.go index dc5120c66a69..f9df27f4095f 100644 --- a/dialogflow/apiv2/versions_client_example_test.go +++ b/dialogflow/apiv2/versions_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewVersionsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleVersionsClient_ListVersions() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListVersionsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleVersionsClient_ListVersions() { } func ExampleVersionsClient_GetVersion() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetVersionRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleVersionsClient_GetVersion() { } func ExampleVersionsClient_CreateVersion() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateVersionRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleVersionsClient_CreateVersion() { } func ExampleVersionsClient_UpdateVersion() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateVersionRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleVersionsClient_DeleteVersion() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteVersionRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3/agents_client.go b/dialogflow/cx/apiv3/agents_client.go index 645d586b8e37..ed303b264f62 100644 --- a/dialogflow/cx/apiv3/agents_client.go +++ b/dialogflow/cx/apiv3/agents_client.go @@ -54,7 +54,7 @@ type AgentsCallOptions struct { GetAgentValidationResult []gax.CallOption } -func defaultAgentsClientOptions() []option.ClientOption { +func defaultAgentsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -170,37 +170,157 @@ func defaultAgentsCallOptions() *AgentsCallOptions { } } +// internalAgentsClient is an interface that defines the methods availaible from Dialogflow API. +type internalAgentsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListAgents(context.Context, *cxpb.ListAgentsRequest, ...gax.CallOption) *AgentIterator + GetAgent(context.Context, *cxpb.GetAgentRequest, ...gax.CallOption) (*cxpb.Agent, error) + CreateAgent(context.Context, *cxpb.CreateAgentRequest, ...gax.CallOption) (*cxpb.Agent, error) + UpdateAgent(context.Context, *cxpb.UpdateAgentRequest, ...gax.CallOption) (*cxpb.Agent, error) + DeleteAgent(context.Context, *cxpb.DeleteAgentRequest, ...gax.CallOption) error + ExportAgent(context.Context, *cxpb.ExportAgentRequest, ...gax.CallOption) (*ExportAgentOperation, error) + ExportAgentOperation(name string) *ExportAgentOperation + RestoreAgent(context.Context, *cxpb.RestoreAgentRequest, ...gax.CallOption) (*RestoreAgentOperation, error) + RestoreAgentOperation(name string) *RestoreAgentOperation + ValidateAgent(context.Context, *cxpb.ValidateAgentRequest, ...gax.CallOption) (*cxpb.AgentValidationResult, error) + GetAgentValidationResult(context.Context, *cxpb.GetAgentValidationResultRequest, ...gax.CallOption) (*cxpb.AgentValidationResult, error) +} + // AgentsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Agents. type AgentsClient struct { + // The internal transport-dependent client. + internalClient internalAgentsClient + + // The call options for this service. + CallOptions *AgentsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *AgentsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *AgentsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *AgentsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListAgents returns the list of all agents in the specified location. +func (c *AgentsClient) ListAgents(ctx context.Context, req *cxpb.ListAgentsRequest, opts ...gax.CallOption) *AgentIterator { + return c.internalClient.ListAgents(ctx, req, opts...) +} + +// GetAgent retrieves the specified agent. +func (c *AgentsClient) GetAgent(ctx context.Context, req *cxpb.GetAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { + return c.internalClient.GetAgent(ctx, req, opts...) +} + +// CreateAgent creates an agent in the specified location. +func (c *AgentsClient) CreateAgent(ctx context.Context, req *cxpb.CreateAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { + return c.internalClient.CreateAgent(ctx, req, opts...) +} + +// UpdateAgent updates the specified agent. +func (c *AgentsClient) UpdateAgent(ctx context.Context, req *cxpb.UpdateAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { + return c.internalClient.UpdateAgent(ctx, req, opts...) +} + +// DeleteAgent deletes the specified agent. +func (c *AgentsClient) DeleteAgent(ctx context.Context, req *cxpb.DeleteAgentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteAgent(ctx, req, opts...) +} + +// ExportAgent exports the specified agent to a binary file. +func (c *AgentsClient) ExportAgent(ctx context.Context, req *cxpb.ExportAgentRequest, opts ...gax.CallOption) (*ExportAgentOperation, error) { + return c.internalClient.ExportAgent(ctx, req, opts...) +} + +// ExportAgentOperation returns a new ExportAgentOperation from a given name. +// The name must be that of a previously created ExportAgentOperation, possibly from a different process. +func (c *AgentsClient) ExportAgentOperation(name string) *ExportAgentOperation { + return c.internalClient.ExportAgentOperation(name) +} + +// RestoreAgent restores the specified agent from a binary file. +// +// Replaces the current agent with a new one. Note that all existing resources +// in agent (e.g. intents, entity types, flows) will be removed. +func (c *AgentsClient) RestoreAgent(ctx context.Context, req *cxpb.RestoreAgentRequest, opts ...gax.CallOption) (*RestoreAgentOperation, error) { + return c.internalClient.RestoreAgent(ctx, req, opts...) +} + +// RestoreAgentOperation returns a new RestoreAgentOperation from a given name. +// The name must be that of a previously created RestoreAgentOperation, possibly from a different process. +func (c *AgentsClient) RestoreAgentOperation(name string) *RestoreAgentOperation { + return c.internalClient.RestoreAgentOperation(name) +} + +// ValidateAgent validates the specified agent and creates or updates validation results. +// The agent in draft version is validated. Please call this API after the +// training is completed to get the complete validation results. +func (c *AgentsClient) ValidateAgent(ctx context.Context, req *cxpb.ValidateAgentRequest, opts ...gax.CallOption) (*cxpb.AgentValidationResult, error) { + return c.internalClient.ValidateAgent(ctx, req, opts...) +} + +// GetAgentValidationResult gets the latest agent validation result. Agent validation is performed +// when ValidateAgent is called. +func (c *AgentsClient) GetAgentValidationResult(ctx context.Context, req *cxpb.GetAgentValidationResultRequest, opts ...gax.CallOption) (*cxpb.AgentValidationResult, error) { + return c.internalClient.GetAgentValidationResult(ctx, req, opts...) +} + +// agentsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type agentsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing AgentsClient + CallOptions **AgentsCallOptions + // The gRPC API client. agentsClient cxpb.AgentsClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *AgentsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewAgentsClient creates a new agents client. +// NewAgentsClient creates a new agents client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Agents. func NewAgentsClient(ctx context.Context, opts ...option.ClientOption) (*AgentsClient, error) { - clientOpts := defaultAgentsClientOptions() - + clientOpts := defaultAgentsGRPCClientOptions() if newAgentsClientHook != nil { hookOpts, err := newAgentsClientHook(ctx, clientHookParams{}) if err != nil { @@ -218,16 +338,19 @@ func NewAgentsClient(ctx context.Context, opts ...option.ClientOption) (*AgentsC if err != nil { return nil, err } - c := &AgentsClient{ + client := AgentsClient{CallOptions: defaultAgentsCallOptions()} + + c := &agentsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultAgentsCallOptions(), - - agentsClient: cxpb.NewAgentsClient(connPool), + agentsClient: cxpb.NewAgentsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -237,36 +360,36 @@ func NewAgentsClient(ctx context.Context, opts ...option.ClientOption) (*AgentsC // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *AgentsClient) Connection() *grpc.ClientConn { +func (c *agentsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *AgentsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *AgentsClient) setGoogleClientInfo(keyval ...string) { +func (c *agentsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListAgents returns the list of all agents in the specified location. -func (c *AgentsClient) ListAgents(ctx context.Context, req *cxpb.ListAgentsRequest, opts ...gax.CallOption) *AgentIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *agentsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *agentsGRPCClient) ListAgents(ctx context.Context, req *cxpb.ListAgentsRequest, opts ...gax.CallOption) *AgentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAgents[0:len(c.CallOptions.ListAgents):len(c.CallOptions.ListAgents)], opts...) + opts = append((*c.CallOptions).ListAgents[0:len((*c.CallOptions).ListAgents):len((*c.CallOptions).ListAgents)], opts...) it := &AgentIterator{} req = proto.Clone(req).(*cxpb.ListAgentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Agent, string, error) { @@ -303,8 +426,7 @@ func (c *AgentsClient) ListAgents(ctx context.Context, req *cxpb.ListAgentsReque return it } -// GetAgent retrieves the specified agent. -func (c *AgentsClient) GetAgent(ctx context.Context, req *cxpb.GetAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { +func (c *agentsGRPCClient) GetAgent(ctx context.Context, req *cxpb.GetAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -312,7 +434,7 @@ func (c *AgentsClient) GetAgent(ctx context.Context, req *cxpb.GetAgentRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetAgent[0:len(c.CallOptions.GetAgent):len(c.CallOptions.GetAgent)], opts...) + opts = append((*c.CallOptions).GetAgent[0:len((*c.CallOptions).GetAgent):len((*c.CallOptions).GetAgent)], opts...) var resp *cxpb.Agent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -325,8 +447,7 @@ func (c *AgentsClient) GetAgent(ctx context.Context, req *cxpb.GetAgentRequest, return resp, nil } -// CreateAgent creates an agent in the specified location. -func (c *AgentsClient) CreateAgent(ctx context.Context, req *cxpb.CreateAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { +func (c *agentsGRPCClient) CreateAgent(ctx context.Context, req *cxpb.CreateAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -334,7 +455,7 @@ func (c *AgentsClient) CreateAgent(ctx context.Context, req *cxpb.CreateAgentReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateAgent[0:len(c.CallOptions.CreateAgent):len(c.CallOptions.CreateAgent)], opts...) + opts = append((*c.CallOptions).CreateAgent[0:len((*c.CallOptions).CreateAgent):len((*c.CallOptions).CreateAgent)], opts...) var resp *cxpb.Agent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -347,8 +468,7 @@ func (c *AgentsClient) CreateAgent(ctx context.Context, req *cxpb.CreateAgentReq return resp, nil } -// UpdateAgent updates the specified agent. -func (c *AgentsClient) UpdateAgent(ctx context.Context, req *cxpb.UpdateAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { +func (c *agentsGRPCClient) UpdateAgent(ctx context.Context, req *cxpb.UpdateAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -356,7 +476,7 @@ func (c *AgentsClient) UpdateAgent(ctx context.Context, req *cxpb.UpdateAgentReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "agent.name", url.QueryEscape(req.GetAgent().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateAgent[0:len(c.CallOptions.UpdateAgent):len(c.CallOptions.UpdateAgent)], opts...) + opts = append((*c.CallOptions).UpdateAgent[0:len((*c.CallOptions).UpdateAgent):len((*c.CallOptions).UpdateAgent)], opts...) var resp *cxpb.Agent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -369,8 +489,7 @@ func (c *AgentsClient) UpdateAgent(ctx context.Context, req *cxpb.UpdateAgentReq return resp, nil } -// DeleteAgent deletes the specified agent. -func (c *AgentsClient) DeleteAgent(ctx context.Context, req *cxpb.DeleteAgentRequest, opts ...gax.CallOption) error { +func (c *agentsGRPCClient) DeleteAgent(ctx context.Context, req *cxpb.DeleteAgentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -378,7 +497,7 @@ func (c *AgentsClient) DeleteAgent(ctx context.Context, req *cxpb.DeleteAgentReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteAgent[0:len(c.CallOptions.DeleteAgent):len(c.CallOptions.DeleteAgent)], opts...) + opts = append((*c.CallOptions).DeleteAgent[0:len((*c.CallOptions).DeleteAgent):len((*c.CallOptions).DeleteAgent)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.agentsClient.DeleteAgent(ctx, req, settings.GRPC...) @@ -387,8 +506,7 @@ func (c *AgentsClient) DeleteAgent(ctx context.Context, req *cxpb.DeleteAgentReq return err } -// ExportAgent exports the specified agent to a binary file. -func (c *AgentsClient) ExportAgent(ctx context.Context, req *cxpb.ExportAgentRequest, opts ...gax.CallOption) (*ExportAgentOperation, error) { +func (c *agentsGRPCClient) ExportAgent(ctx context.Context, req *cxpb.ExportAgentRequest, opts ...gax.CallOption) (*ExportAgentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -396,7 +514,7 @@ func (c *AgentsClient) ExportAgent(ctx context.Context, req *cxpb.ExportAgentReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportAgent[0:len(c.CallOptions.ExportAgent):len(c.CallOptions.ExportAgent)], opts...) + opts = append((*c.CallOptions).ExportAgent[0:len((*c.CallOptions).ExportAgent):len((*c.CallOptions).ExportAgent)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -407,15 +525,11 @@ func (c *AgentsClient) ExportAgent(ctx context.Context, req *cxpb.ExportAgentReq return nil, err } return &ExportAgentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// RestoreAgent restores the specified agent from a binary file. -// -// Replaces the current agent with a new one. Note that all existing resources -// in agent (e.g. intents, entity types, flows) will be removed. -func (c *AgentsClient) RestoreAgent(ctx context.Context, req *cxpb.RestoreAgentRequest, opts ...gax.CallOption) (*RestoreAgentOperation, error) { +func (c *agentsGRPCClient) RestoreAgent(ctx context.Context, req *cxpb.RestoreAgentRequest, opts ...gax.CallOption) (*RestoreAgentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -423,7 +537,7 @@ func (c *AgentsClient) RestoreAgent(ctx context.Context, req *cxpb.RestoreAgentR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RestoreAgent[0:len(c.CallOptions.RestoreAgent):len(c.CallOptions.RestoreAgent)], opts...) + opts = append((*c.CallOptions).RestoreAgent[0:len((*c.CallOptions).RestoreAgent):len((*c.CallOptions).RestoreAgent)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -434,14 +548,11 @@ func (c *AgentsClient) RestoreAgent(ctx context.Context, req *cxpb.RestoreAgentR return nil, err } return &RestoreAgentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ValidateAgent validates the specified agent and creates or updates validation results. -// The agent in draft version is validated. Please call this API after the -// training is completed to get the complete validation results. -func (c *AgentsClient) ValidateAgent(ctx context.Context, req *cxpb.ValidateAgentRequest, opts ...gax.CallOption) (*cxpb.AgentValidationResult, error) { +func (c *agentsGRPCClient) ValidateAgent(ctx context.Context, req *cxpb.ValidateAgentRequest, opts ...gax.CallOption) (*cxpb.AgentValidationResult, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -449,7 +560,7 @@ func (c *AgentsClient) ValidateAgent(ctx context.Context, req *cxpb.ValidateAgen } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ValidateAgent[0:len(c.CallOptions.ValidateAgent):len(c.CallOptions.ValidateAgent)], opts...) + opts = append((*c.CallOptions).ValidateAgent[0:len((*c.CallOptions).ValidateAgent):len((*c.CallOptions).ValidateAgent)], opts...) var resp *cxpb.AgentValidationResult err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -462,9 +573,7 @@ func (c *AgentsClient) ValidateAgent(ctx context.Context, req *cxpb.ValidateAgen return resp, nil } -// GetAgentValidationResult gets the latest agent validation result. Agent validation is performed -// when ValidateAgent is called. -func (c *AgentsClient) GetAgentValidationResult(ctx context.Context, req *cxpb.GetAgentValidationResultRequest, opts ...gax.CallOption) (*cxpb.AgentValidationResult, error) { +func (c *agentsGRPCClient) GetAgentValidationResult(ctx context.Context, req *cxpb.GetAgentValidationResultRequest, opts ...gax.CallOption) (*cxpb.AgentValidationResult, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -472,7 +581,7 @@ func (c *AgentsClient) GetAgentValidationResult(ctx context.Context, req *cxpb.G } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetAgentValidationResult[0:len(c.CallOptions.GetAgentValidationResult):len(c.CallOptions.GetAgentValidationResult)], opts...) + opts = append((*c.CallOptions).GetAgentValidationResult[0:len((*c.CallOptions).GetAgentValidationResult):len((*c.CallOptions).GetAgentValidationResult)], opts...) var resp *cxpb.AgentValidationResult err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -492,9 +601,9 @@ type ExportAgentOperation struct { // ExportAgentOperation returns a new ExportAgentOperation from a given name. // The name must be that of a previously created ExportAgentOperation, possibly from a different process. -func (c *AgentsClient) ExportAgentOperation(name string) *ExportAgentOperation { +func (c *agentsGRPCClient) ExportAgentOperation(name string) *ExportAgentOperation { return &ExportAgentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -561,9 +670,9 @@ type RestoreAgentOperation struct { // RestoreAgentOperation returns a new RestoreAgentOperation from a given name. // The name must be that of a previously created RestoreAgentOperation, possibly from a different process. -func (c *AgentsClient) RestoreAgentOperation(name string) *RestoreAgentOperation { +func (c *agentsGRPCClient) RestoreAgentOperation(name string) *RestoreAgentOperation { return &RestoreAgentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dialogflow/cx/apiv3/agents_client_example_test.go b/dialogflow/cx/apiv3/agents_client_example_test.go index 848ab2d8ac31..2e3326a7a243 100644 --- a/dialogflow/cx/apiv3/agents_client_example_test.go +++ b/dialogflow/cx/apiv3/agents_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewAgentsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleAgentsClient_ListAgents() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListAgentsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleAgentsClient_ListAgents() { } func ExampleAgentsClient_GetAgent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetAgentRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleAgentsClient_GetAgent() { } func ExampleAgentsClient_CreateAgent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateAgentRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleAgentsClient_CreateAgent() { } func ExampleAgentsClient_UpdateAgent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateAgentRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleAgentsClient_DeleteAgent() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteAgentRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleAgentsClient_DeleteAgent() { } func ExampleAgentsClient_ExportAgent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ExportAgentRequest{ // TODO: Fill request struct fields. @@ -163,13 +160,12 @@ func ExampleAgentsClient_ExportAgent() { } func ExampleAgentsClient_RestoreAgent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.RestoreAgentRequest{ // TODO: Fill request struct fields. @@ -186,13 +182,12 @@ func ExampleAgentsClient_RestoreAgent() { } func ExampleAgentsClient_ValidateAgent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ValidateAgentRequest{ // TODO: Fill request struct fields. @@ -206,13 +201,12 @@ func ExampleAgentsClient_ValidateAgent() { } func ExampleAgentsClient_GetAgentValidationResult() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetAgentValidationResultRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3/doc.go b/dialogflow/cx/apiv3/doc.go index dbd0fbb208f1..168a07292074 100644 --- a/dialogflow/cx/apiv3/doc.go +++ b/dialogflow/cx/apiv3/doc.go @@ -20,6 +20,8 @@ // Builds conversational interfaces (for example, chatbots, and voice-powered // apps and devices). // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package cx // import "cloud.google.com/go/dialogflow/cx/apiv3" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/dialogflow/cx/apiv3/entity_types_client.go b/dialogflow/cx/apiv3/entity_types_client.go index 1283b1ac9baf..60008bf12bcf 100644 --- a/dialogflow/cx/apiv3/entity_types_client.go +++ b/dialogflow/cx/apiv3/entity_types_client.go @@ -46,7 +46,7 @@ type EntityTypesCallOptions struct { DeleteEntityType []gax.CallOption } -func defaultEntityTypesClientOptions() []option.ClientOption { +func defaultEntityTypesGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,103 @@ func defaultEntityTypesCallOptions() *EntityTypesCallOptions { } } +// internalEntityTypesClient is an interface that defines the methods availaible from Dialogflow API. +type internalEntityTypesClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListEntityTypes(context.Context, *cxpb.ListEntityTypesRequest, ...gax.CallOption) *EntityTypeIterator + GetEntityType(context.Context, *cxpb.GetEntityTypeRequest, ...gax.CallOption) (*cxpb.EntityType, error) + CreateEntityType(context.Context, *cxpb.CreateEntityTypeRequest, ...gax.CallOption) (*cxpb.EntityType, error) + UpdateEntityType(context.Context, *cxpb.UpdateEntityTypeRequest, ...gax.CallOption) (*cxpb.EntityType, error) + DeleteEntityType(context.Context, *cxpb.DeleteEntityTypeRequest, ...gax.CallOption) error +} + // EntityTypesClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing EntityTypes. type EntityTypesClient struct { + // The internal transport-dependent client. + internalClient internalEntityTypesClient + + // The call options for this service. + CallOptions *EntityTypesCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *EntityTypesClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *EntityTypesClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *EntityTypesClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListEntityTypes returns the list of all entity types in the specified agent. +func (c *EntityTypesClient) ListEntityTypes(ctx context.Context, req *cxpb.ListEntityTypesRequest, opts ...gax.CallOption) *EntityTypeIterator { + return c.internalClient.ListEntityTypes(ctx, req, opts...) +} + +// GetEntityType retrieves the specified entity type. +func (c *EntityTypesClient) GetEntityType(ctx context.Context, req *cxpb.GetEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { + return c.internalClient.GetEntityType(ctx, req, opts...) +} + +// CreateEntityType creates an entity type in the specified agent. +func (c *EntityTypesClient) CreateEntityType(ctx context.Context, req *cxpb.CreateEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { + return c.internalClient.CreateEntityType(ctx, req, opts...) +} + +// UpdateEntityType updates the specified entity type. +func (c *EntityTypesClient) UpdateEntityType(ctx context.Context, req *cxpb.UpdateEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { + return c.internalClient.UpdateEntityType(ctx, req, opts...) +} + +// DeleteEntityType deletes the specified entity type. +func (c *EntityTypesClient) DeleteEntityType(ctx context.Context, req *cxpb.DeleteEntityTypeRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteEntityType(ctx, req, opts...) +} + +// entityTypesGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type entityTypesGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing EntityTypesClient + CallOptions **EntityTypesCallOptions + // The gRPC API client. entityTypesClient cxpb.EntityTypesClient - // The call options for this service. - CallOptions *EntityTypesCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewEntityTypesClient creates a new entity types client. +// NewEntityTypesClient creates a new entity types client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing EntityTypes. func NewEntityTypesClient(ctx context.Context, opts ...option.ClientOption) (*EntityTypesClient, error) { - clientOpts := defaultEntityTypesClientOptions() - + clientOpts := defaultEntityTypesGRPCClientOptions() if newEntityTypesClientHook != nil { hookOpts, err := newEntityTypesClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,45 +232,47 @@ func NewEntityTypesClient(ctx context.Context, opts ...option.ClientOption) (*En if err != nil { return nil, err } - c := &EntityTypesClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultEntityTypesCallOptions(), + client := EntityTypesClient{CallOptions: defaultEntityTypesCallOptions()} + c := &entityTypesGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, entityTypesClient: cxpb.NewEntityTypesClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *EntityTypesClient) Connection() *grpc.ClientConn { +func (c *entityTypesGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *EntityTypesClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *EntityTypesClient) setGoogleClientInfo(keyval ...string) { +func (c *entityTypesGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListEntityTypes returns the list of all entity types in the specified agent. -func (c *EntityTypesClient) ListEntityTypes(ctx context.Context, req *cxpb.ListEntityTypesRequest, opts ...gax.CallOption) *EntityTypeIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *entityTypesGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *entityTypesGRPCClient) ListEntityTypes(ctx context.Context, req *cxpb.ListEntityTypesRequest, opts ...gax.CallOption) *EntityTypeIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListEntityTypes[0:len(c.CallOptions.ListEntityTypes):len(c.CallOptions.ListEntityTypes)], opts...) + opts = append((*c.CallOptions).ListEntityTypes[0:len((*c.CallOptions).ListEntityTypes):len((*c.CallOptions).ListEntityTypes)], opts...) it := &EntityTypeIterator{} req = proto.Clone(req).(*cxpb.ListEntityTypesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.EntityType, string, error) { @@ -236,8 +309,7 @@ func (c *EntityTypesClient) ListEntityTypes(ctx context.Context, req *cxpb.ListE return it } -// GetEntityType retrieves the specified entity type. -func (c *EntityTypesClient) GetEntityType(ctx context.Context, req *cxpb.GetEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { +func (c *entityTypesGRPCClient) GetEntityType(ctx context.Context, req *cxpb.GetEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -245,7 +317,7 @@ func (c *EntityTypesClient) GetEntityType(ctx context.Context, req *cxpb.GetEnti } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEntityType[0:len(c.CallOptions.GetEntityType):len(c.CallOptions.GetEntityType)], opts...) + opts = append((*c.CallOptions).GetEntityType[0:len((*c.CallOptions).GetEntityType):len((*c.CallOptions).GetEntityType)], opts...) var resp *cxpb.EntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -258,8 +330,7 @@ func (c *EntityTypesClient) GetEntityType(ctx context.Context, req *cxpb.GetEnti return resp, nil } -// CreateEntityType creates an entity type in the specified agent. -func (c *EntityTypesClient) CreateEntityType(ctx context.Context, req *cxpb.CreateEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { +func (c *entityTypesGRPCClient) CreateEntityType(ctx context.Context, req *cxpb.CreateEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -267,7 +338,7 @@ func (c *EntityTypesClient) CreateEntityType(ctx context.Context, req *cxpb.Crea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateEntityType[0:len(c.CallOptions.CreateEntityType):len(c.CallOptions.CreateEntityType)], opts...) + opts = append((*c.CallOptions).CreateEntityType[0:len((*c.CallOptions).CreateEntityType):len((*c.CallOptions).CreateEntityType)], opts...) var resp *cxpb.EntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -280,8 +351,7 @@ func (c *EntityTypesClient) CreateEntityType(ctx context.Context, req *cxpb.Crea return resp, nil } -// UpdateEntityType updates the specified entity type. -func (c *EntityTypesClient) UpdateEntityType(ctx context.Context, req *cxpb.UpdateEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { +func (c *entityTypesGRPCClient) UpdateEntityType(ctx context.Context, req *cxpb.UpdateEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -289,7 +359,7 @@ func (c *EntityTypesClient) UpdateEntityType(ctx context.Context, req *cxpb.Upda } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "entity_type.name", url.QueryEscape(req.GetEntityType().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateEntityType[0:len(c.CallOptions.UpdateEntityType):len(c.CallOptions.UpdateEntityType)], opts...) + opts = append((*c.CallOptions).UpdateEntityType[0:len((*c.CallOptions).UpdateEntityType):len((*c.CallOptions).UpdateEntityType)], opts...) var resp *cxpb.EntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -302,8 +372,7 @@ func (c *EntityTypesClient) UpdateEntityType(ctx context.Context, req *cxpb.Upda return resp, nil } -// DeleteEntityType deletes the specified entity type. -func (c *EntityTypesClient) DeleteEntityType(ctx context.Context, req *cxpb.DeleteEntityTypeRequest, opts ...gax.CallOption) error { +func (c *entityTypesGRPCClient) DeleteEntityType(ctx context.Context, req *cxpb.DeleteEntityTypeRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -311,7 +380,7 @@ func (c *EntityTypesClient) DeleteEntityType(ctx context.Context, req *cxpb.Dele } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteEntityType[0:len(c.CallOptions.DeleteEntityType):len(c.CallOptions.DeleteEntityType)], opts...) + opts = append((*c.CallOptions).DeleteEntityType[0:len((*c.CallOptions).DeleteEntityType):len((*c.CallOptions).DeleteEntityType)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.entityTypesClient.DeleteEntityType(ctx, req, settings.GRPC...) diff --git a/dialogflow/cx/apiv3/entity_types_client_example_test.go b/dialogflow/cx/apiv3/entity_types_client_example_test.go index 8f54b093340e..7052f70daa0f 100644 --- a/dialogflow/cx/apiv3/entity_types_client_example_test.go +++ b/dialogflow/cx/apiv3/entity_types_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewEntityTypesClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleEntityTypesClient_ListEntityTypes() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListEntityTypesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleEntityTypesClient_ListEntityTypes() { } func ExampleEntityTypesClient_GetEntityType() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetEntityTypeRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleEntityTypesClient_GetEntityType() { } func ExampleEntityTypesClient_CreateEntityType() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateEntityTypeRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleEntityTypesClient_CreateEntityType() { } func ExampleEntityTypesClient_UpdateEntityType() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateEntityTypeRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleEntityTypesClient_DeleteEntityType() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3/environments_client.go b/dialogflow/cx/apiv3/environments_client.go index 3aeeb5e1a37e..029c4930ce88 100644 --- a/dialogflow/cx/apiv3/environments_client.go +++ b/dialogflow/cx/apiv3/environments_client.go @@ -51,7 +51,7 @@ type EnvironmentsCallOptions struct { LookupEnvironmentHistory []gax.CallOption } -func defaultEnvironmentsClientOptions() []option.ClientOption { +func defaultEnvironmentsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -134,37 +134,133 @@ func defaultEnvironmentsCallOptions() *EnvironmentsCallOptions { } } +// internalEnvironmentsClient is an interface that defines the methods availaible from Dialogflow API. +type internalEnvironmentsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListEnvironments(context.Context, *cxpb.ListEnvironmentsRequest, ...gax.CallOption) *EnvironmentIterator + GetEnvironment(context.Context, *cxpb.GetEnvironmentRequest, ...gax.CallOption) (*cxpb.Environment, error) + CreateEnvironment(context.Context, *cxpb.CreateEnvironmentRequest, ...gax.CallOption) (*CreateEnvironmentOperation, error) + CreateEnvironmentOperation(name string) *CreateEnvironmentOperation + UpdateEnvironment(context.Context, *cxpb.UpdateEnvironmentRequest, ...gax.CallOption) (*UpdateEnvironmentOperation, error) + UpdateEnvironmentOperation(name string) *UpdateEnvironmentOperation + DeleteEnvironment(context.Context, *cxpb.DeleteEnvironmentRequest, ...gax.CallOption) error + LookupEnvironmentHistory(context.Context, *cxpb.LookupEnvironmentHistoryRequest, ...gax.CallOption) *EnvironmentIterator +} + // EnvironmentsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Environments. type EnvironmentsClient struct { + // The internal transport-dependent client. + internalClient internalEnvironmentsClient + + // The call options for this service. + CallOptions *EnvironmentsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *EnvironmentsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *EnvironmentsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *EnvironmentsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListEnvironments returns the list of all environments in the specified Agent. +func (c *EnvironmentsClient) ListEnvironments(ctx context.Context, req *cxpb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { + return c.internalClient.ListEnvironments(ctx, req, opts...) +} + +// GetEnvironment retrieves the specified Environment. +func (c *EnvironmentsClient) GetEnvironment(ctx context.Context, req *cxpb.GetEnvironmentRequest, opts ...gax.CallOption) (*cxpb.Environment, error) { + return c.internalClient.GetEnvironment(ctx, req, opts...) +} + +// CreateEnvironment creates an Environment in the specified Agent. +func (c *EnvironmentsClient) CreateEnvironment(ctx context.Context, req *cxpb.CreateEnvironmentRequest, opts ...gax.CallOption) (*CreateEnvironmentOperation, error) { + return c.internalClient.CreateEnvironment(ctx, req, opts...) +} + +// CreateEnvironmentOperation returns a new CreateEnvironmentOperation from a given name. +// The name must be that of a previously created CreateEnvironmentOperation, possibly from a different process. +func (c *EnvironmentsClient) CreateEnvironmentOperation(name string) *CreateEnvironmentOperation { + return c.internalClient.CreateEnvironmentOperation(name) +} + +// UpdateEnvironment updates the specified Environment. +func (c *EnvironmentsClient) UpdateEnvironment(ctx context.Context, req *cxpb.UpdateEnvironmentRequest, opts ...gax.CallOption) (*UpdateEnvironmentOperation, error) { + return c.internalClient.UpdateEnvironment(ctx, req, opts...) +} + +// UpdateEnvironmentOperation returns a new UpdateEnvironmentOperation from a given name. +// The name must be that of a previously created UpdateEnvironmentOperation, possibly from a different process. +func (c *EnvironmentsClient) UpdateEnvironmentOperation(name string) *UpdateEnvironmentOperation { + return c.internalClient.UpdateEnvironmentOperation(name) +} + +// DeleteEnvironment deletes the specified Environment. +func (c *EnvironmentsClient) DeleteEnvironment(ctx context.Context, req *cxpb.DeleteEnvironmentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteEnvironment(ctx, req, opts...) +} + +// LookupEnvironmentHistory looks up the history of the specified Environment. +func (c *EnvironmentsClient) LookupEnvironmentHistory(ctx context.Context, req *cxpb.LookupEnvironmentHistoryRequest, opts ...gax.CallOption) *EnvironmentIterator { + return c.internalClient.LookupEnvironmentHistory(ctx, req, opts...) +} + +// environmentsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type environmentsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing EnvironmentsClient + CallOptions **EnvironmentsCallOptions + // The gRPC API client. environmentsClient cxpb.EnvironmentsClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *EnvironmentsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewEnvironmentsClient creates a new environments client. +// NewEnvironmentsClient creates a new environments client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Environments. func NewEnvironmentsClient(ctx context.Context, opts ...option.ClientOption) (*EnvironmentsClient, error) { - clientOpts := defaultEnvironmentsClientOptions() - + clientOpts := defaultEnvironmentsGRPCClientOptions() if newEnvironmentsClientHook != nil { hookOpts, err := newEnvironmentsClientHook(ctx, clientHookParams{}) if err != nil { @@ -182,16 +278,19 @@ func NewEnvironmentsClient(ctx context.Context, opts ...option.ClientOption) (*E if err != nil { return nil, err } - c := &EnvironmentsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultEnvironmentsCallOptions(), + client := EnvironmentsClient{CallOptions: defaultEnvironmentsCallOptions()} + c := &environmentsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, environmentsClient: cxpb.NewEnvironmentsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -201,36 +300,36 @@ func NewEnvironmentsClient(ctx context.Context, opts ...option.ClientOption) (*E // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *EnvironmentsClient) Connection() *grpc.ClientConn { +func (c *environmentsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *EnvironmentsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *EnvironmentsClient) setGoogleClientInfo(keyval ...string) { +func (c *environmentsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListEnvironments returns the list of all environments in the specified Agent. -func (c *EnvironmentsClient) ListEnvironments(ctx context.Context, req *cxpb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *environmentsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *environmentsGRPCClient) ListEnvironments(ctx context.Context, req *cxpb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListEnvironments[0:len(c.CallOptions.ListEnvironments):len(c.CallOptions.ListEnvironments)], opts...) + opts = append((*c.CallOptions).ListEnvironments[0:len((*c.CallOptions).ListEnvironments):len((*c.CallOptions).ListEnvironments)], opts...) it := &EnvironmentIterator{} req = proto.Clone(req).(*cxpb.ListEnvironmentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Environment, string, error) { @@ -267,8 +366,7 @@ func (c *EnvironmentsClient) ListEnvironments(ctx context.Context, req *cxpb.Lis return it } -// GetEnvironment retrieves the specified Environment. -func (c *EnvironmentsClient) GetEnvironment(ctx context.Context, req *cxpb.GetEnvironmentRequest, opts ...gax.CallOption) (*cxpb.Environment, error) { +func (c *environmentsGRPCClient) GetEnvironment(ctx context.Context, req *cxpb.GetEnvironmentRequest, opts ...gax.CallOption) (*cxpb.Environment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -276,7 +374,7 @@ func (c *EnvironmentsClient) GetEnvironment(ctx context.Context, req *cxpb.GetEn } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEnvironment[0:len(c.CallOptions.GetEnvironment):len(c.CallOptions.GetEnvironment)], opts...) + opts = append((*c.CallOptions).GetEnvironment[0:len((*c.CallOptions).GetEnvironment):len((*c.CallOptions).GetEnvironment)], opts...) var resp *cxpb.Environment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -289,8 +387,7 @@ func (c *EnvironmentsClient) GetEnvironment(ctx context.Context, req *cxpb.GetEn return resp, nil } -// CreateEnvironment creates an Environment in the specified Agent. -func (c *EnvironmentsClient) CreateEnvironment(ctx context.Context, req *cxpb.CreateEnvironmentRequest, opts ...gax.CallOption) (*CreateEnvironmentOperation, error) { +func (c *environmentsGRPCClient) CreateEnvironment(ctx context.Context, req *cxpb.CreateEnvironmentRequest, opts ...gax.CallOption) (*CreateEnvironmentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -298,7 +395,7 @@ func (c *EnvironmentsClient) CreateEnvironment(ctx context.Context, req *cxpb.Cr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateEnvironment[0:len(c.CallOptions.CreateEnvironment):len(c.CallOptions.CreateEnvironment)], opts...) + opts = append((*c.CallOptions).CreateEnvironment[0:len((*c.CallOptions).CreateEnvironment):len((*c.CallOptions).CreateEnvironment)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -309,12 +406,11 @@ func (c *EnvironmentsClient) CreateEnvironment(ctx context.Context, req *cxpb.Cr return nil, err } return &CreateEnvironmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateEnvironment updates the specified Environment. -func (c *EnvironmentsClient) UpdateEnvironment(ctx context.Context, req *cxpb.UpdateEnvironmentRequest, opts ...gax.CallOption) (*UpdateEnvironmentOperation, error) { +func (c *environmentsGRPCClient) UpdateEnvironment(ctx context.Context, req *cxpb.UpdateEnvironmentRequest, opts ...gax.CallOption) (*UpdateEnvironmentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -322,7 +418,7 @@ func (c *EnvironmentsClient) UpdateEnvironment(ctx context.Context, req *cxpb.Up } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "environment.name", url.QueryEscape(req.GetEnvironment().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateEnvironment[0:len(c.CallOptions.UpdateEnvironment):len(c.CallOptions.UpdateEnvironment)], opts...) + opts = append((*c.CallOptions).UpdateEnvironment[0:len((*c.CallOptions).UpdateEnvironment):len((*c.CallOptions).UpdateEnvironment)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -333,12 +429,11 @@ func (c *EnvironmentsClient) UpdateEnvironment(ctx context.Context, req *cxpb.Up return nil, err } return &UpdateEnvironmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteEnvironment deletes the specified Environment. -func (c *EnvironmentsClient) DeleteEnvironment(ctx context.Context, req *cxpb.DeleteEnvironmentRequest, opts ...gax.CallOption) error { +func (c *environmentsGRPCClient) DeleteEnvironment(ctx context.Context, req *cxpb.DeleteEnvironmentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -346,7 +441,7 @@ func (c *EnvironmentsClient) DeleteEnvironment(ctx context.Context, req *cxpb.De } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteEnvironment[0:len(c.CallOptions.DeleteEnvironment):len(c.CallOptions.DeleteEnvironment)], opts...) + opts = append((*c.CallOptions).DeleteEnvironment[0:len((*c.CallOptions).DeleteEnvironment):len((*c.CallOptions).DeleteEnvironment)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.environmentsClient.DeleteEnvironment(ctx, req, settings.GRPC...) @@ -355,11 +450,10 @@ func (c *EnvironmentsClient) DeleteEnvironment(ctx context.Context, req *cxpb.De return err } -// LookupEnvironmentHistory looks up the history of the specified Environment. -func (c *EnvironmentsClient) LookupEnvironmentHistory(ctx context.Context, req *cxpb.LookupEnvironmentHistoryRequest, opts ...gax.CallOption) *EnvironmentIterator { +func (c *environmentsGRPCClient) LookupEnvironmentHistory(ctx context.Context, req *cxpb.LookupEnvironmentHistoryRequest, opts ...gax.CallOption) *EnvironmentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.LookupEnvironmentHistory[0:len(c.CallOptions.LookupEnvironmentHistory):len(c.CallOptions.LookupEnvironmentHistory)], opts...) + opts = append((*c.CallOptions).LookupEnvironmentHistory[0:len((*c.CallOptions).LookupEnvironmentHistory):len((*c.CallOptions).LookupEnvironmentHistory)], opts...) it := &EnvironmentIterator{} req = proto.Clone(req).(*cxpb.LookupEnvironmentHistoryRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Environment, string, error) { @@ -403,9 +497,9 @@ type CreateEnvironmentOperation struct { // CreateEnvironmentOperation returns a new CreateEnvironmentOperation from a given name. // The name must be that of a previously created CreateEnvironmentOperation, possibly from a different process. -func (c *EnvironmentsClient) CreateEnvironmentOperation(name string) *CreateEnvironmentOperation { +func (c *environmentsGRPCClient) CreateEnvironmentOperation(name string) *CreateEnvironmentOperation { return &CreateEnvironmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -472,9 +566,9 @@ type UpdateEnvironmentOperation struct { // UpdateEnvironmentOperation returns a new UpdateEnvironmentOperation from a given name. // The name must be that of a previously created UpdateEnvironmentOperation, possibly from a different process. -func (c *EnvironmentsClient) UpdateEnvironmentOperation(name string) *UpdateEnvironmentOperation { +func (c *environmentsGRPCClient) UpdateEnvironmentOperation(name string) *UpdateEnvironmentOperation { return &UpdateEnvironmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dialogflow/cx/apiv3/environments_client_example_test.go b/dialogflow/cx/apiv3/environments_client_example_test.go index d94824607ceb..ab6c5ae047fb 100644 --- a/dialogflow/cx/apiv3/environments_client_example_test.go +++ b/dialogflow/cx/apiv3/environments_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewEnvironmentsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleEnvironmentsClient_ListEnvironments() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListEnvironmentsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleEnvironmentsClient_ListEnvironments() { } func ExampleEnvironmentsClient_GetEnvironment() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetEnvironmentRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleEnvironmentsClient_GetEnvironment() { } func ExampleEnvironmentsClient_CreateEnvironment() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateEnvironmentRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleEnvironmentsClient_CreateEnvironment() { } func ExampleEnvironmentsClient_UpdateEnvironment() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateEnvironmentRequest{ // TODO: Fill request struct fields. @@ -137,6 +134,7 @@ func ExampleEnvironmentsClient_DeleteEnvironment() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteEnvironmentRequest{ // TODO: Fill request struct fields. @@ -148,14 +146,12 @@ func ExampleEnvironmentsClient_DeleteEnvironment() { } func ExampleEnvironmentsClient_LookupEnvironmentHistory() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.LookupEnvironmentHistoryRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3/experiments_client.go b/dialogflow/cx/apiv3/experiments_client.go index 390c542bd69f..0633ddc9fa25 100644 --- a/dialogflow/cx/apiv3/experiments_client.go +++ b/dialogflow/cx/apiv3/experiments_client.go @@ -48,7 +48,7 @@ type ExperimentsCallOptions struct { StopExperiment []gax.CallOption } -func defaultExperimentsClientOptions() []option.ClientOption { +func defaultExperimentsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -142,32 +142,117 @@ func defaultExperimentsCallOptions() *ExperimentsCallOptions { } } +// internalExperimentsClient is an interface that defines the methods availaible from Dialogflow API. +type internalExperimentsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListExperiments(context.Context, *cxpb.ListExperimentsRequest, ...gax.CallOption) *ExperimentIterator + GetExperiment(context.Context, *cxpb.GetExperimentRequest, ...gax.CallOption) (*cxpb.Experiment, error) + CreateExperiment(context.Context, *cxpb.CreateExperimentRequest, ...gax.CallOption) (*cxpb.Experiment, error) + UpdateExperiment(context.Context, *cxpb.UpdateExperimentRequest, ...gax.CallOption) (*cxpb.Experiment, error) + DeleteExperiment(context.Context, *cxpb.DeleteExperimentRequest, ...gax.CallOption) error + StartExperiment(context.Context, *cxpb.StartExperimentRequest, ...gax.CallOption) (*cxpb.Experiment, error) + StopExperiment(context.Context, *cxpb.StopExperimentRequest, ...gax.CallOption) (*cxpb.Experiment, error) +} + // ExperimentsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Experiments. type ExperimentsClient struct { + // The internal transport-dependent client. + internalClient internalExperimentsClient + + // The call options for this service. + CallOptions *ExperimentsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ExperimentsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ExperimentsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ExperimentsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListExperiments returns the list of all experiments in the specified Environment. +func (c *ExperimentsClient) ListExperiments(ctx context.Context, req *cxpb.ListExperimentsRequest, opts ...gax.CallOption) *ExperimentIterator { + return c.internalClient.ListExperiments(ctx, req, opts...) +} + +// GetExperiment retrieves the specified Experiment. +func (c *ExperimentsClient) GetExperiment(ctx context.Context, req *cxpb.GetExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { + return c.internalClient.GetExperiment(ctx, req, opts...) +} + +// CreateExperiment creates an Experiment in the specified Environment. +func (c *ExperimentsClient) CreateExperiment(ctx context.Context, req *cxpb.CreateExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { + return c.internalClient.CreateExperiment(ctx, req, opts...) +} + +// UpdateExperiment updates the specified Experiment. +func (c *ExperimentsClient) UpdateExperiment(ctx context.Context, req *cxpb.UpdateExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { + return c.internalClient.UpdateExperiment(ctx, req, opts...) +} + +// DeleteExperiment deletes the specified Experiment. +func (c *ExperimentsClient) DeleteExperiment(ctx context.Context, req *cxpb.DeleteExperimentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteExperiment(ctx, req, opts...) +} + +// StartExperiment starts the specified Experiment. This rpc only changes the state of +// experiment from PENDING to RUNNING. +func (c *ExperimentsClient) StartExperiment(ctx context.Context, req *cxpb.StartExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { + return c.internalClient.StartExperiment(ctx, req, opts...) +} + +// StopExperiment stops the specified Experiment. This rpc only changes the state of +// experiment from RUNNING to DONE. +func (c *ExperimentsClient) StopExperiment(ctx context.Context, req *cxpb.StopExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { + return c.internalClient.StopExperiment(ctx, req, opts...) +} + +// experimentsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type experimentsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ExperimentsClient + CallOptions **ExperimentsCallOptions + // The gRPC API client. experimentsClient cxpb.ExperimentsClient - // The call options for this service. - CallOptions *ExperimentsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewExperimentsClient creates a new experiments client. +// NewExperimentsClient creates a new experiments client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Experiments. func NewExperimentsClient(ctx context.Context, opts ...option.ClientOption) (*ExperimentsClient, error) { - clientOpts := defaultExperimentsClientOptions() - + clientOpts := defaultExperimentsGRPCClientOptions() if newExperimentsClientHook != nil { hookOpts, err := newExperimentsClientHook(ctx, clientHookParams{}) if err != nil { @@ -185,45 +270,47 @@ func NewExperimentsClient(ctx context.Context, opts ...option.ClientOption) (*Ex if err != nil { return nil, err } - c := &ExperimentsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultExperimentsCallOptions(), + client := ExperimentsClient{CallOptions: defaultExperimentsCallOptions()} + c := &experimentsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, experimentsClient: cxpb.NewExperimentsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ExperimentsClient) Connection() *grpc.ClientConn { +func (c *experimentsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ExperimentsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ExperimentsClient) setGoogleClientInfo(keyval ...string) { +func (c *experimentsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListExperiments returns the list of all experiments in the specified Environment. -func (c *ExperimentsClient) ListExperiments(ctx context.Context, req *cxpb.ListExperimentsRequest, opts ...gax.CallOption) *ExperimentIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *experimentsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *experimentsGRPCClient) ListExperiments(ctx context.Context, req *cxpb.ListExperimentsRequest, opts ...gax.CallOption) *ExperimentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListExperiments[0:len(c.CallOptions.ListExperiments):len(c.CallOptions.ListExperiments)], opts...) + opts = append((*c.CallOptions).ListExperiments[0:len((*c.CallOptions).ListExperiments):len((*c.CallOptions).ListExperiments)], opts...) it := &ExperimentIterator{} req = proto.Clone(req).(*cxpb.ListExperimentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Experiment, string, error) { @@ -260,8 +347,7 @@ func (c *ExperimentsClient) ListExperiments(ctx context.Context, req *cxpb.ListE return it } -// GetExperiment retrieves the specified Experiment. -func (c *ExperimentsClient) GetExperiment(ctx context.Context, req *cxpb.GetExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { +func (c *experimentsGRPCClient) GetExperiment(ctx context.Context, req *cxpb.GetExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -269,7 +355,7 @@ func (c *ExperimentsClient) GetExperiment(ctx context.Context, req *cxpb.GetExpe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetExperiment[0:len(c.CallOptions.GetExperiment):len(c.CallOptions.GetExperiment)], opts...) + opts = append((*c.CallOptions).GetExperiment[0:len((*c.CallOptions).GetExperiment):len((*c.CallOptions).GetExperiment)], opts...) var resp *cxpb.Experiment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -282,8 +368,7 @@ func (c *ExperimentsClient) GetExperiment(ctx context.Context, req *cxpb.GetExpe return resp, nil } -// CreateExperiment creates an Experiment in the specified Environment. -func (c *ExperimentsClient) CreateExperiment(ctx context.Context, req *cxpb.CreateExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { +func (c *experimentsGRPCClient) CreateExperiment(ctx context.Context, req *cxpb.CreateExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -291,7 +376,7 @@ func (c *ExperimentsClient) CreateExperiment(ctx context.Context, req *cxpb.Crea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateExperiment[0:len(c.CallOptions.CreateExperiment):len(c.CallOptions.CreateExperiment)], opts...) + opts = append((*c.CallOptions).CreateExperiment[0:len((*c.CallOptions).CreateExperiment):len((*c.CallOptions).CreateExperiment)], opts...) var resp *cxpb.Experiment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -304,8 +389,7 @@ func (c *ExperimentsClient) CreateExperiment(ctx context.Context, req *cxpb.Crea return resp, nil } -// UpdateExperiment updates the specified Experiment. -func (c *ExperimentsClient) UpdateExperiment(ctx context.Context, req *cxpb.UpdateExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { +func (c *experimentsGRPCClient) UpdateExperiment(ctx context.Context, req *cxpb.UpdateExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -313,7 +397,7 @@ func (c *ExperimentsClient) UpdateExperiment(ctx context.Context, req *cxpb.Upda } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "experiment.name", url.QueryEscape(req.GetExperiment().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateExperiment[0:len(c.CallOptions.UpdateExperiment):len(c.CallOptions.UpdateExperiment)], opts...) + opts = append((*c.CallOptions).UpdateExperiment[0:len((*c.CallOptions).UpdateExperiment):len((*c.CallOptions).UpdateExperiment)], opts...) var resp *cxpb.Experiment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -326,8 +410,7 @@ func (c *ExperimentsClient) UpdateExperiment(ctx context.Context, req *cxpb.Upda return resp, nil } -// DeleteExperiment deletes the specified Experiment. -func (c *ExperimentsClient) DeleteExperiment(ctx context.Context, req *cxpb.DeleteExperimentRequest, opts ...gax.CallOption) error { +func (c *experimentsGRPCClient) DeleteExperiment(ctx context.Context, req *cxpb.DeleteExperimentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -335,7 +418,7 @@ func (c *ExperimentsClient) DeleteExperiment(ctx context.Context, req *cxpb.Dele } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteExperiment[0:len(c.CallOptions.DeleteExperiment):len(c.CallOptions.DeleteExperiment)], opts...) + opts = append((*c.CallOptions).DeleteExperiment[0:len((*c.CallOptions).DeleteExperiment):len((*c.CallOptions).DeleteExperiment)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.experimentsClient.DeleteExperiment(ctx, req, settings.GRPC...) @@ -344,9 +427,7 @@ func (c *ExperimentsClient) DeleteExperiment(ctx context.Context, req *cxpb.Dele return err } -// StartExperiment starts the specified Experiment. This rpc only changes the state of -// experiment from PENDING to RUNNING. -func (c *ExperimentsClient) StartExperiment(ctx context.Context, req *cxpb.StartExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { +func (c *experimentsGRPCClient) StartExperiment(ctx context.Context, req *cxpb.StartExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -354,7 +435,7 @@ func (c *ExperimentsClient) StartExperiment(ctx context.Context, req *cxpb.Start } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.StartExperiment[0:len(c.CallOptions.StartExperiment):len(c.CallOptions.StartExperiment)], opts...) + opts = append((*c.CallOptions).StartExperiment[0:len((*c.CallOptions).StartExperiment):len((*c.CallOptions).StartExperiment)], opts...) var resp *cxpb.Experiment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -367,9 +448,7 @@ func (c *ExperimentsClient) StartExperiment(ctx context.Context, req *cxpb.Start return resp, nil } -// StopExperiment stops the specified Experiment. This rpc only changes the state of -// experiment from RUNNING to DONE. -func (c *ExperimentsClient) StopExperiment(ctx context.Context, req *cxpb.StopExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { +func (c *experimentsGRPCClient) StopExperiment(ctx context.Context, req *cxpb.StopExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -377,7 +456,7 @@ func (c *ExperimentsClient) StopExperiment(ctx context.Context, req *cxpb.StopEx } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.StopExperiment[0:len(c.CallOptions.StopExperiment):len(c.CallOptions.StopExperiment)], opts...) + opts = append((*c.CallOptions).StopExperiment[0:len((*c.CallOptions).StopExperiment):len((*c.CallOptions).StopExperiment)], opts...) var resp *cxpb.Experiment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/dialogflow/cx/apiv3/experiments_client_example_test.go b/dialogflow/cx/apiv3/experiments_client_example_test.go index bc8efccabbf8..879e0fb27d92 100644 --- a/dialogflow/cx/apiv3/experiments_client_example_test.go +++ b/dialogflow/cx/apiv3/experiments_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewExperimentsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleExperimentsClient_ListExperiments() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListExperimentsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleExperimentsClient_ListExperiments() { } func ExampleExperimentsClient_GetExperiment() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetExperimentRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleExperimentsClient_GetExperiment() { } func ExampleExperimentsClient_CreateExperiment() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateExperimentRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleExperimentsClient_CreateExperiment() { } func ExampleExperimentsClient_UpdateExperiment() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateExperimentRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleExperimentsClient_DeleteExperiment() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteExperimentRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleExperimentsClient_DeleteExperiment() { } func ExampleExperimentsClient_StartExperiment() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.StartExperimentRequest{ // TODO: Fill request struct fields. @@ -158,13 +155,12 @@ func ExampleExperimentsClient_StartExperiment() { } func ExampleExperimentsClient_StopExperiment() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.StopExperimentRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3/flows_client.go b/dialogflow/cx/apiv3/flows_client.go index 25c2f2a70d1a..015217b481a9 100644 --- a/dialogflow/cx/apiv3/flows_client.go +++ b/dialogflow/cx/apiv3/flows_client.go @@ -55,7 +55,7 @@ type FlowsCallOptions struct { ExportFlow []gax.CallOption } -func defaultFlowsClientOptions() []option.ClientOption { +func defaultFlowsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -182,37 +182,171 @@ func defaultFlowsCallOptions() *FlowsCallOptions { } } +// internalFlowsClient is an interface that defines the methods availaible from Dialogflow API. +type internalFlowsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateFlow(context.Context, *cxpb.CreateFlowRequest, ...gax.CallOption) (*cxpb.Flow, error) + DeleteFlow(context.Context, *cxpb.DeleteFlowRequest, ...gax.CallOption) error + ListFlows(context.Context, *cxpb.ListFlowsRequest, ...gax.CallOption) *FlowIterator + GetFlow(context.Context, *cxpb.GetFlowRequest, ...gax.CallOption) (*cxpb.Flow, error) + UpdateFlow(context.Context, *cxpb.UpdateFlowRequest, ...gax.CallOption) (*cxpb.Flow, error) + TrainFlow(context.Context, *cxpb.TrainFlowRequest, ...gax.CallOption) (*TrainFlowOperation, error) + TrainFlowOperation(name string) *TrainFlowOperation + ValidateFlow(context.Context, *cxpb.ValidateFlowRequest, ...gax.CallOption) (*cxpb.FlowValidationResult, error) + GetFlowValidationResult(context.Context, *cxpb.GetFlowValidationResultRequest, ...gax.CallOption) (*cxpb.FlowValidationResult, error) + ImportFlow(context.Context, *cxpb.ImportFlowRequest, ...gax.CallOption) (*ImportFlowOperation, error) + ImportFlowOperation(name string) *ImportFlowOperation + ExportFlow(context.Context, *cxpb.ExportFlowRequest, ...gax.CallOption) (*ExportFlowOperation, error) + ExportFlowOperation(name string) *ExportFlowOperation +} + // FlowsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Flows. type FlowsClient struct { + // The internal transport-dependent client. + internalClient internalFlowsClient + + // The call options for this service. + CallOptions *FlowsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *FlowsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *FlowsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *FlowsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateFlow creates a flow in the specified agent. +func (c *FlowsClient) CreateFlow(ctx context.Context, req *cxpb.CreateFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { + return c.internalClient.CreateFlow(ctx, req, opts...) +} + +// DeleteFlow deletes a specified flow. +func (c *FlowsClient) DeleteFlow(ctx context.Context, req *cxpb.DeleteFlowRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteFlow(ctx, req, opts...) +} + +// ListFlows returns the list of all flows in the specified agent. +func (c *FlowsClient) ListFlows(ctx context.Context, req *cxpb.ListFlowsRequest, opts ...gax.CallOption) *FlowIterator { + return c.internalClient.ListFlows(ctx, req, opts...) +} + +// GetFlow retrieves the specified flow. +func (c *FlowsClient) GetFlow(ctx context.Context, req *cxpb.GetFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { + return c.internalClient.GetFlow(ctx, req, opts...) +} + +// UpdateFlow updates the specified flow. +func (c *FlowsClient) UpdateFlow(ctx context.Context, req *cxpb.UpdateFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { + return c.internalClient.UpdateFlow(ctx, req, opts...) +} + +// TrainFlow trains the specified flow. Note that only the flow in ‘draft’ environment +// is trained. +func (c *FlowsClient) TrainFlow(ctx context.Context, req *cxpb.TrainFlowRequest, opts ...gax.CallOption) (*TrainFlowOperation, error) { + return c.internalClient.TrainFlow(ctx, req, opts...) +} + +// TrainFlowOperation returns a new TrainFlowOperation from a given name. +// The name must be that of a previously created TrainFlowOperation, possibly from a different process. +func (c *FlowsClient) TrainFlowOperation(name string) *TrainFlowOperation { + return c.internalClient.TrainFlowOperation(name) +} + +// ValidateFlow validates the specified flow and creates or updates validation results. +// Please call this API after the training is completed to get the complete +// validation results. +func (c *FlowsClient) ValidateFlow(ctx context.Context, req *cxpb.ValidateFlowRequest, opts ...gax.CallOption) (*cxpb.FlowValidationResult, error) { + return c.internalClient.ValidateFlow(ctx, req, opts...) +} + +// GetFlowValidationResult gets the latest flow validation result. Flow validation is performed +// when ValidateFlow is called. +func (c *FlowsClient) GetFlowValidationResult(ctx context.Context, req *cxpb.GetFlowValidationResultRequest, opts ...gax.CallOption) (*cxpb.FlowValidationResult, error) { + return c.internalClient.GetFlowValidationResult(ctx, req, opts...) +} + +// ImportFlow imports the specified flow to the specified agent from a binary file. +func (c *FlowsClient) ImportFlow(ctx context.Context, req *cxpb.ImportFlowRequest, opts ...gax.CallOption) (*ImportFlowOperation, error) { + return c.internalClient.ImportFlow(ctx, req, opts...) +} + +// ImportFlowOperation returns a new ImportFlowOperation from a given name. +// The name must be that of a previously created ImportFlowOperation, possibly from a different process. +func (c *FlowsClient) ImportFlowOperation(name string) *ImportFlowOperation { + return c.internalClient.ImportFlowOperation(name) +} + +// ExportFlow exports the specified flow to a binary file. +// +// Note that resources (e.g. intents, entities, webhooks) that the flow +// references will also be exported. +func (c *FlowsClient) ExportFlow(ctx context.Context, req *cxpb.ExportFlowRequest, opts ...gax.CallOption) (*ExportFlowOperation, error) { + return c.internalClient.ExportFlow(ctx, req, opts...) +} + +// ExportFlowOperation returns a new ExportFlowOperation from a given name. +// The name must be that of a previously created ExportFlowOperation, possibly from a different process. +func (c *FlowsClient) ExportFlowOperation(name string) *ExportFlowOperation { + return c.internalClient.ExportFlowOperation(name) +} + +// flowsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type flowsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing FlowsClient + CallOptions **FlowsCallOptions + // The gRPC API client. flowsClient cxpb.FlowsClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *FlowsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewFlowsClient creates a new flows client. +// NewFlowsClient creates a new flows client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Flows. func NewFlowsClient(ctx context.Context, opts ...option.ClientOption) (*FlowsClient, error) { - clientOpts := defaultFlowsClientOptions() - + clientOpts := defaultFlowsGRPCClientOptions() if newFlowsClientHook != nil { hookOpts, err := newFlowsClientHook(ctx, clientHookParams{}) if err != nil { @@ -230,16 +364,19 @@ func NewFlowsClient(ctx context.Context, opts ...option.ClientOption) (*FlowsCli if err != nil { return nil, err } - c := &FlowsClient{ + client := FlowsClient{CallOptions: defaultFlowsCallOptions()} + + c := &flowsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultFlowsCallOptions(), - - flowsClient: cxpb.NewFlowsClient(connPool), + flowsClient: cxpb.NewFlowsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -249,33 +386,33 @@ func NewFlowsClient(ctx context.Context, opts ...option.ClientOption) (*FlowsCli // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *FlowsClient) Connection() *grpc.ClientConn { +func (c *flowsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *FlowsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *FlowsClient) setGoogleClientInfo(keyval ...string) { +func (c *flowsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateFlow creates a flow in the specified agent. -func (c *FlowsClient) CreateFlow(ctx context.Context, req *cxpb.CreateFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *flowsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *flowsGRPCClient) CreateFlow(ctx context.Context, req *cxpb.CreateFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -283,7 +420,7 @@ func (c *FlowsClient) CreateFlow(ctx context.Context, req *cxpb.CreateFlowReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateFlow[0:len(c.CallOptions.CreateFlow):len(c.CallOptions.CreateFlow)], opts...) + opts = append((*c.CallOptions).CreateFlow[0:len((*c.CallOptions).CreateFlow):len((*c.CallOptions).CreateFlow)], opts...) var resp *cxpb.Flow err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -296,8 +433,7 @@ func (c *FlowsClient) CreateFlow(ctx context.Context, req *cxpb.CreateFlowReques return resp, nil } -// DeleteFlow deletes a specified flow. -func (c *FlowsClient) DeleteFlow(ctx context.Context, req *cxpb.DeleteFlowRequest, opts ...gax.CallOption) error { +func (c *flowsGRPCClient) DeleteFlow(ctx context.Context, req *cxpb.DeleteFlowRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -305,7 +441,7 @@ func (c *FlowsClient) DeleteFlow(ctx context.Context, req *cxpb.DeleteFlowReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteFlow[0:len(c.CallOptions.DeleteFlow):len(c.CallOptions.DeleteFlow)], opts...) + opts = append((*c.CallOptions).DeleteFlow[0:len((*c.CallOptions).DeleteFlow):len((*c.CallOptions).DeleteFlow)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.flowsClient.DeleteFlow(ctx, req, settings.GRPC...) @@ -314,11 +450,10 @@ func (c *FlowsClient) DeleteFlow(ctx context.Context, req *cxpb.DeleteFlowReques return err } -// ListFlows returns the list of all flows in the specified agent. -func (c *FlowsClient) ListFlows(ctx context.Context, req *cxpb.ListFlowsRequest, opts ...gax.CallOption) *FlowIterator { +func (c *flowsGRPCClient) ListFlows(ctx context.Context, req *cxpb.ListFlowsRequest, opts ...gax.CallOption) *FlowIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListFlows[0:len(c.CallOptions.ListFlows):len(c.CallOptions.ListFlows)], opts...) + opts = append((*c.CallOptions).ListFlows[0:len((*c.CallOptions).ListFlows):len((*c.CallOptions).ListFlows)], opts...) it := &FlowIterator{} req = proto.Clone(req).(*cxpb.ListFlowsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Flow, string, error) { @@ -355,8 +490,7 @@ func (c *FlowsClient) ListFlows(ctx context.Context, req *cxpb.ListFlowsRequest, return it } -// GetFlow retrieves the specified flow. -func (c *FlowsClient) GetFlow(ctx context.Context, req *cxpb.GetFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { +func (c *flowsGRPCClient) GetFlow(ctx context.Context, req *cxpb.GetFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -364,7 +498,7 @@ func (c *FlowsClient) GetFlow(ctx context.Context, req *cxpb.GetFlowRequest, opt } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetFlow[0:len(c.CallOptions.GetFlow):len(c.CallOptions.GetFlow)], opts...) + opts = append((*c.CallOptions).GetFlow[0:len((*c.CallOptions).GetFlow):len((*c.CallOptions).GetFlow)], opts...) var resp *cxpb.Flow err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -377,8 +511,7 @@ func (c *FlowsClient) GetFlow(ctx context.Context, req *cxpb.GetFlowRequest, opt return resp, nil } -// UpdateFlow updates the specified flow. -func (c *FlowsClient) UpdateFlow(ctx context.Context, req *cxpb.UpdateFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { +func (c *flowsGRPCClient) UpdateFlow(ctx context.Context, req *cxpb.UpdateFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -386,7 +519,7 @@ func (c *FlowsClient) UpdateFlow(ctx context.Context, req *cxpb.UpdateFlowReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "flow.name", url.QueryEscape(req.GetFlow().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateFlow[0:len(c.CallOptions.UpdateFlow):len(c.CallOptions.UpdateFlow)], opts...) + opts = append((*c.CallOptions).UpdateFlow[0:len((*c.CallOptions).UpdateFlow):len((*c.CallOptions).UpdateFlow)], opts...) var resp *cxpb.Flow err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -399,9 +532,7 @@ func (c *FlowsClient) UpdateFlow(ctx context.Context, req *cxpb.UpdateFlowReques return resp, nil } -// TrainFlow trains the specified flow. Note that only the flow in ‘draft’ environment -// is trained. -func (c *FlowsClient) TrainFlow(ctx context.Context, req *cxpb.TrainFlowRequest, opts ...gax.CallOption) (*TrainFlowOperation, error) { +func (c *flowsGRPCClient) TrainFlow(ctx context.Context, req *cxpb.TrainFlowRequest, opts ...gax.CallOption) (*TrainFlowOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -409,7 +540,7 @@ func (c *FlowsClient) TrainFlow(ctx context.Context, req *cxpb.TrainFlowRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TrainFlow[0:len(c.CallOptions.TrainFlow):len(c.CallOptions.TrainFlow)], opts...) + opts = append((*c.CallOptions).TrainFlow[0:len((*c.CallOptions).TrainFlow):len((*c.CallOptions).TrainFlow)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -420,14 +551,11 @@ func (c *FlowsClient) TrainFlow(ctx context.Context, req *cxpb.TrainFlowRequest, return nil, err } return &TrainFlowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ValidateFlow validates the specified flow and creates or updates validation results. -// Please call this API after the training is completed to get the complete -// validation results. -func (c *FlowsClient) ValidateFlow(ctx context.Context, req *cxpb.ValidateFlowRequest, opts ...gax.CallOption) (*cxpb.FlowValidationResult, error) { +func (c *flowsGRPCClient) ValidateFlow(ctx context.Context, req *cxpb.ValidateFlowRequest, opts ...gax.CallOption) (*cxpb.FlowValidationResult, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -435,7 +563,7 @@ func (c *FlowsClient) ValidateFlow(ctx context.Context, req *cxpb.ValidateFlowRe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ValidateFlow[0:len(c.CallOptions.ValidateFlow):len(c.CallOptions.ValidateFlow)], opts...) + opts = append((*c.CallOptions).ValidateFlow[0:len((*c.CallOptions).ValidateFlow):len((*c.CallOptions).ValidateFlow)], opts...) var resp *cxpb.FlowValidationResult err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -448,9 +576,7 @@ func (c *FlowsClient) ValidateFlow(ctx context.Context, req *cxpb.ValidateFlowRe return resp, nil } -// GetFlowValidationResult gets the latest flow validation result. Flow validation is performed -// when ValidateFlow is called. -func (c *FlowsClient) GetFlowValidationResult(ctx context.Context, req *cxpb.GetFlowValidationResultRequest, opts ...gax.CallOption) (*cxpb.FlowValidationResult, error) { +func (c *flowsGRPCClient) GetFlowValidationResult(ctx context.Context, req *cxpb.GetFlowValidationResultRequest, opts ...gax.CallOption) (*cxpb.FlowValidationResult, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -458,7 +584,7 @@ func (c *FlowsClient) GetFlowValidationResult(ctx context.Context, req *cxpb.Get } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetFlowValidationResult[0:len(c.CallOptions.GetFlowValidationResult):len(c.CallOptions.GetFlowValidationResult)], opts...) + opts = append((*c.CallOptions).GetFlowValidationResult[0:len((*c.CallOptions).GetFlowValidationResult):len((*c.CallOptions).GetFlowValidationResult)], opts...) var resp *cxpb.FlowValidationResult err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -471,8 +597,7 @@ func (c *FlowsClient) GetFlowValidationResult(ctx context.Context, req *cxpb.Get return resp, nil } -// ImportFlow imports the specified flow to the specified agent from a binary file. -func (c *FlowsClient) ImportFlow(ctx context.Context, req *cxpb.ImportFlowRequest, opts ...gax.CallOption) (*ImportFlowOperation, error) { +func (c *flowsGRPCClient) ImportFlow(ctx context.Context, req *cxpb.ImportFlowRequest, opts ...gax.CallOption) (*ImportFlowOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -480,7 +605,7 @@ func (c *FlowsClient) ImportFlow(ctx context.Context, req *cxpb.ImportFlowReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportFlow[0:len(c.CallOptions.ImportFlow):len(c.CallOptions.ImportFlow)], opts...) + opts = append((*c.CallOptions).ImportFlow[0:len((*c.CallOptions).ImportFlow):len((*c.CallOptions).ImportFlow)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -491,15 +616,11 @@ func (c *FlowsClient) ImportFlow(ctx context.Context, req *cxpb.ImportFlowReques return nil, err } return &ImportFlowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ExportFlow exports the specified flow to a binary file. -// -// Note that resources (e.g. intents, entities, webhooks) that the flow -// references will also be exported. -func (c *FlowsClient) ExportFlow(ctx context.Context, req *cxpb.ExportFlowRequest, opts ...gax.CallOption) (*ExportFlowOperation, error) { +func (c *flowsGRPCClient) ExportFlow(ctx context.Context, req *cxpb.ExportFlowRequest, opts ...gax.CallOption) (*ExportFlowOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -507,7 +628,7 @@ func (c *FlowsClient) ExportFlow(ctx context.Context, req *cxpb.ExportFlowReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportFlow[0:len(c.CallOptions.ExportFlow):len(c.CallOptions.ExportFlow)], opts...) + opts = append((*c.CallOptions).ExportFlow[0:len((*c.CallOptions).ExportFlow):len((*c.CallOptions).ExportFlow)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -518,7 +639,7 @@ func (c *FlowsClient) ExportFlow(ctx context.Context, req *cxpb.ExportFlowReques return nil, err } return &ExportFlowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -529,9 +650,9 @@ type ExportFlowOperation struct { // ExportFlowOperation returns a new ExportFlowOperation from a given name. // The name must be that of a previously created ExportFlowOperation, possibly from a different process. -func (c *FlowsClient) ExportFlowOperation(name string) *ExportFlowOperation { +func (c *flowsGRPCClient) ExportFlowOperation(name string) *ExportFlowOperation { return &ExportFlowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -598,9 +719,9 @@ type ImportFlowOperation struct { // ImportFlowOperation returns a new ImportFlowOperation from a given name. // The name must be that of a previously created ImportFlowOperation, possibly from a different process. -func (c *FlowsClient) ImportFlowOperation(name string) *ImportFlowOperation { +func (c *flowsGRPCClient) ImportFlowOperation(name string) *ImportFlowOperation { return &ImportFlowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -667,9 +788,9 @@ type TrainFlowOperation struct { // TrainFlowOperation returns a new TrainFlowOperation from a given name. // The name must be that of a previously created TrainFlowOperation, possibly from a different process. -func (c *FlowsClient) TrainFlowOperation(name string) *TrainFlowOperation { +func (c *flowsGRPCClient) TrainFlowOperation(name string) *TrainFlowOperation { return &TrainFlowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dialogflow/cx/apiv3/flows_client_example_test.go b/dialogflow/cx/apiv3/flows_client_example_test.go index fae9e916a7bd..539539a1bc6e 100644 --- a/dialogflow/cx/apiv3/flows_client_example_test.go +++ b/dialogflow/cx/apiv3/flows_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewFlowsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleFlowsClient_CreateFlow() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateFlowRequest{ // TODO: Fill request struct fields. @@ -60,6 +61,7 @@ func ExampleFlowsClient_DeleteFlow() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteFlowRequest{ // TODO: Fill request struct fields. @@ -71,14 +73,12 @@ func ExampleFlowsClient_DeleteFlow() { } func ExampleFlowsClient_ListFlows() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListFlowsRequest{ // TODO: Fill request struct fields. @@ -98,13 +98,12 @@ func ExampleFlowsClient_ListFlows() { } func ExampleFlowsClient_GetFlow() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetFlowRequest{ // TODO: Fill request struct fields. @@ -118,13 +117,12 @@ func ExampleFlowsClient_GetFlow() { } func ExampleFlowsClient_UpdateFlow() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateFlowRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleFlowsClient_UpdateFlow() { } func ExampleFlowsClient_TrainFlow() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.TrainFlowRequest{ // TODO: Fill request struct fields. @@ -161,13 +158,12 @@ func ExampleFlowsClient_TrainFlow() { } func ExampleFlowsClient_ValidateFlow() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ValidateFlowRequest{ // TODO: Fill request struct fields. @@ -181,13 +177,12 @@ func ExampleFlowsClient_ValidateFlow() { } func ExampleFlowsClient_GetFlowValidationResult() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetFlowValidationResultRequest{ // TODO: Fill request struct fields. @@ -201,13 +196,12 @@ func ExampleFlowsClient_GetFlowValidationResult() { } func ExampleFlowsClient_ImportFlow() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ImportFlowRequest{ // TODO: Fill request struct fields. @@ -226,13 +220,12 @@ func ExampleFlowsClient_ImportFlow() { } func ExampleFlowsClient_ExportFlow() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ExportFlowRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3/intents_client.go b/dialogflow/cx/apiv3/intents_client.go index 10774e861f71..6bd879cabc14 100644 --- a/dialogflow/cx/apiv3/intents_client.go +++ b/dialogflow/cx/apiv3/intents_client.go @@ -46,7 +46,7 @@ type IntentsCallOptions struct { DeleteIntent []gax.CallOption } -func defaultIntentsClientOptions() []option.ClientOption { +func defaultIntentsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,103 @@ func defaultIntentsCallOptions() *IntentsCallOptions { } } +// internalIntentsClient is an interface that defines the methods availaible from Dialogflow API. +type internalIntentsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListIntents(context.Context, *cxpb.ListIntentsRequest, ...gax.CallOption) *IntentIterator + GetIntent(context.Context, *cxpb.GetIntentRequest, ...gax.CallOption) (*cxpb.Intent, error) + CreateIntent(context.Context, *cxpb.CreateIntentRequest, ...gax.CallOption) (*cxpb.Intent, error) + UpdateIntent(context.Context, *cxpb.UpdateIntentRequest, ...gax.CallOption) (*cxpb.Intent, error) + DeleteIntent(context.Context, *cxpb.DeleteIntentRequest, ...gax.CallOption) error +} + // IntentsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Intents. type IntentsClient struct { + // The internal transport-dependent client. + internalClient internalIntentsClient + + // The call options for this service. + CallOptions *IntentsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *IntentsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *IntentsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *IntentsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListIntents returns the list of all intents in the specified agent. +func (c *IntentsClient) ListIntents(ctx context.Context, req *cxpb.ListIntentsRequest, opts ...gax.CallOption) *IntentIterator { + return c.internalClient.ListIntents(ctx, req, opts...) +} + +// GetIntent retrieves the specified intent. +func (c *IntentsClient) GetIntent(ctx context.Context, req *cxpb.GetIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { + return c.internalClient.GetIntent(ctx, req, opts...) +} + +// CreateIntent creates an intent in the specified agent. +func (c *IntentsClient) CreateIntent(ctx context.Context, req *cxpb.CreateIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { + return c.internalClient.CreateIntent(ctx, req, opts...) +} + +// UpdateIntent updates the specified intent. +func (c *IntentsClient) UpdateIntent(ctx context.Context, req *cxpb.UpdateIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { + return c.internalClient.UpdateIntent(ctx, req, opts...) +} + +// DeleteIntent deletes the specified intent. +func (c *IntentsClient) DeleteIntent(ctx context.Context, req *cxpb.DeleteIntentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteIntent(ctx, req, opts...) +} + +// intentsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type intentsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing IntentsClient + CallOptions **IntentsCallOptions + // The gRPC API client. intentsClient cxpb.IntentsClient - // The call options for this service. - CallOptions *IntentsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewIntentsClient creates a new intents client. +// NewIntentsClient creates a new intents client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Intents. func NewIntentsClient(ctx context.Context, opts ...option.ClientOption) (*IntentsClient, error) { - clientOpts := defaultIntentsClientOptions() - + clientOpts := defaultIntentsGRPCClientOptions() if newIntentsClientHook != nil { hookOpts, err := newIntentsClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,45 +232,47 @@ func NewIntentsClient(ctx context.Context, opts ...option.ClientOption) (*Intent if err != nil { return nil, err } - c := &IntentsClient{ + client := IntentsClient{CallOptions: defaultIntentsCallOptions()} + + c := &intentsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultIntentsCallOptions(), - - intentsClient: cxpb.NewIntentsClient(connPool), + intentsClient: cxpb.NewIntentsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *IntentsClient) Connection() *grpc.ClientConn { +func (c *intentsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *IntentsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *IntentsClient) setGoogleClientInfo(keyval ...string) { +func (c *intentsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListIntents returns the list of all intents in the specified agent. -func (c *IntentsClient) ListIntents(ctx context.Context, req *cxpb.ListIntentsRequest, opts ...gax.CallOption) *IntentIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *intentsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *intentsGRPCClient) ListIntents(ctx context.Context, req *cxpb.ListIntentsRequest, opts ...gax.CallOption) *IntentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListIntents[0:len(c.CallOptions.ListIntents):len(c.CallOptions.ListIntents)], opts...) + opts = append((*c.CallOptions).ListIntents[0:len((*c.CallOptions).ListIntents):len((*c.CallOptions).ListIntents)], opts...) it := &IntentIterator{} req = proto.Clone(req).(*cxpb.ListIntentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Intent, string, error) { @@ -236,8 +309,7 @@ func (c *IntentsClient) ListIntents(ctx context.Context, req *cxpb.ListIntentsRe return it } -// GetIntent retrieves the specified intent. -func (c *IntentsClient) GetIntent(ctx context.Context, req *cxpb.GetIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { +func (c *intentsGRPCClient) GetIntent(ctx context.Context, req *cxpb.GetIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -245,7 +317,7 @@ func (c *IntentsClient) GetIntent(ctx context.Context, req *cxpb.GetIntentReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIntent[0:len(c.CallOptions.GetIntent):len(c.CallOptions.GetIntent)], opts...) + opts = append((*c.CallOptions).GetIntent[0:len((*c.CallOptions).GetIntent):len((*c.CallOptions).GetIntent)], opts...) var resp *cxpb.Intent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -258,8 +330,7 @@ func (c *IntentsClient) GetIntent(ctx context.Context, req *cxpb.GetIntentReques return resp, nil } -// CreateIntent creates an intent in the specified agent. -func (c *IntentsClient) CreateIntent(ctx context.Context, req *cxpb.CreateIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { +func (c *intentsGRPCClient) CreateIntent(ctx context.Context, req *cxpb.CreateIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -267,7 +338,7 @@ func (c *IntentsClient) CreateIntent(ctx context.Context, req *cxpb.CreateIntent } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateIntent[0:len(c.CallOptions.CreateIntent):len(c.CallOptions.CreateIntent)], opts...) + opts = append((*c.CallOptions).CreateIntent[0:len((*c.CallOptions).CreateIntent):len((*c.CallOptions).CreateIntent)], opts...) var resp *cxpb.Intent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -280,8 +351,7 @@ func (c *IntentsClient) CreateIntent(ctx context.Context, req *cxpb.CreateIntent return resp, nil } -// UpdateIntent updates the specified intent. -func (c *IntentsClient) UpdateIntent(ctx context.Context, req *cxpb.UpdateIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { +func (c *intentsGRPCClient) UpdateIntent(ctx context.Context, req *cxpb.UpdateIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -289,7 +359,7 @@ func (c *IntentsClient) UpdateIntent(ctx context.Context, req *cxpb.UpdateIntent } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "intent.name", url.QueryEscape(req.GetIntent().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateIntent[0:len(c.CallOptions.UpdateIntent):len(c.CallOptions.UpdateIntent)], opts...) + opts = append((*c.CallOptions).UpdateIntent[0:len((*c.CallOptions).UpdateIntent):len((*c.CallOptions).UpdateIntent)], opts...) var resp *cxpb.Intent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -302,8 +372,7 @@ func (c *IntentsClient) UpdateIntent(ctx context.Context, req *cxpb.UpdateIntent return resp, nil } -// DeleteIntent deletes the specified intent. -func (c *IntentsClient) DeleteIntent(ctx context.Context, req *cxpb.DeleteIntentRequest, opts ...gax.CallOption) error { +func (c *intentsGRPCClient) DeleteIntent(ctx context.Context, req *cxpb.DeleteIntentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -311,7 +380,7 @@ func (c *IntentsClient) DeleteIntent(ctx context.Context, req *cxpb.DeleteIntent } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteIntent[0:len(c.CallOptions.DeleteIntent):len(c.CallOptions.DeleteIntent)], opts...) + opts = append((*c.CallOptions).DeleteIntent[0:len((*c.CallOptions).DeleteIntent):len((*c.CallOptions).DeleteIntent)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.intentsClient.DeleteIntent(ctx, req, settings.GRPC...) diff --git a/dialogflow/cx/apiv3/intents_client_example_test.go b/dialogflow/cx/apiv3/intents_client_example_test.go index 804ebd26f2b8..1e00dbfb84c1 100644 --- a/dialogflow/cx/apiv3/intents_client_example_test.go +++ b/dialogflow/cx/apiv3/intents_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewIntentsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleIntentsClient_ListIntents() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListIntentsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleIntentsClient_ListIntents() { } func ExampleIntentsClient_GetIntent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetIntentRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleIntentsClient_GetIntent() { } func ExampleIntentsClient_CreateIntent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateIntentRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleIntentsClient_CreateIntent() { } func ExampleIntentsClient_UpdateIntent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateIntentRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleIntentsClient_DeleteIntent() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteIntentRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3/pages_client.go b/dialogflow/cx/apiv3/pages_client.go index 8df429c54b33..949ce6a42d6d 100644 --- a/dialogflow/cx/apiv3/pages_client.go +++ b/dialogflow/cx/apiv3/pages_client.go @@ -46,7 +46,7 @@ type PagesCallOptions struct { DeletePage []gax.CallOption } -func defaultPagesClientOptions() []option.ClientOption { +func defaultPagesGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,103 @@ func defaultPagesCallOptions() *PagesCallOptions { } } +// internalPagesClient is an interface that defines the methods availaible from Dialogflow API. +type internalPagesClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListPages(context.Context, *cxpb.ListPagesRequest, ...gax.CallOption) *PageIterator + GetPage(context.Context, *cxpb.GetPageRequest, ...gax.CallOption) (*cxpb.Page, error) + CreatePage(context.Context, *cxpb.CreatePageRequest, ...gax.CallOption) (*cxpb.Page, error) + UpdatePage(context.Context, *cxpb.UpdatePageRequest, ...gax.CallOption) (*cxpb.Page, error) + DeletePage(context.Context, *cxpb.DeletePageRequest, ...gax.CallOption) error +} + // PagesClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing [Pages][google.cloud.dialogflow.cx.v3.Page (at http://google.cloud.dialogflow.cx.v3.Page)]. type PagesClient struct { + // The internal transport-dependent client. + internalClient internalPagesClient + + // The call options for this service. + CallOptions *PagesCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *PagesClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *PagesClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *PagesClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListPages returns the list of all pages in the specified flow. +func (c *PagesClient) ListPages(ctx context.Context, req *cxpb.ListPagesRequest, opts ...gax.CallOption) *PageIterator { + return c.internalClient.ListPages(ctx, req, opts...) +} + +// GetPage retrieves the specified page. +func (c *PagesClient) GetPage(ctx context.Context, req *cxpb.GetPageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { + return c.internalClient.GetPage(ctx, req, opts...) +} + +// CreatePage creates a page in the specified flow. +func (c *PagesClient) CreatePage(ctx context.Context, req *cxpb.CreatePageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { + return c.internalClient.CreatePage(ctx, req, opts...) +} + +// UpdatePage updates the specified page. +func (c *PagesClient) UpdatePage(ctx context.Context, req *cxpb.UpdatePageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { + return c.internalClient.UpdatePage(ctx, req, opts...) +} + +// DeletePage deletes the specified page. +func (c *PagesClient) DeletePage(ctx context.Context, req *cxpb.DeletePageRequest, opts ...gax.CallOption) error { + return c.internalClient.DeletePage(ctx, req, opts...) +} + +// pagesGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type pagesGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing PagesClient + CallOptions **PagesCallOptions + // The gRPC API client. pagesClient cxpb.PagesClient - // The call options for this service. - CallOptions *PagesCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewPagesClient creates a new pages client. +// NewPagesClient creates a new pages client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing [Pages][google.cloud.dialogflow.cx.v3.Page (at http://google.cloud.dialogflow.cx.v3.Page)]. func NewPagesClient(ctx context.Context, opts ...option.ClientOption) (*PagesClient, error) { - clientOpts := defaultPagesClientOptions() - + clientOpts := defaultPagesGRPCClientOptions() if newPagesClientHook != nil { hookOpts, err := newPagesClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,45 +232,47 @@ func NewPagesClient(ctx context.Context, opts ...option.ClientOption) (*PagesCli if err != nil { return nil, err } - c := &PagesClient{ + client := PagesClient{CallOptions: defaultPagesCallOptions()} + + c := &pagesGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultPagesCallOptions(), - - pagesClient: cxpb.NewPagesClient(connPool), + pagesClient: cxpb.NewPagesClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *PagesClient) Connection() *grpc.ClientConn { +func (c *pagesGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *PagesClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *PagesClient) setGoogleClientInfo(keyval ...string) { +func (c *pagesGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListPages returns the list of all pages in the specified flow. -func (c *PagesClient) ListPages(ctx context.Context, req *cxpb.ListPagesRequest, opts ...gax.CallOption) *PageIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *pagesGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *pagesGRPCClient) ListPages(ctx context.Context, req *cxpb.ListPagesRequest, opts ...gax.CallOption) *PageIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListPages[0:len(c.CallOptions.ListPages):len(c.CallOptions.ListPages)], opts...) + opts = append((*c.CallOptions).ListPages[0:len((*c.CallOptions).ListPages):len((*c.CallOptions).ListPages)], opts...) it := &PageIterator{} req = proto.Clone(req).(*cxpb.ListPagesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Page, string, error) { @@ -236,8 +309,7 @@ func (c *PagesClient) ListPages(ctx context.Context, req *cxpb.ListPagesRequest, return it } -// GetPage retrieves the specified page. -func (c *PagesClient) GetPage(ctx context.Context, req *cxpb.GetPageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { +func (c *pagesGRPCClient) GetPage(ctx context.Context, req *cxpb.GetPageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -245,7 +317,7 @@ func (c *PagesClient) GetPage(ctx context.Context, req *cxpb.GetPageRequest, opt } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetPage[0:len(c.CallOptions.GetPage):len(c.CallOptions.GetPage)], opts...) + opts = append((*c.CallOptions).GetPage[0:len((*c.CallOptions).GetPage):len((*c.CallOptions).GetPage)], opts...) var resp *cxpb.Page err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -258,8 +330,7 @@ func (c *PagesClient) GetPage(ctx context.Context, req *cxpb.GetPageRequest, opt return resp, nil } -// CreatePage creates a page in the specified flow. -func (c *PagesClient) CreatePage(ctx context.Context, req *cxpb.CreatePageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { +func (c *pagesGRPCClient) CreatePage(ctx context.Context, req *cxpb.CreatePageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -267,7 +338,7 @@ func (c *PagesClient) CreatePage(ctx context.Context, req *cxpb.CreatePageReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreatePage[0:len(c.CallOptions.CreatePage):len(c.CallOptions.CreatePage)], opts...) + opts = append((*c.CallOptions).CreatePage[0:len((*c.CallOptions).CreatePage):len((*c.CallOptions).CreatePage)], opts...) var resp *cxpb.Page err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -280,8 +351,7 @@ func (c *PagesClient) CreatePage(ctx context.Context, req *cxpb.CreatePageReques return resp, nil } -// UpdatePage updates the specified page. -func (c *PagesClient) UpdatePage(ctx context.Context, req *cxpb.UpdatePageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { +func (c *pagesGRPCClient) UpdatePage(ctx context.Context, req *cxpb.UpdatePageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -289,7 +359,7 @@ func (c *PagesClient) UpdatePage(ctx context.Context, req *cxpb.UpdatePageReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "page.name", url.QueryEscape(req.GetPage().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdatePage[0:len(c.CallOptions.UpdatePage):len(c.CallOptions.UpdatePage)], opts...) + opts = append((*c.CallOptions).UpdatePage[0:len((*c.CallOptions).UpdatePage):len((*c.CallOptions).UpdatePage)], opts...) var resp *cxpb.Page err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -302,8 +372,7 @@ func (c *PagesClient) UpdatePage(ctx context.Context, req *cxpb.UpdatePageReques return resp, nil } -// DeletePage deletes the specified page. -func (c *PagesClient) DeletePage(ctx context.Context, req *cxpb.DeletePageRequest, opts ...gax.CallOption) error { +func (c *pagesGRPCClient) DeletePage(ctx context.Context, req *cxpb.DeletePageRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -311,7 +380,7 @@ func (c *PagesClient) DeletePage(ctx context.Context, req *cxpb.DeletePageReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeletePage[0:len(c.CallOptions.DeletePage):len(c.CallOptions.DeletePage)], opts...) + opts = append((*c.CallOptions).DeletePage[0:len((*c.CallOptions).DeletePage):len((*c.CallOptions).DeletePage)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.pagesClient.DeletePage(ctx, req, settings.GRPC...) diff --git a/dialogflow/cx/apiv3/pages_client_example_test.go b/dialogflow/cx/apiv3/pages_client_example_test.go index 51f8840a4ac9..d0323416f62e 100644 --- a/dialogflow/cx/apiv3/pages_client_example_test.go +++ b/dialogflow/cx/apiv3/pages_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewPagesClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExamplePagesClient_ListPages() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewPagesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListPagesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExamplePagesClient_ListPages() { } func ExamplePagesClient_GetPage() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewPagesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetPageRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExamplePagesClient_GetPage() { } func ExamplePagesClient_CreatePage() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewPagesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreatePageRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExamplePagesClient_CreatePage() { } func ExamplePagesClient_UpdatePage() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewPagesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdatePageRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExamplePagesClient_DeletePage() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeletePageRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3/security_settings_client.go b/dialogflow/cx/apiv3/security_settings_client.go index e548a1c4e5e8..5e638897d46f 100644 --- a/dialogflow/cx/apiv3/security_settings_client.go +++ b/dialogflow/cx/apiv3/security_settings_client.go @@ -46,7 +46,7 @@ type SecuritySettingsCallOptions struct { DeleteSecuritySettings []gax.CallOption } -func defaultSecuritySettingsClientOptions() []option.ClientOption { +func defaultSecuritySettingsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,104 @@ func defaultSecuritySettingsCallOptions() *SecuritySettingsCallOptions { } } +// internalSecuritySettingsClient is an interface that defines the methods availaible from Dialogflow API. +type internalSecuritySettingsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateSecuritySettings(context.Context, *cxpb.CreateSecuritySettingsRequest, ...gax.CallOption) (*cxpb.SecuritySettings, error) + GetSecuritySettings(context.Context, *cxpb.GetSecuritySettingsRequest, ...gax.CallOption) (*cxpb.SecuritySettings, error) + UpdateSecuritySettings(context.Context, *cxpb.UpdateSecuritySettingsRequest, ...gax.CallOption) (*cxpb.SecuritySettings, error) + ListSecuritySettings(context.Context, *cxpb.ListSecuritySettingsRequest, ...gax.CallOption) *SecuritySettingsIterator + DeleteSecuritySettings(context.Context, *cxpb.DeleteSecuritySettingsRequest, ...gax.CallOption) error +} + // SecuritySettingsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing security settings for Dialogflow. type SecuritySettingsClient struct { + // The internal transport-dependent client. + internalClient internalSecuritySettingsClient + + // The call options for this service. + CallOptions *SecuritySettingsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *SecuritySettingsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *SecuritySettingsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *SecuritySettingsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateSecuritySettings create security settings in the specified location. +func (c *SecuritySettingsClient) CreateSecuritySettings(ctx context.Context, req *cxpb.CreateSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { + return c.internalClient.CreateSecuritySettings(ctx, req, opts...) +} + +// GetSecuritySettings retrieves the specified SecuritySettings. +// The returned settings may be stale by up to 1 minute. +func (c *SecuritySettingsClient) GetSecuritySettings(ctx context.Context, req *cxpb.GetSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { + return c.internalClient.GetSecuritySettings(ctx, req, opts...) +} + +// UpdateSecuritySettings updates the specified SecuritySettings. +func (c *SecuritySettingsClient) UpdateSecuritySettings(ctx context.Context, req *cxpb.UpdateSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { + return c.internalClient.UpdateSecuritySettings(ctx, req, opts...) +} + +// ListSecuritySettings returns the list of all security settings in the specified location. +func (c *SecuritySettingsClient) ListSecuritySettings(ctx context.Context, req *cxpb.ListSecuritySettingsRequest, opts ...gax.CallOption) *SecuritySettingsIterator { + return c.internalClient.ListSecuritySettings(ctx, req, opts...) +} + +// DeleteSecuritySettings deletes the specified SecuritySettings. +func (c *SecuritySettingsClient) DeleteSecuritySettings(ctx context.Context, req *cxpb.DeleteSecuritySettingsRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteSecuritySettings(ctx, req, opts...) +} + +// securitySettingsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type securitySettingsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing SecuritySettingsClient + CallOptions **SecuritySettingsCallOptions + // The gRPC API client. securitySettingsClient cxpb.SecuritySettingsServiceClient - // The call options for this service. - CallOptions *SecuritySettingsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewSecuritySettingsClient creates a new security settings service client. +// NewSecuritySettingsClient creates a new security settings service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing security settings for Dialogflow. func NewSecuritySettingsClient(ctx context.Context, opts ...option.ClientOption) (*SecuritySettingsClient, error) { - clientOpts := defaultSecuritySettingsClientOptions() - + clientOpts := defaultSecuritySettingsGRPCClientOptions() if newSecuritySettingsClientHook != nil { hookOpts, err := newSecuritySettingsClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,42 +233,44 @@ func NewSecuritySettingsClient(ctx context.Context, opts ...option.ClientOption) if err != nil { return nil, err } - c := &SecuritySettingsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultSecuritySettingsCallOptions(), + client := SecuritySettingsClient{CallOptions: defaultSecuritySettingsCallOptions()} + c := &securitySettingsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, securitySettingsClient: cxpb.NewSecuritySettingsServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *SecuritySettingsClient) Connection() *grpc.ClientConn { +func (c *securitySettingsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *SecuritySettingsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *SecuritySettingsClient) setGoogleClientInfo(keyval ...string) { +func (c *securitySettingsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateSecuritySettings create security settings in the specified location. -func (c *SecuritySettingsClient) CreateSecuritySettings(ctx context.Context, req *cxpb.CreateSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *securitySettingsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *securitySettingsGRPCClient) CreateSecuritySettings(ctx context.Context, req *cxpb.CreateSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -204,7 +278,7 @@ func (c *SecuritySettingsClient) CreateSecuritySettings(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSecuritySettings[0:len(c.CallOptions.CreateSecuritySettings):len(c.CallOptions.CreateSecuritySettings)], opts...) + opts = append((*c.CallOptions).CreateSecuritySettings[0:len((*c.CallOptions).CreateSecuritySettings):len((*c.CallOptions).CreateSecuritySettings)], opts...) var resp *cxpb.SecuritySettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -217,9 +291,7 @@ func (c *SecuritySettingsClient) CreateSecuritySettings(ctx context.Context, req return resp, nil } -// GetSecuritySettings retrieves the specified SecuritySettings. -// The returned settings may be stale by up to 1 minute. -func (c *SecuritySettingsClient) GetSecuritySettings(ctx context.Context, req *cxpb.GetSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { +func (c *securitySettingsGRPCClient) GetSecuritySettings(ctx context.Context, req *cxpb.GetSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -227,7 +299,7 @@ func (c *SecuritySettingsClient) GetSecuritySettings(ctx context.Context, req *c } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSecuritySettings[0:len(c.CallOptions.GetSecuritySettings):len(c.CallOptions.GetSecuritySettings)], opts...) + opts = append((*c.CallOptions).GetSecuritySettings[0:len((*c.CallOptions).GetSecuritySettings):len((*c.CallOptions).GetSecuritySettings)], opts...) var resp *cxpb.SecuritySettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -240,8 +312,7 @@ func (c *SecuritySettingsClient) GetSecuritySettings(ctx context.Context, req *c return resp, nil } -// UpdateSecuritySettings updates the specified SecuritySettings. -func (c *SecuritySettingsClient) UpdateSecuritySettings(ctx context.Context, req *cxpb.UpdateSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { +func (c *securitySettingsGRPCClient) UpdateSecuritySettings(ctx context.Context, req *cxpb.UpdateSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -249,7 +320,7 @@ func (c *SecuritySettingsClient) UpdateSecuritySettings(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "security_settings.name", url.QueryEscape(req.GetSecuritySettings().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSecuritySettings[0:len(c.CallOptions.UpdateSecuritySettings):len(c.CallOptions.UpdateSecuritySettings)], opts...) + opts = append((*c.CallOptions).UpdateSecuritySettings[0:len((*c.CallOptions).UpdateSecuritySettings):len((*c.CallOptions).UpdateSecuritySettings)], opts...) var resp *cxpb.SecuritySettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -262,11 +333,10 @@ func (c *SecuritySettingsClient) UpdateSecuritySettings(ctx context.Context, req return resp, nil } -// ListSecuritySettings returns the list of all security settings in the specified location. -func (c *SecuritySettingsClient) ListSecuritySettings(ctx context.Context, req *cxpb.ListSecuritySettingsRequest, opts ...gax.CallOption) *SecuritySettingsIterator { +func (c *securitySettingsGRPCClient) ListSecuritySettings(ctx context.Context, req *cxpb.ListSecuritySettingsRequest, opts ...gax.CallOption) *SecuritySettingsIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSecuritySettings[0:len(c.CallOptions.ListSecuritySettings):len(c.CallOptions.ListSecuritySettings)], opts...) + opts = append((*c.CallOptions).ListSecuritySettings[0:len((*c.CallOptions).ListSecuritySettings):len((*c.CallOptions).ListSecuritySettings)], opts...) it := &SecuritySettingsIterator{} req = proto.Clone(req).(*cxpb.ListSecuritySettingsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.SecuritySettings, string, error) { @@ -303,8 +373,7 @@ func (c *SecuritySettingsClient) ListSecuritySettings(ctx context.Context, req * return it } -// DeleteSecuritySettings deletes the specified SecuritySettings. -func (c *SecuritySettingsClient) DeleteSecuritySettings(ctx context.Context, req *cxpb.DeleteSecuritySettingsRequest, opts ...gax.CallOption) error { +func (c *securitySettingsGRPCClient) DeleteSecuritySettings(ctx context.Context, req *cxpb.DeleteSecuritySettingsRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -312,7 +381,7 @@ func (c *SecuritySettingsClient) DeleteSecuritySettings(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteSecuritySettings[0:len(c.CallOptions.DeleteSecuritySettings):len(c.CallOptions.DeleteSecuritySettings)], opts...) + opts = append((*c.CallOptions).DeleteSecuritySettings[0:len((*c.CallOptions).DeleteSecuritySettings):len((*c.CallOptions).DeleteSecuritySettings)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.securitySettingsClient.DeleteSecuritySettings(ctx, req, settings.GRPC...) diff --git a/dialogflow/cx/apiv3/security_settings_client_example_test.go b/dialogflow/cx/apiv3/security_settings_client_example_test.go index cd299ce1a262..d742438ac36f 100644 --- a/dialogflow/cx/apiv3/security_settings_client_example_test.go +++ b/dialogflow/cx/apiv3/security_settings_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewSecuritySettingsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleSecuritySettingsClient_CreateSecuritySettings() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSecuritySettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateSecuritySettingsRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleSecuritySettingsClient_CreateSecuritySettings() { } func ExampleSecuritySettingsClient_GetSecuritySettings() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSecuritySettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetSecuritySettingsRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleSecuritySettingsClient_GetSecuritySettings() { } func ExampleSecuritySettingsClient_UpdateSecuritySettings() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSecuritySettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateSecuritySettingsRequest{ // TODO: Fill request struct fields. @@ -95,14 +94,12 @@ func ExampleSecuritySettingsClient_UpdateSecuritySettings() { } func ExampleSecuritySettingsClient_ListSecuritySettings() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewSecuritySettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListSecuritySettingsRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleSecuritySettingsClient_DeleteSecuritySettings() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteSecuritySettingsRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3/session_entity_types_client.go b/dialogflow/cx/apiv3/session_entity_types_client.go index 3b2e90aadddc..b9e73a276204 100644 --- a/dialogflow/cx/apiv3/session_entity_types_client.go +++ b/dialogflow/cx/apiv3/session_entity_types_client.go @@ -46,7 +46,7 @@ type SessionEntityTypesCallOptions struct { DeleteSessionEntityType []gax.CallOption } -func defaultSessionEntityTypesClientOptions() []option.ClientOption { +func defaultSessionEntityTypesGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,103 @@ func defaultSessionEntityTypesCallOptions() *SessionEntityTypesCallOptions { } } +// internalSessionEntityTypesClient is an interface that defines the methods availaible from Dialogflow API. +type internalSessionEntityTypesClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListSessionEntityTypes(context.Context, *cxpb.ListSessionEntityTypesRequest, ...gax.CallOption) *SessionEntityTypeIterator + GetSessionEntityType(context.Context, *cxpb.GetSessionEntityTypeRequest, ...gax.CallOption) (*cxpb.SessionEntityType, error) + CreateSessionEntityType(context.Context, *cxpb.CreateSessionEntityTypeRequest, ...gax.CallOption) (*cxpb.SessionEntityType, error) + UpdateSessionEntityType(context.Context, *cxpb.UpdateSessionEntityTypeRequest, ...gax.CallOption) (*cxpb.SessionEntityType, error) + DeleteSessionEntityType(context.Context, *cxpb.DeleteSessionEntityTypeRequest, ...gax.CallOption) error +} + // SessionEntityTypesClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing SessionEntityTypes. type SessionEntityTypesClient struct { + // The internal transport-dependent client. + internalClient internalSessionEntityTypesClient + + // The call options for this service. + CallOptions *SessionEntityTypesCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *SessionEntityTypesClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *SessionEntityTypesClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *SessionEntityTypesClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListSessionEntityTypes returns the list of all session entity types in the specified session. +func (c *SessionEntityTypesClient) ListSessionEntityTypes(ctx context.Context, req *cxpb.ListSessionEntityTypesRequest, opts ...gax.CallOption) *SessionEntityTypeIterator { + return c.internalClient.ListSessionEntityTypes(ctx, req, opts...) +} + +// GetSessionEntityType retrieves the specified session entity type. +func (c *SessionEntityTypesClient) GetSessionEntityType(ctx context.Context, req *cxpb.GetSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { + return c.internalClient.GetSessionEntityType(ctx, req, opts...) +} + +// CreateSessionEntityType creates a session entity type. +func (c *SessionEntityTypesClient) CreateSessionEntityType(ctx context.Context, req *cxpb.CreateSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { + return c.internalClient.CreateSessionEntityType(ctx, req, opts...) +} + +// UpdateSessionEntityType updates the specified session entity type. +func (c *SessionEntityTypesClient) UpdateSessionEntityType(ctx context.Context, req *cxpb.UpdateSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { + return c.internalClient.UpdateSessionEntityType(ctx, req, opts...) +} + +// DeleteSessionEntityType deletes the specified session entity type. +func (c *SessionEntityTypesClient) DeleteSessionEntityType(ctx context.Context, req *cxpb.DeleteSessionEntityTypeRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteSessionEntityType(ctx, req, opts...) +} + +// sessionEntityTypesGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type sessionEntityTypesGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing SessionEntityTypesClient + CallOptions **SessionEntityTypesCallOptions + // The gRPC API client. sessionEntityTypesClient cxpb.SessionEntityTypesClient - // The call options for this service. - CallOptions *SessionEntityTypesCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewSessionEntityTypesClient creates a new session entity types client. +// NewSessionEntityTypesClient creates a new session entity types client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing SessionEntityTypes. func NewSessionEntityTypesClient(ctx context.Context, opts ...option.ClientOption) (*SessionEntityTypesClient, error) { - clientOpts := defaultSessionEntityTypesClientOptions() - + clientOpts := defaultSessionEntityTypesGRPCClientOptions() if newSessionEntityTypesClientHook != nil { hookOpts, err := newSessionEntityTypesClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,45 +232,47 @@ func NewSessionEntityTypesClient(ctx context.Context, opts ...option.ClientOptio if err != nil { return nil, err } - c := &SessionEntityTypesClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultSessionEntityTypesCallOptions(), + client := SessionEntityTypesClient{CallOptions: defaultSessionEntityTypesCallOptions()} + c := &sessionEntityTypesGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, sessionEntityTypesClient: cxpb.NewSessionEntityTypesClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *SessionEntityTypesClient) Connection() *grpc.ClientConn { +func (c *sessionEntityTypesGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *SessionEntityTypesClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *SessionEntityTypesClient) setGoogleClientInfo(keyval ...string) { +func (c *sessionEntityTypesGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListSessionEntityTypes returns the list of all session entity types in the specified session. -func (c *SessionEntityTypesClient) ListSessionEntityTypes(ctx context.Context, req *cxpb.ListSessionEntityTypesRequest, opts ...gax.CallOption) *SessionEntityTypeIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *sessionEntityTypesGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *sessionEntityTypesGRPCClient) ListSessionEntityTypes(ctx context.Context, req *cxpb.ListSessionEntityTypesRequest, opts ...gax.CallOption) *SessionEntityTypeIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSessionEntityTypes[0:len(c.CallOptions.ListSessionEntityTypes):len(c.CallOptions.ListSessionEntityTypes)], opts...) + opts = append((*c.CallOptions).ListSessionEntityTypes[0:len((*c.CallOptions).ListSessionEntityTypes):len((*c.CallOptions).ListSessionEntityTypes)], opts...) it := &SessionEntityTypeIterator{} req = proto.Clone(req).(*cxpb.ListSessionEntityTypesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.SessionEntityType, string, error) { @@ -236,8 +309,7 @@ func (c *SessionEntityTypesClient) ListSessionEntityTypes(ctx context.Context, r return it } -// GetSessionEntityType retrieves the specified session entity type. -func (c *SessionEntityTypesClient) GetSessionEntityType(ctx context.Context, req *cxpb.GetSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { +func (c *sessionEntityTypesGRPCClient) GetSessionEntityType(ctx context.Context, req *cxpb.GetSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -245,7 +317,7 @@ func (c *SessionEntityTypesClient) GetSessionEntityType(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSessionEntityType[0:len(c.CallOptions.GetSessionEntityType):len(c.CallOptions.GetSessionEntityType)], opts...) + opts = append((*c.CallOptions).GetSessionEntityType[0:len((*c.CallOptions).GetSessionEntityType):len((*c.CallOptions).GetSessionEntityType)], opts...) var resp *cxpb.SessionEntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -258,8 +330,7 @@ func (c *SessionEntityTypesClient) GetSessionEntityType(ctx context.Context, req return resp, nil } -// CreateSessionEntityType creates a session entity type. -func (c *SessionEntityTypesClient) CreateSessionEntityType(ctx context.Context, req *cxpb.CreateSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { +func (c *sessionEntityTypesGRPCClient) CreateSessionEntityType(ctx context.Context, req *cxpb.CreateSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -267,7 +338,7 @@ func (c *SessionEntityTypesClient) CreateSessionEntityType(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSessionEntityType[0:len(c.CallOptions.CreateSessionEntityType):len(c.CallOptions.CreateSessionEntityType)], opts...) + opts = append((*c.CallOptions).CreateSessionEntityType[0:len((*c.CallOptions).CreateSessionEntityType):len((*c.CallOptions).CreateSessionEntityType)], opts...) var resp *cxpb.SessionEntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -280,8 +351,7 @@ func (c *SessionEntityTypesClient) CreateSessionEntityType(ctx context.Context, return resp, nil } -// UpdateSessionEntityType updates the specified session entity type. -func (c *SessionEntityTypesClient) UpdateSessionEntityType(ctx context.Context, req *cxpb.UpdateSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { +func (c *sessionEntityTypesGRPCClient) UpdateSessionEntityType(ctx context.Context, req *cxpb.UpdateSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -289,7 +359,7 @@ func (c *SessionEntityTypesClient) UpdateSessionEntityType(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session_entity_type.name", url.QueryEscape(req.GetSessionEntityType().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSessionEntityType[0:len(c.CallOptions.UpdateSessionEntityType):len(c.CallOptions.UpdateSessionEntityType)], opts...) + opts = append((*c.CallOptions).UpdateSessionEntityType[0:len((*c.CallOptions).UpdateSessionEntityType):len((*c.CallOptions).UpdateSessionEntityType)], opts...) var resp *cxpb.SessionEntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -302,8 +372,7 @@ func (c *SessionEntityTypesClient) UpdateSessionEntityType(ctx context.Context, return resp, nil } -// DeleteSessionEntityType deletes the specified session entity type. -func (c *SessionEntityTypesClient) DeleteSessionEntityType(ctx context.Context, req *cxpb.DeleteSessionEntityTypeRequest, opts ...gax.CallOption) error { +func (c *sessionEntityTypesGRPCClient) DeleteSessionEntityType(ctx context.Context, req *cxpb.DeleteSessionEntityTypeRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -311,7 +380,7 @@ func (c *SessionEntityTypesClient) DeleteSessionEntityType(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteSessionEntityType[0:len(c.CallOptions.DeleteSessionEntityType):len(c.CallOptions.DeleteSessionEntityType)], opts...) + opts = append((*c.CallOptions).DeleteSessionEntityType[0:len((*c.CallOptions).DeleteSessionEntityType):len((*c.CallOptions).DeleteSessionEntityType)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.sessionEntityTypesClient.DeleteSessionEntityType(ctx, req, settings.GRPC...) diff --git a/dialogflow/cx/apiv3/session_entity_types_client_example_test.go b/dialogflow/cx/apiv3/session_entity_types_client_example_test.go index eea7879d00a4..5ed7efd97307 100644 --- a/dialogflow/cx/apiv3/session_entity_types_client_example_test.go +++ b/dialogflow/cx/apiv3/session_entity_types_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewSessionEntityTypesClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleSessionEntityTypesClient_ListSessionEntityTypes() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListSessionEntityTypesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleSessionEntityTypesClient_ListSessionEntityTypes() { } func ExampleSessionEntityTypesClient_GetSessionEntityType() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetSessionEntityTypeRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleSessionEntityTypesClient_GetSessionEntityType() { } func ExampleSessionEntityTypesClient_CreateSessionEntityType() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateSessionEntityTypeRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleSessionEntityTypesClient_CreateSessionEntityType() { } func ExampleSessionEntityTypesClient_UpdateSessionEntityType() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateSessionEntityTypeRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleSessionEntityTypesClient_DeleteSessionEntityType() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteSessionEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3/sessions_client.go b/dialogflow/cx/apiv3/sessions_client.go index 3a7b8fa7fd91..9906476347f8 100644 --- a/dialogflow/cx/apiv3/sessions_client.go +++ b/dialogflow/cx/apiv3/sessions_client.go @@ -43,7 +43,7 @@ type SessionsCallOptions struct { FulfillIntent []gax.CallOption } -func defaultSessionsClientOptions() []option.ClientOption { +func defaultSessionsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -94,34 +94,117 @@ func defaultSessionsCallOptions() *SessionsCallOptions { } } +// internalSessionsClient is an interface that defines the methods availaible from Dialogflow API. +type internalSessionsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + DetectIntent(context.Context, *cxpb.DetectIntentRequest, ...gax.CallOption) (*cxpb.DetectIntentResponse, error) + StreamingDetectIntent(context.Context, ...gax.CallOption) (cxpb.Sessions_StreamingDetectIntentClient, error) + MatchIntent(context.Context, *cxpb.MatchIntentRequest, ...gax.CallOption) (*cxpb.MatchIntentResponse, error) + FulfillIntent(context.Context, *cxpb.FulfillIntentRequest, ...gax.CallOption) (*cxpb.FulfillIntentResponse, error) +} + // SessionsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A session represents an interaction with a user. You retrieve user input +// and pass it to the DetectIntent method to determine +// user intent and respond. type SessionsClient struct { + // The internal transport-dependent client. + internalClient internalSessionsClient + + // The call options for this service. + CallOptions *SessionsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *SessionsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *SessionsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *SessionsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// DetectIntent processes a natural language query and returns structured, actionable data +// as a result. This method is not idempotent, because it may cause session +// entity types to be updated, which in turn might affect results of future +// queries. +// +// Note: Always use agent versions for production traffic. +// See Versions and +// environments (at https://cloud.google.com/dialogflow/cx/docs/concept/version). +func (c *SessionsClient) DetectIntent(ctx context.Context, req *cxpb.DetectIntentRequest, opts ...gax.CallOption) (*cxpb.DetectIntentResponse, error) { + return c.internalClient.DetectIntent(ctx, req, opts...) +} + +// StreamingDetectIntent processes a natural language query in audio format in a streaming fashion +// and returns structured, actionable data as a result. This method is only +// available via the gRPC API (not REST). +// +// Note: Always use agent versions for production traffic. +// See Versions and +// environments (at https://cloud.google.com/dialogflow/cx/docs/concept/version). +func (c *SessionsClient) StreamingDetectIntent(ctx context.Context, opts ...gax.CallOption) (cxpb.Sessions_StreamingDetectIntentClient, error) { + return c.internalClient.StreamingDetectIntent(ctx, opts...) +} + +// MatchIntent returns preliminary intent match results, doesn’t change the session +// status. +func (c *SessionsClient) MatchIntent(ctx context.Context, req *cxpb.MatchIntentRequest, opts ...gax.CallOption) (*cxpb.MatchIntentResponse, error) { + return c.internalClient.MatchIntent(ctx, req, opts...) +} + +// FulfillIntent fulfills a matched intent returned by MatchIntent. +// Must be called after MatchIntent, with input from +// MatchIntentResponse. Otherwise, the behavior is undefined. +func (c *SessionsClient) FulfillIntent(ctx context.Context, req *cxpb.FulfillIntentRequest, opts ...gax.CallOption) (*cxpb.FulfillIntentResponse, error) { + return c.internalClient.FulfillIntent(ctx, req, opts...) +} + +// sessionsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type sessionsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing SessionsClient + CallOptions **SessionsCallOptions + // The gRPC API client. sessionsClient cxpb.SessionsClient - // The call options for this service. - CallOptions *SessionsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewSessionsClient creates a new sessions client. +// NewSessionsClient creates a new sessions client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A session represents an interaction with a user. You retrieve user input // and pass it to the DetectIntent method to determine // user intent and respond. func NewSessionsClient(ctx context.Context, opts ...option.ClientOption) (*SessionsClient, error) { - clientOpts := defaultSessionsClientOptions() - + clientOpts := defaultSessionsGRPCClientOptions() if newSessionsClientHook != nil { hookOpts, err := newSessionsClientHook(ctx, clientHookParams{}) if err != nil { @@ -139,49 +222,44 @@ func NewSessionsClient(ctx context.Context, opts ...option.ClientOption) (*Sessi if err != nil { return nil, err } - c := &SessionsClient{ + client := SessionsClient{CallOptions: defaultSessionsCallOptions()} + + c := &sessionsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultSessionsCallOptions(), - - sessionsClient: cxpb.NewSessionsClient(connPool), + sessionsClient: cxpb.NewSessionsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *SessionsClient) Connection() *grpc.ClientConn { +func (c *sessionsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *SessionsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *SessionsClient) setGoogleClientInfo(keyval ...string) { +func (c *sessionsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// DetectIntent processes a natural language query and returns structured, actionable data -// as a result. This method is not idempotent, because it may cause session -// entity types to be updated, which in turn might affect results of future -// queries. -// -// Note: Always use agent versions for production traffic. -// See Versions and -// environments (at https://cloud.google.com/dialogflow/cx/docs/concept/version). -func (c *SessionsClient) DetectIntent(ctx context.Context, req *cxpb.DetectIntentRequest, opts ...gax.CallOption) (*cxpb.DetectIntentResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *sessionsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *sessionsGRPCClient) DetectIntent(ctx context.Context, req *cxpb.DetectIntentRequest, opts ...gax.CallOption) (*cxpb.DetectIntentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 220000*time.Millisecond) defer cancel() @@ -189,7 +267,7 @@ func (c *SessionsClient) DetectIntent(ctx context.Context, req *cxpb.DetectInten } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DetectIntent[0:len(c.CallOptions.DetectIntent):len(c.CallOptions.DetectIntent)], opts...) + opts = append((*c.CallOptions).DetectIntent[0:len((*c.CallOptions).DetectIntent):len((*c.CallOptions).DetectIntent)], opts...) var resp *cxpb.DetectIntentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -202,17 +280,10 @@ func (c *SessionsClient) DetectIntent(ctx context.Context, req *cxpb.DetectInten return resp, nil } -// StreamingDetectIntent processes a natural language query in audio format in a streaming fashion -// and returns structured, actionable data as a result. This method is only -// available via the gRPC API (not REST). -// -// Note: Always use agent versions for production traffic. -// See Versions and -// environments (at https://cloud.google.com/dialogflow/cx/docs/concept/version). -func (c *SessionsClient) StreamingDetectIntent(ctx context.Context, opts ...gax.CallOption) (cxpb.Sessions_StreamingDetectIntentClient, error) { +func (c *sessionsGRPCClient) StreamingDetectIntent(ctx context.Context, opts ...gax.CallOption) (cxpb.Sessions_StreamingDetectIntentClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.StreamingDetectIntent[0:len(c.CallOptions.StreamingDetectIntent):len(c.CallOptions.StreamingDetectIntent)], opts...) var resp cxpb.Sessions_StreamingDetectIntentClient + opts = append((*c.CallOptions).StreamingDetectIntent[0:len((*c.CallOptions).StreamingDetectIntent):len((*c.CallOptions).StreamingDetectIntent)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.sessionsClient.StreamingDetectIntent(ctx, settings.GRPC...) @@ -224,9 +295,7 @@ func (c *SessionsClient) StreamingDetectIntent(ctx context.Context, opts ...gax. return resp, nil } -// MatchIntent returns preliminary intent match results, doesn’t change the session -// status. -func (c *SessionsClient) MatchIntent(ctx context.Context, req *cxpb.MatchIntentRequest, opts ...gax.CallOption) (*cxpb.MatchIntentResponse, error) { +func (c *sessionsGRPCClient) MatchIntent(ctx context.Context, req *cxpb.MatchIntentRequest, opts ...gax.CallOption) (*cxpb.MatchIntentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -234,7 +303,7 @@ func (c *SessionsClient) MatchIntent(ctx context.Context, req *cxpb.MatchIntentR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.MatchIntent[0:len(c.CallOptions.MatchIntent):len(c.CallOptions.MatchIntent)], opts...) + opts = append((*c.CallOptions).MatchIntent[0:len((*c.CallOptions).MatchIntent):len((*c.CallOptions).MatchIntent)], opts...) var resp *cxpb.MatchIntentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -247,10 +316,7 @@ func (c *SessionsClient) MatchIntent(ctx context.Context, req *cxpb.MatchIntentR return resp, nil } -// FulfillIntent fulfills a matched intent returned by MatchIntent. -// Must be called after MatchIntent, with input from -// MatchIntentResponse. Otherwise, the behavior is undefined. -func (c *SessionsClient) FulfillIntent(ctx context.Context, req *cxpb.FulfillIntentRequest, opts ...gax.CallOption) (*cxpb.FulfillIntentResponse, error) { +func (c *sessionsGRPCClient) FulfillIntent(ctx context.Context, req *cxpb.FulfillIntentRequest, opts ...gax.CallOption) (*cxpb.FulfillIntentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -258,7 +324,7 @@ func (c *SessionsClient) FulfillIntent(ctx context.Context, req *cxpb.FulfillInt } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "match_intent_request.session", url.QueryEscape(req.GetMatchIntentRequest().GetSession()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.FulfillIntent[0:len(c.CallOptions.FulfillIntent):len(c.CallOptions.FulfillIntent)], opts...) + opts = append((*c.CallOptions).FulfillIntent[0:len((*c.CallOptions).FulfillIntent):len((*c.CallOptions).FulfillIntent)], opts...) var resp *cxpb.FulfillIntentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/dialogflow/cx/apiv3/sessions_client_example_test.go b/dialogflow/cx/apiv3/sessions_client_example_test.go index 8c36fa95fdc6..5ea4d4d21860 100644 --- a/dialogflow/cx/apiv3/sessions_client_example_test.go +++ b/dialogflow/cx/apiv3/sessions_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewSessionsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleSessionsClient_DetectIntent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DetectIntentRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleSessionsClient_DetectIntent() { } func ExampleSessionsClient_StreamingDetectIntent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.StreamingDetectIntent(ctx) if err != nil { // TODO: Handle error. @@ -91,13 +91,12 @@ func ExampleSessionsClient_StreamingDetectIntent() { } func ExampleSessionsClient_MatchIntent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.MatchIntentRequest{ // TODO: Fill request struct fields. @@ -111,13 +110,12 @@ func ExampleSessionsClient_MatchIntent() { } func ExampleSessionsClient_FulfillIntent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.FulfillIntentRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3/test_cases_client.go b/dialogflow/cx/apiv3/test_cases_client.go index 53d7f5bab838..04b7f6555578 100644 --- a/dialogflow/cx/apiv3/test_cases_client.go +++ b/dialogflow/cx/apiv3/test_cases_client.go @@ -56,7 +56,7 @@ type TestCasesCallOptions struct { GetTestCaseResult []gax.CallOption } -func defaultTestCasesClientOptions() []option.ClientOption { +func defaultTestCasesGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -205,38 +205,188 @@ func defaultTestCasesCallOptions() *TestCasesCallOptions { } } +// internalTestCasesClient is an interface that defines the methods availaible from Dialogflow API. +type internalTestCasesClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListTestCases(context.Context, *cxpb.ListTestCasesRequest, ...gax.CallOption) *TestCaseIterator + BatchDeleteTestCases(context.Context, *cxpb.BatchDeleteTestCasesRequest, ...gax.CallOption) error + GetTestCase(context.Context, *cxpb.GetTestCaseRequest, ...gax.CallOption) (*cxpb.TestCase, error) + CreateTestCase(context.Context, *cxpb.CreateTestCaseRequest, ...gax.CallOption) (*cxpb.TestCase, error) + UpdateTestCase(context.Context, *cxpb.UpdateTestCaseRequest, ...gax.CallOption) (*cxpb.TestCase, error) + RunTestCase(context.Context, *cxpb.RunTestCaseRequest, ...gax.CallOption) (*RunTestCaseOperation, error) + RunTestCaseOperation(name string) *RunTestCaseOperation + BatchRunTestCases(context.Context, *cxpb.BatchRunTestCasesRequest, ...gax.CallOption) (*BatchRunTestCasesOperation, error) + BatchRunTestCasesOperation(name string) *BatchRunTestCasesOperation + CalculateCoverage(context.Context, *cxpb.CalculateCoverageRequest, ...gax.CallOption) (*cxpb.CalculateCoverageResponse, error) + ImportTestCases(context.Context, *cxpb.ImportTestCasesRequest, ...gax.CallOption) (*ImportTestCasesOperation, error) + ImportTestCasesOperation(name string) *ImportTestCasesOperation + ExportTestCases(context.Context, *cxpb.ExportTestCasesRequest, ...gax.CallOption) (*ExportTestCasesOperation, error) + ExportTestCasesOperation(name string) *ExportTestCasesOperation + ListTestCaseResults(context.Context, *cxpb.ListTestCaseResultsRequest, ...gax.CallOption) *TestCaseResultIterator + GetTestCaseResult(context.Context, *cxpb.GetTestCaseResultRequest, ...gax.CallOption) (*cxpb.TestCaseResult, error) +} + // TestCasesClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing [Test Cases][google.cloud.dialogflow.cx.v3.TestCase] and +// [Test Case Results][google.cloud.dialogflow.cx.v3.TestCaseResult]. type TestCasesClient struct { + // The internal transport-dependent client. + internalClient internalTestCasesClient + + // The call options for this service. + CallOptions *TestCasesCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *TestCasesClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *TestCasesClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *TestCasesClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListTestCases fetches a list of test cases for a given agent. +func (c *TestCasesClient) ListTestCases(ctx context.Context, req *cxpb.ListTestCasesRequest, opts ...gax.CallOption) *TestCaseIterator { + return c.internalClient.ListTestCases(ctx, req, opts...) +} + +// BatchDeleteTestCases batch deletes test cases. +func (c *TestCasesClient) BatchDeleteTestCases(ctx context.Context, req *cxpb.BatchDeleteTestCasesRequest, opts ...gax.CallOption) error { + return c.internalClient.BatchDeleteTestCases(ctx, req, opts...) +} + +// GetTestCase gets a test case. +func (c *TestCasesClient) GetTestCase(ctx context.Context, req *cxpb.GetTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { + return c.internalClient.GetTestCase(ctx, req, opts...) +} + +// CreateTestCase creates a test case for the given agent. +func (c *TestCasesClient) CreateTestCase(ctx context.Context, req *cxpb.CreateTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { + return c.internalClient.CreateTestCase(ctx, req, opts...) +} + +// UpdateTestCase updates the specified test case. +func (c *TestCasesClient) UpdateTestCase(ctx context.Context, req *cxpb.UpdateTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { + return c.internalClient.UpdateTestCase(ctx, req, opts...) +} + +// RunTestCase kicks off a test case run. +func (c *TestCasesClient) RunTestCase(ctx context.Context, req *cxpb.RunTestCaseRequest, opts ...gax.CallOption) (*RunTestCaseOperation, error) { + return c.internalClient.RunTestCase(ctx, req, opts...) +} + +// RunTestCaseOperation returns a new RunTestCaseOperation from a given name. +// The name must be that of a previously created RunTestCaseOperation, possibly from a different process. +func (c *TestCasesClient) RunTestCaseOperation(name string) *RunTestCaseOperation { + return c.internalClient.RunTestCaseOperation(name) +} + +// BatchRunTestCases kicks off a batch run of test cases. +func (c *TestCasesClient) BatchRunTestCases(ctx context.Context, req *cxpb.BatchRunTestCasesRequest, opts ...gax.CallOption) (*BatchRunTestCasesOperation, error) { + return c.internalClient.BatchRunTestCases(ctx, req, opts...) +} + +// BatchRunTestCasesOperation returns a new BatchRunTestCasesOperation from a given name. +// The name must be that of a previously created BatchRunTestCasesOperation, possibly from a different process. +func (c *TestCasesClient) BatchRunTestCasesOperation(name string) *BatchRunTestCasesOperation { + return c.internalClient.BatchRunTestCasesOperation(name) +} + +// CalculateCoverage calculates the test coverage for an agent. +func (c *TestCasesClient) CalculateCoverage(ctx context.Context, req *cxpb.CalculateCoverageRequest, opts ...gax.CallOption) (*cxpb.CalculateCoverageResponse, error) { + return c.internalClient.CalculateCoverage(ctx, req, opts...) +} + +// ImportTestCases imports the test cases from a Cloud Storage bucket or a local file. It +// always creates new test cases and won’t overwite any existing ones. The +// provided ID in the imported test case is neglected. +func (c *TestCasesClient) ImportTestCases(ctx context.Context, req *cxpb.ImportTestCasesRequest, opts ...gax.CallOption) (*ImportTestCasesOperation, error) { + return c.internalClient.ImportTestCases(ctx, req, opts...) +} + +// ImportTestCasesOperation returns a new ImportTestCasesOperation from a given name. +// The name must be that of a previously created ImportTestCasesOperation, possibly from a different process. +func (c *TestCasesClient) ImportTestCasesOperation(name string) *ImportTestCasesOperation { + return c.internalClient.ImportTestCasesOperation(name) +} + +// ExportTestCases exports the test cases under the agent to a Cloud Storage bucket or a local +// file. Filter can be applied to export a subset of test cases. +func (c *TestCasesClient) ExportTestCases(ctx context.Context, req *cxpb.ExportTestCasesRequest, opts ...gax.CallOption) (*ExportTestCasesOperation, error) { + return c.internalClient.ExportTestCases(ctx, req, opts...) +} + +// ExportTestCasesOperation returns a new ExportTestCasesOperation from a given name. +// The name must be that of a previously created ExportTestCasesOperation, possibly from a different process. +func (c *TestCasesClient) ExportTestCasesOperation(name string) *ExportTestCasesOperation { + return c.internalClient.ExportTestCasesOperation(name) +} + +// ListTestCaseResults fetches a list of results for a given test case. +func (c *TestCasesClient) ListTestCaseResults(ctx context.Context, req *cxpb.ListTestCaseResultsRequest, opts ...gax.CallOption) *TestCaseResultIterator { + return c.internalClient.ListTestCaseResults(ctx, req, opts...) +} + +// GetTestCaseResult gets a test case result. +func (c *TestCasesClient) GetTestCaseResult(ctx context.Context, req *cxpb.GetTestCaseResultRequest, opts ...gax.CallOption) (*cxpb.TestCaseResult, error) { + return c.internalClient.GetTestCaseResult(ctx, req, opts...) +} + +// testCasesGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type testCasesGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing TestCasesClient + CallOptions **TestCasesCallOptions + // The gRPC API client. testCasesClient cxpb.TestCasesClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *TestCasesCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewTestCasesClient creates a new test cases client. +// NewTestCasesClient creates a new test cases client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing [Test Cases][google.cloud.dialogflow.cx.v3.TestCase] and // [Test Case Results][google.cloud.dialogflow.cx.v3.TestCaseResult]. func NewTestCasesClient(ctx context.Context, opts ...option.ClientOption) (*TestCasesClient, error) { - clientOpts := defaultTestCasesClientOptions() - + clientOpts := defaultTestCasesGRPCClientOptions() if newTestCasesClientHook != nil { hookOpts, err := newTestCasesClientHook(ctx, clientHookParams{}) if err != nil { @@ -254,16 +404,19 @@ func NewTestCasesClient(ctx context.Context, opts ...option.ClientOption) (*Test if err != nil { return nil, err } - c := &TestCasesClient{ + client := TestCasesClient{CallOptions: defaultTestCasesCallOptions()} + + c := &testCasesGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultTestCasesCallOptions(), - - testCasesClient: cxpb.NewTestCasesClient(connPool), + testCasesClient: cxpb.NewTestCasesClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -273,36 +426,36 @@ func NewTestCasesClient(ctx context.Context, opts ...option.ClientOption) (*Test // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *TestCasesClient) Connection() *grpc.ClientConn { +func (c *testCasesGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *TestCasesClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *TestCasesClient) setGoogleClientInfo(keyval ...string) { +func (c *testCasesGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListTestCases fetches a list of test cases for a given agent. -func (c *TestCasesClient) ListTestCases(ctx context.Context, req *cxpb.ListTestCasesRequest, opts ...gax.CallOption) *TestCaseIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *testCasesGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *testCasesGRPCClient) ListTestCases(ctx context.Context, req *cxpb.ListTestCasesRequest, opts ...gax.CallOption) *TestCaseIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTestCases[0:len(c.CallOptions.ListTestCases):len(c.CallOptions.ListTestCases)], opts...) + opts = append((*c.CallOptions).ListTestCases[0:len((*c.CallOptions).ListTestCases):len((*c.CallOptions).ListTestCases)], opts...) it := &TestCaseIterator{} req = proto.Clone(req).(*cxpb.ListTestCasesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.TestCase, string, error) { @@ -339,8 +492,7 @@ func (c *TestCasesClient) ListTestCases(ctx context.Context, req *cxpb.ListTestC return it } -// BatchDeleteTestCases batch deletes test cases. -func (c *TestCasesClient) BatchDeleteTestCases(ctx context.Context, req *cxpb.BatchDeleteTestCasesRequest, opts ...gax.CallOption) error { +func (c *testCasesGRPCClient) BatchDeleteTestCases(ctx context.Context, req *cxpb.BatchDeleteTestCasesRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -348,7 +500,7 @@ func (c *TestCasesClient) BatchDeleteTestCases(ctx context.Context, req *cxpb.Ba } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchDeleteTestCases[0:len(c.CallOptions.BatchDeleteTestCases):len(c.CallOptions.BatchDeleteTestCases)], opts...) + opts = append((*c.CallOptions).BatchDeleteTestCases[0:len((*c.CallOptions).BatchDeleteTestCases):len((*c.CallOptions).BatchDeleteTestCases)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.testCasesClient.BatchDeleteTestCases(ctx, req, settings.GRPC...) @@ -357,8 +509,7 @@ func (c *TestCasesClient) BatchDeleteTestCases(ctx context.Context, req *cxpb.Ba return err } -// GetTestCase gets a test case. -func (c *TestCasesClient) GetTestCase(ctx context.Context, req *cxpb.GetTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { +func (c *testCasesGRPCClient) GetTestCase(ctx context.Context, req *cxpb.GetTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -366,7 +517,7 @@ func (c *TestCasesClient) GetTestCase(ctx context.Context, req *cxpb.GetTestCase } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTestCase[0:len(c.CallOptions.GetTestCase):len(c.CallOptions.GetTestCase)], opts...) + opts = append((*c.CallOptions).GetTestCase[0:len((*c.CallOptions).GetTestCase):len((*c.CallOptions).GetTestCase)], opts...) var resp *cxpb.TestCase err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -379,8 +530,7 @@ func (c *TestCasesClient) GetTestCase(ctx context.Context, req *cxpb.GetTestCase return resp, nil } -// CreateTestCase creates a test case for the given agent. -func (c *TestCasesClient) CreateTestCase(ctx context.Context, req *cxpb.CreateTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { +func (c *testCasesGRPCClient) CreateTestCase(ctx context.Context, req *cxpb.CreateTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -388,7 +538,7 @@ func (c *TestCasesClient) CreateTestCase(ctx context.Context, req *cxpb.CreateTe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTestCase[0:len(c.CallOptions.CreateTestCase):len(c.CallOptions.CreateTestCase)], opts...) + opts = append((*c.CallOptions).CreateTestCase[0:len((*c.CallOptions).CreateTestCase):len((*c.CallOptions).CreateTestCase)], opts...) var resp *cxpb.TestCase err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -401,8 +551,7 @@ func (c *TestCasesClient) CreateTestCase(ctx context.Context, req *cxpb.CreateTe return resp, nil } -// UpdateTestCase updates the specified test case. -func (c *TestCasesClient) UpdateTestCase(ctx context.Context, req *cxpb.UpdateTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { +func (c *testCasesGRPCClient) UpdateTestCase(ctx context.Context, req *cxpb.UpdateTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -410,7 +559,7 @@ func (c *TestCasesClient) UpdateTestCase(ctx context.Context, req *cxpb.UpdateTe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "test_case.name", url.QueryEscape(req.GetTestCase().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTestCase[0:len(c.CallOptions.UpdateTestCase):len(c.CallOptions.UpdateTestCase)], opts...) + opts = append((*c.CallOptions).UpdateTestCase[0:len((*c.CallOptions).UpdateTestCase):len((*c.CallOptions).UpdateTestCase)], opts...) var resp *cxpb.TestCase err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -423,8 +572,7 @@ func (c *TestCasesClient) UpdateTestCase(ctx context.Context, req *cxpb.UpdateTe return resp, nil } -// RunTestCase kicks off a test case run. -func (c *TestCasesClient) RunTestCase(ctx context.Context, req *cxpb.RunTestCaseRequest, opts ...gax.CallOption) (*RunTestCaseOperation, error) { +func (c *testCasesGRPCClient) RunTestCase(ctx context.Context, req *cxpb.RunTestCaseRequest, opts ...gax.CallOption) (*RunTestCaseOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -432,7 +580,7 @@ func (c *TestCasesClient) RunTestCase(ctx context.Context, req *cxpb.RunTestCase } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RunTestCase[0:len(c.CallOptions.RunTestCase):len(c.CallOptions.RunTestCase)], opts...) + opts = append((*c.CallOptions).RunTestCase[0:len((*c.CallOptions).RunTestCase):len((*c.CallOptions).RunTestCase)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -443,12 +591,11 @@ func (c *TestCasesClient) RunTestCase(ctx context.Context, req *cxpb.RunTestCase return nil, err } return &RunTestCaseOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// BatchRunTestCases kicks off a batch run of test cases. -func (c *TestCasesClient) BatchRunTestCases(ctx context.Context, req *cxpb.BatchRunTestCasesRequest, opts ...gax.CallOption) (*BatchRunTestCasesOperation, error) { +func (c *testCasesGRPCClient) BatchRunTestCases(ctx context.Context, req *cxpb.BatchRunTestCasesRequest, opts ...gax.CallOption) (*BatchRunTestCasesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -456,7 +603,7 @@ func (c *TestCasesClient) BatchRunTestCases(ctx context.Context, req *cxpb.Batch } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchRunTestCases[0:len(c.CallOptions.BatchRunTestCases):len(c.CallOptions.BatchRunTestCases)], opts...) + opts = append((*c.CallOptions).BatchRunTestCases[0:len((*c.CallOptions).BatchRunTestCases):len((*c.CallOptions).BatchRunTestCases)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -467,12 +614,11 @@ func (c *TestCasesClient) BatchRunTestCases(ctx context.Context, req *cxpb.Batch return nil, err } return &BatchRunTestCasesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// CalculateCoverage calculates the test coverage for an agent. -func (c *TestCasesClient) CalculateCoverage(ctx context.Context, req *cxpb.CalculateCoverageRequest, opts ...gax.CallOption) (*cxpb.CalculateCoverageResponse, error) { +func (c *testCasesGRPCClient) CalculateCoverage(ctx context.Context, req *cxpb.CalculateCoverageRequest, opts ...gax.CallOption) (*cxpb.CalculateCoverageResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -480,7 +626,7 @@ func (c *TestCasesClient) CalculateCoverage(ctx context.Context, req *cxpb.Calcu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "agent", url.QueryEscape(req.GetAgent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CalculateCoverage[0:len(c.CallOptions.CalculateCoverage):len(c.CallOptions.CalculateCoverage)], opts...) + opts = append((*c.CallOptions).CalculateCoverage[0:len((*c.CallOptions).CalculateCoverage):len((*c.CallOptions).CalculateCoverage)], opts...) var resp *cxpb.CalculateCoverageResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -493,10 +639,7 @@ func (c *TestCasesClient) CalculateCoverage(ctx context.Context, req *cxpb.Calcu return resp, nil } -// ImportTestCases imports the test cases from a Cloud Storage bucket or a local file. It -// always creates new test cases and won’t overwite any existing ones. The -// provided ID in the imported test case is neglected. -func (c *TestCasesClient) ImportTestCases(ctx context.Context, req *cxpb.ImportTestCasesRequest, opts ...gax.CallOption) (*ImportTestCasesOperation, error) { +func (c *testCasesGRPCClient) ImportTestCases(ctx context.Context, req *cxpb.ImportTestCasesRequest, opts ...gax.CallOption) (*ImportTestCasesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -504,7 +647,7 @@ func (c *TestCasesClient) ImportTestCases(ctx context.Context, req *cxpb.ImportT } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportTestCases[0:len(c.CallOptions.ImportTestCases):len(c.CallOptions.ImportTestCases)], opts...) + opts = append((*c.CallOptions).ImportTestCases[0:len((*c.CallOptions).ImportTestCases):len((*c.CallOptions).ImportTestCases)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -515,13 +658,11 @@ func (c *TestCasesClient) ImportTestCases(ctx context.Context, req *cxpb.ImportT return nil, err } return &ImportTestCasesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ExportTestCases exports the test cases under the agent to a Cloud Storage bucket or a local -// file. Filter can be applied to export a subset of test cases. -func (c *TestCasesClient) ExportTestCases(ctx context.Context, req *cxpb.ExportTestCasesRequest, opts ...gax.CallOption) (*ExportTestCasesOperation, error) { +func (c *testCasesGRPCClient) ExportTestCases(ctx context.Context, req *cxpb.ExportTestCasesRequest, opts ...gax.CallOption) (*ExportTestCasesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -529,7 +670,7 @@ func (c *TestCasesClient) ExportTestCases(ctx context.Context, req *cxpb.ExportT } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportTestCases[0:len(c.CallOptions.ExportTestCases):len(c.CallOptions.ExportTestCases)], opts...) + opts = append((*c.CallOptions).ExportTestCases[0:len((*c.CallOptions).ExportTestCases):len((*c.CallOptions).ExportTestCases)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -540,15 +681,14 @@ func (c *TestCasesClient) ExportTestCases(ctx context.Context, req *cxpb.ExportT return nil, err } return &ExportTestCasesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListTestCaseResults fetches a list of results for a given test case. -func (c *TestCasesClient) ListTestCaseResults(ctx context.Context, req *cxpb.ListTestCaseResultsRequest, opts ...gax.CallOption) *TestCaseResultIterator { +func (c *testCasesGRPCClient) ListTestCaseResults(ctx context.Context, req *cxpb.ListTestCaseResultsRequest, opts ...gax.CallOption) *TestCaseResultIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTestCaseResults[0:len(c.CallOptions.ListTestCaseResults):len(c.CallOptions.ListTestCaseResults)], opts...) + opts = append((*c.CallOptions).ListTestCaseResults[0:len((*c.CallOptions).ListTestCaseResults):len((*c.CallOptions).ListTestCaseResults)], opts...) it := &TestCaseResultIterator{} req = proto.Clone(req).(*cxpb.ListTestCaseResultsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.TestCaseResult, string, error) { @@ -585,8 +725,7 @@ func (c *TestCasesClient) ListTestCaseResults(ctx context.Context, req *cxpb.Lis return it } -// GetTestCaseResult gets a test case result. -func (c *TestCasesClient) GetTestCaseResult(ctx context.Context, req *cxpb.GetTestCaseResultRequest, opts ...gax.CallOption) (*cxpb.TestCaseResult, error) { +func (c *testCasesGRPCClient) GetTestCaseResult(ctx context.Context, req *cxpb.GetTestCaseResultRequest, opts ...gax.CallOption) (*cxpb.TestCaseResult, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -594,7 +733,7 @@ func (c *TestCasesClient) GetTestCaseResult(ctx context.Context, req *cxpb.GetTe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTestCaseResult[0:len(c.CallOptions.GetTestCaseResult):len(c.CallOptions.GetTestCaseResult)], opts...) + opts = append((*c.CallOptions).GetTestCaseResult[0:len((*c.CallOptions).GetTestCaseResult):len((*c.CallOptions).GetTestCaseResult)], opts...) var resp *cxpb.TestCaseResult err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -614,9 +753,9 @@ type BatchRunTestCasesOperation struct { // BatchRunTestCasesOperation returns a new BatchRunTestCasesOperation from a given name. // The name must be that of a previously created BatchRunTestCasesOperation, possibly from a different process. -func (c *TestCasesClient) BatchRunTestCasesOperation(name string) *BatchRunTestCasesOperation { +func (c *testCasesGRPCClient) BatchRunTestCasesOperation(name string) *BatchRunTestCasesOperation { return &BatchRunTestCasesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -683,9 +822,9 @@ type ExportTestCasesOperation struct { // ExportTestCasesOperation returns a new ExportTestCasesOperation from a given name. // The name must be that of a previously created ExportTestCasesOperation, possibly from a different process. -func (c *TestCasesClient) ExportTestCasesOperation(name string) *ExportTestCasesOperation { +func (c *testCasesGRPCClient) ExportTestCasesOperation(name string) *ExportTestCasesOperation { return &ExportTestCasesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -752,9 +891,9 @@ type ImportTestCasesOperation struct { // ImportTestCasesOperation returns a new ImportTestCasesOperation from a given name. // The name must be that of a previously created ImportTestCasesOperation, possibly from a different process. -func (c *TestCasesClient) ImportTestCasesOperation(name string) *ImportTestCasesOperation { +func (c *testCasesGRPCClient) ImportTestCasesOperation(name string) *ImportTestCasesOperation { return &ImportTestCasesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -821,9 +960,9 @@ type RunTestCaseOperation struct { // RunTestCaseOperation returns a new RunTestCaseOperation from a given name. // The name must be that of a previously created RunTestCaseOperation, possibly from a different process. -func (c *TestCasesClient) RunTestCaseOperation(name string) *RunTestCaseOperation { +func (c *testCasesGRPCClient) RunTestCaseOperation(name string) *RunTestCaseOperation { return &RunTestCaseOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dialogflow/cx/apiv3/test_cases_client_example_test.go b/dialogflow/cx/apiv3/test_cases_client_example_test.go index 8bb04de59cc2..32004b3814ba 100644 --- a/dialogflow/cx/apiv3/test_cases_client_example_test.go +++ b/dialogflow/cx/apiv3/test_cases_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewTestCasesClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleTestCasesClient_ListTestCases() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListTestCasesRequest{ // TODO: Fill request struct fields. @@ -67,6 +67,7 @@ func ExampleTestCasesClient_BatchDeleteTestCases() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.BatchDeleteTestCasesRequest{ // TODO: Fill request struct fields. @@ -78,13 +79,12 @@ func ExampleTestCasesClient_BatchDeleteTestCases() { } func ExampleTestCasesClient_GetTestCase() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetTestCaseRequest{ // TODO: Fill request struct fields. @@ -98,13 +98,12 @@ func ExampleTestCasesClient_GetTestCase() { } func ExampleTestCasesClient_CreateTestCase() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateTestCaseRequest{ // TODO: Fill request struct fields. @@ -118,13 +117,12 @@ func ExampleTestCasesClient_CreateTestCase() { } func ExampleTestCasesClient_UpdateTestCase() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateTestCaseRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleTestCasesClient_UpdateTestCase() { } func ExampleTestCasesClient_RunTestCase() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.RunTestCaseRequest{ // TODO: Fill request struct fields. @@ -163,13 +160,12 @@ func ExampleTestCasesClient_RunTestCase() { } func ExampleTestCasesClient_BatchRunTestCases() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.BatchRunTestCasesRequest{ // TODO: Fill request struct fields. @@ -188,13 +184,12 @@ func ExampleTestCasesClient_BatchRunTestCases() { } func ExampleTestCasesClient_CalculateCoverage() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CalculateCoverageRequest{ // TODO: Fill request struct fields. @@ -208,13 +203,12 @@ func ExampleTestCasesClient_CalculateCoverage() { } func ExampleTestCasesClient_ImportTestCases() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ImportTestCasesRequest{ // TODO: Fill request struct fields. @@ -233,13 +227,12 @@ func ExampleTestCasesClient_ImportTestCases() { } func ExampleTestCasesClient_ExportTestCases() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ExportTestCasesRequest{ // TODO: Fill request struct fields. @@ -258,14 +251,12 @@ func ExampleTestCasesClient_ExportTestCases() { } func ExampleTestCasesClient_ListTestCaseResults() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListTestCaseResultsRequest{ // TODO: Fill request struct fields. @@ -285,13 +276,12 @@ func ExampleTestCasesClient_ListTestCaseResults() { } func ExampleTestCasesClient_GetTestCaseResult() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetTestCaseResultRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3/transition_route_groups_client.go b/dialogflow/cx/apiv3/transition_route_groups_client.go index f86ed37f45a1..feb8542c7fa5 100644 --- a/dialogflow/cx/apiv3/transition_route_groups_client.go +++ b/dialogflow/cx/apiv3/transition_route_groups_client.go @@ -46,7 +46,7 @@ type TransitionRouteGroupsCallOptions struct { DeleteTransitionRouteGroup []gax.CallOption } -func defaultTransitionRouteGroupsClientOptions() []option.ClientOption { +func defaultTransitionRouteGroupsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,103 @@ func defaultTransitionRouteGroupsCallOptions() *TransitionRouteGroupsCallOptions } } +// internalTransitionRouteGroupsClient is an interface that defines the methods availaible from Dialogflow API. +type internalTransitionRouteGroupsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListTransitionRouteGroups(context.Context, *cxpb.ListTransitionRouteGroupsRequest, ...gax.CallOption) *TransitionRouteGroupIterator + GetTransitionRouteGroup(context.Context, *cxpb.GetTransitionRouteGroupRequest, ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) + CreateTransitionRouteGroup(context.Context, *cxpb.CreateTransitionRouteGroupRequest, ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) + UpdateTransitionRouteGroup(context.Context, *cxpb.UpdateTransitionRouteGroupRequest, ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) + DeleteTransitionRouteGroup(context.Context, *cxpb.DeleteTransitionRouteGroupRequest, ...gax.CallOption) error +} + // TransitionRouteGroupsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing TransitionRouteGroups. type TransitionRouteGroupsClient struct { + // The internal transport-dependent client. + internalClient internalTransitionRouteGroupsClient + + // The call options for this service. + CallOptions *TransitionRouteGroupsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *TransitionRouteGroupsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *TransitionRouteGroupsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *TransitionRouteGroupsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListTransitionRouteGroups returns the list of all transition route groups in the specified flow. +func (c *TransitionRouteGroupsClient) ListTransitionRouteGroups(ctx context.Context, req *cxpb.ListTransitionRouteGroupsRequest, opts ...gax.CallOption) *TransitionRouteGroupIterator { + return c.internalClient.ListTransitionRouteGroups(ctx, req, opts...) +} + +// GetTransitionRouteGroup retrieves the specified TransitionRouteGroup. +func (c *TransitionRouteGroupsClient) GetTransitionRouteGroup(ctx context.Context, req *cxpb.GetTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { + return c.internalClient.GetTransitionRouteGroup(ctx, req, opts...) +} + +// CreateTransitionRouteGroup creates an TransitionRouteGroup in the specified flow. +func (c *TransitionRouteGroupsClient) CreateTransitionRouteGroup(ctx context.Context, req *cxpb.CreateTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { + return c.internalClient.CreateTransitionRouteGroup(ctx, req, opts...) +} + +// UpdateTransitionRouteGroup updates the specified TransitionRouteGroup. +func (c *TransitionRouteGroupsClient) UpdateTransitionRouteGroup(ctx context.Context, req *cxpb.UpdateTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { + return c.internalClient.UpdateTransitionRouteGroup(ctx, req, opts...) +} + +// DeleteTransitionRouteGroup deletes the specified TransitionRouteGroup. +func (c *TransitionRouteGroupsClient) DeleteTransitionRouteGroup(ctx context.Context, req *cxpb.DeleteTransitionRouteGroupRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTransitionRouteGroup(ctx, req, opts...) +} + +// transitionRouteGroupsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type transitionRouteGroupsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing TransitionRouteGroupsClient + CallOptions **TransitionRouteGroupsCallOptions + // The gRPC API client. transitionRouteGroupsClient cxpb.TransitionRouteGroupsClient - // The call options for this service. - CallOptions *TransitionRouteGroupsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewTransitionRouteGroupsClient creates a new transition route groups client. +// NewTransitionRouteGroupsClient creates a new transition route groups client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing TransitionRouteGroups. func NewTransitionRouteGroupsClient(ctx context.Context, opts ...option.ClientOption) (*TransitionRouteGroupsClient, error) { - clientOpts := defaultTransitionRouteGroupsClientOptions() - + clientOpts := defaultTransitionRouteGroupsGRPCClientOptions() if newTransitionRouteGroupsClientHook != nil { hookOpts, err := newTransitionRouteGroupsClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,45 +232,47 @@ func NewTransitionRouteGroupsClient(ctx context.Context, opts ...option.ClientOp if err != nil { return nil, err } - c := &TransitionRouteGroupsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultTransitionRouteGroupsCallOptions(), + client := TransitionRouteGroupsClient{CallOptions: defaultTransitionRouteGroupsCallOptions()} + c := &transitionRouteGroupsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, transitionRouteGroupsClient: cxpb.NewTransitionRouteGroupsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *TransitionRouteGroupsClient) Connection() *grpc.ClientConn { +func (c *transitionRouteGroupsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *TransitionRouteGroupsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *TransitionRouteGroupsClient) setGoogleClientInfo(keyval ...string) { +func (c *transitionRouteGroupsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListTransitionRouteGroups returns the list of all transition route groups in the specified flow. -func (c *TransitionRouteGroupsClient) ListTransitionRouteGroups(ctx context.Context, req *cxpb.ListTransitionRouteGroupsRequest, opts ...gax.CallOption) *TransitionRouteGroupIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *transitionRouteGroupsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *transitionRouteGroupsGRPCClient) ListTransitionRouteGroups(ctx context.Context, req *cxpb.ListTransitionRouteGroupsRequest, opts ...gax.CallOption) *TransitionRouteGroupIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTransitionRouteGroups[0:len(c.CallOptions.ListTransitionRouteGroups):len(c.CallOptions.ListTransitionRouteGroups)], opts...) + opts = append((*c.CallOptions).ListTransitionRouteGroups[0:len((*c.CallOptions).ListTransitionRouteGroups):len((*c.CallOptions).ListTransitionRouteGroups)], opts...) it := &TransitionRouteGroupIterator{} req = proto.Clone(req).(*cxpb.ListTransitionRouteGroupsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.TransitionRouteGroup, string, error) { @@ -236,8 +309,7 @@ func (c *TransitionRouteGroupsClient) ListTransitionRouteGroups(ctx context.Cont return it } -// GetTransitionRouteGroup retrieves the specified TransitionRouteGroup. -func (c *TransitionRouteGroupsClient) GetTransitionRouteGroup(ctx context.Context, req *cxpb.GetTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { +func (c *transitionRouteGroupsGRPCClient) GetTransitionRouteGroup(ctx context.Context, req *cxpb.GetTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -245,7 +317,7 @@ func (c *TransitionRouteGroupsClient) GetTransitionRouteGroup(ctx context.Contex } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTransitionRouteGroup[0:len(c.CallOptions.GetTransitionRouteGroup):len(c.CallOptions.GetTransitionRouteGroup)], opts...) + opts = append((*c.CallOptions).GetTransitionRouteGroup[0:len((*c.CallOptions).GetTransitionRouteGroup):len((*c.CallOptions).GetTransitionRouteGroup)], opts...) var resp *cxpb.TransitionRouteGroup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -258,8 +330,7 @@ func (c *TransitionRouteGroupsClient) GetTransitionRouteGroup(ctx context.Contex return resp, nil } -// CreateTransitionRouteGroup creates an TransitionRouteGroup in the specified flow. -func (c *TransitionRouteGroupsClient) CreateTransitionRouteGroup(ctx context.Context, req *cxpb.CreateTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { +func (c *transitionRouteGroupsGRPCClient) CreateTransitionRouteGroup(ctx context.Context, req *cxpb.CreateTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -267,7 +338,7 @@ func (c *TransitionRouteGroupsClient) CreateTransitionRouteGroup(ctx context.Con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTransitionRouteGroup[0:len(c.CallOptions.CreateTransitionRouteGroup):len(c.CallOptions.CreateTransitionRouteGroup)], opts...) + opts = append((*c.CallOptions).CreateTransitionRouteGroup[0:len((*c.CallOptions).CreateTransitionRouteGroup):len((*c.CallOptions).CreateTransitionRouteGroup)], opts...) var resp *cxpb.TransitionRouteGroup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -280,8 +351,7 @@ func (c *TransitionRouteGroupsClient) CreateTransitionRouteGroup(ctx context.Con return resp, nil } -// UpdateTransitionRouteGroup updates the specified TransitionRouteGroup. -func (c *TransitionRouteGroupsClient) UpdateTransitionRouteGroup(ctx context.Context, req *cxpb.UpdateTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { +func (c *transitionRouteGroupsGRPCClient) UpdateTransitionRouteGroup(ctx context.Context, req *cxpb.UpdateTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -289,7 +359,7 @@ func (c *TransitionRouteGroupsClient) UpdateTransitionRouteGroup(ctx context.Con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "transition_route_group.name", url.QueryEscape(req.GetTransitionRouteGroup().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTransitionRouteGroup[0:len(c.CallOptions.UpdateTransitionRouteGroup):len(c.CallOptions.UpdateTransitionRouteGroup)], opts...) + opts = append((*c.CallOptions).UpdateTransitionRouteGroup[0:len((*c.CallOptions).UpdateTransitionRouteGroup):len((*c.CallOptions).UpdateTransitionRouteGroup)], opts...) var resp *cxpb.TransitionRouteGroup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -302,8 +372,7 @@ func (c *TransitionRouteGroupsClient) UpdateTransitionRouteGroup(ctx context.Con return resp, nil } -// DeleteTransitionRouteGroup deletes the specified TransitionRouteGroup. -func (c *TransitionRouteGroupsClient) DeleteTransitionRouteGroup(ctx context.Context, req *cxpb.DeleteTransitionRouteGroupRequest, opts ...gax.CallOption) error { +func (c *transitionRouteGroupsGRPCClient) DeleteTransitionRouteGroup(ctx context.Context, req *cxpb.DeleteTransitionRouteGroupRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -311,7 +380,7 @@ func (c *TransitionRouteGroupsClient) DeleteTransitionRouteGroup(ctx context.Con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTransitionRouteGroup[0:len(c.CallOptions.DeleteTransitionRouteGroup):len(c.CallOptions.DeleteTransitionRouteGroup)], opts...) + opts = append((*c.CallOptions).DeleteTransitionRouteGroup[0:len((*c.CallOptions).DeleteTransitionRouteGroup):len((*c.CallOptions).DeleteTransitionRouteGroup)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.transitionRouteGroupsClient.DeleteTransitionRouteGroup(ctx, req, settings.GRPC...) diff --git a/dialogflow/cx/apiv3/transition_route_groups_client_example_test.go b/dialogflow/cx/apiv3/transition_route_groups_client_example_test.go index 85f3407396bb..89ad4f9cecf0 100644 --- a/dialogflow/cx/apiv3/transition_route_groups_client_example_test.go +++ b/dialogflow/cx/apiv3/transition_route_groups_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewTransitionRouteGroupsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleTransitionRouteGroupsClient_ListTransitionRouteGroups() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewTransitionRouteGroupsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListTransitionRouteGroupsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleTransitionRouteGroupsClient_ListTransitionRouteGroups() { } func ExampleTransitionRouteGroupsClient_GetTransitionRouteGroup() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTransitionRouteGroupsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetTransitionRouteGroupRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleTransitionRouteGroupsClient_GetTransitionRouteGroup() { } func ExampleTransitionRouteGroupsClient_CreateTransitionRouteGroup() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTransitionRouteGroupsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateTransitionRouteGroupRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleTransitionRouteGroupsClient_CreateTransitionRouteGroup() { } func ExampleTransitionRouteGroupsClient_UpdateTransitionRouteGroup() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTransitionRouteGroupsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateTransitionRouteGroupRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleTransitionRouteGroupsClient_DeleteTransitionRouteGroup() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteTransitionRouteGroupRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3/versions_client.go b/dialogflow/cx/apiv3/versions_client.go index eac23065b86b..42c61e9bf40a 100644 --- a/dialogflow/cx/apiv3/versions_client.go +++ b/dialogflow/cx/apiv3/versions_client.go @@ -51,7 +51,7 @@ type VersionsCallOptions struct { LoadVersion []gax.CallOption } -func defaultVersionsClientOptions() []option.ClientOption { +func defaultVersionsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -134,37 +134,133 @@ func defaultVersionsCallOptions() *VersionsCallOptions { } } +// internalVersionsClient is an interface that defines the methods availaible from Dialogflow API. +type internalVersionsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListVersions(context.Context, *cxpb.ListVersionsRequest, ...gax.CallOption) *VersionIterator + GetVersion(context.Context, *cxpb.GetVersionRequest, ...gax.CallOption) (*cxpb.Version, error) + CreateVersion(context.Context, *cxpb.CreateVersionRequest, ...gax.CallOption) (*CreateVersionOperation, error) + CreateVersionOperation(name string) *CreateVersionOperation + UpdateVersion(context.Context, *cxpb.UpdateVersionRequest, ...gax.CallOption) (*cxpb.Version, error) + DeleteVersion(context.Context, *cxpb.DeleteVersionRequest, ...gax.CallOption) error + LoadVersion(context.Context, *cxpb.LoadVersionRequest, ...gax.CallOption) (*LoadVersionOperation, error) + LoadVersionOperation(name string) *LoadVersionOperation +} + // VersionsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Versions. type VersionsClient struct { + // The internal transport-dependent client. + internalClient internalVersionsClient + + // The call options for this service. + CallOptions *VersionsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *VersionsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *VersionsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *VersionsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListVersions returns the list of all versions in the specified Flow. +func (c *VersionsClient) ListVersions(ctx context.Context, req *cxpb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { + return c.internalClient.ListVersions(ctx, req, opts...) +} + +// GetVersion retrieves the specified Version. +func (c *VersionsClient) GetVersion(ctx context.Context, req *cxpb.GetVersionRequest, opts ...gax.CallOption) (*cxpb.Version, error) { + return c.internalClient.GetVersion(ctx, req, opts...) +} + +// CreateVersion creates a Version in the specified Flow. +func (c *VersionsClient) CreateVersion(ctx context.Context, req *cxpb.CreateVersionRequest, opts ...gax.CallOption) (*CreateVersionOperation, error) { + return c.internalClient.CreateVersion(ctx, req, opts...) +} + +// CreateVersionOperation returns a new CreateVersionOperation from a given name. +// The name must be that of a previously created CreateVersionOperation, possibly from a different process. +func (c *VersionsClient) CreateVersionOperation(name string) *CreateVersionOperation { + return c.internalClient.CreateVersionOperation(name) +} + +// UpdateVersion updates the specified Version. +func (c *VersionsClient) UpdateVersion(ctx context.Context, req *cxpb.UpdateVersionRequest, opts ...gax.CallOption) (*cxpb.Version, error) { + return c.internalClient.UpdateVersion(ctx, req, opts...) +} + +// DeleteVersion deletes the specified Version. +func (c *VersionsClient) DeleteVersion(ctx context.Context, req *cxpb.DeleteVersionRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteVersion(ctx, req, opts...) +} + +// LoadVersion loads resources in the specified version to the draft flow. +func (c *VersionsClient) LoadVersion(ctx context.Context, req *cxpb.LoadVersionRequest, opts ...gax.CallOption) (*LoadVersionOperation, error) { + return c.internalClient.LoadVersion(ctx, req, opts...) +} + +// LoadVersionOperation returns a new LoadVersionOperation from a given name. +// The name must be that of a previously created LoadVersionOperation, possibly from a different process. +func (c *VersionsClient) LoadVersionOperation(name string) *LoadVersionOperation { + return c.internalClient.LoadVersionOperation(name) +} + +// versionsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type versionsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing VersionsClient + CallOptions **VersionsCallOptions + // The gRPC API client. versionsClient cxpb.VersionsClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *VersionsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewVersionsClient creates a new versions client. +// NewVersionsClient creates a new versions client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Versions. func NewVersionsClient(ctx context.Context, opts ...option.ClientOption) (*VersionsClient, error) { - clientOpts := defaultVersionsClientOptions() - + clientOpts := defaultVersionsGRPCClientOptions() if newVersionsClientHook != nil { hookOpts, err := newVersionsClientHook(ctx, clientHookParams{}) if err != nil { @@ -182,16 +278,19 @@ func NewVersionsClient(ctx context.Context, opts ...option.ClientOption) (*Versi if err != nil { return nil, err } - c := &VersionsClient{ + client := VersionsClient{CallOptions: defaultVersionsCallOptions()} + + c := &versionsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultVersionsCallOptions(), - - versionsClient: cxpb.NewVersionsClient(connPool), + versionsClient: cxpb.NewVersionsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -201,36 +300,36 @@ func NewVersionsClient(ctx context.Context, opts ...option.ClientOption) (*Versi // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *VersionsClient) Connection() *grpc.ClientConn { +func (c *versionsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *VersionsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *VersionsClient) setGoogleClientInfo(keyval ...string) { +func (c *versionsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListVersions returns the list of all versions in the specified Flow. -func (c *VersionsClient) ListVersions(ctx context.Context, req *cxpb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *versionsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *versionsGRPCClient) ListVersions(ctx context.Context, req *cxpb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListVersions[0:len(c.CallOptions.ListVersions):len(c.CallOptions.ListVersions)], opts...) + opts = append((*c.CallOptions).ListVersions[0:len((*c.CallOptions).ListVersions):len((*c.CallOptions).ListVersions)], opts...) it := &VersionIterator{} req = proto.Clone(req).(*cxpb.ListVersionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Version, string, error) { @@ -267,8 +366,7 @@ func (c *VersionsClient) ListVersions(ctx context.Context, req *cxpb.ListVersion return it } -// GetVersion retrieves the specified Version. -func (c *VersionsClient) GetVersion(ctx context.Context, req *cxpb.GetVersionRequest, opts ...gax.CallOption) (*cxpb.Version, error) { +func (c *versionsGRPCClient) GetVersion(ctx context.Context, req *cxpb.GetVersionRequest, opts ...gax.CallOption) (*cxpb.Version, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -276,7 +374,7 @@ func (c *VersionsClient) GetVersion(ctx context.Context, req *cxpb.GetVersionReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetVersion[0:len(c.CallOptions.GetVersion):len(c.CallOptions.GetVersion)], opts...) + opts = append((*c.CallOptions).GetVersion[0:len((*c.CallOptions).GetVersion):len((*c.CallOptions).GetVersion)], opts...) var resp *cxpb.Version err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -289,8 +387,7 @@ func (c *VersionsClient) GetVersion(ctx context.Context, req *cxpb.GetVersionReq return resp, nil } -// CreateVersion creates a Version in the specified Flow. -func (c *VersionsClient) CreateVersion(ctx context.Context, req *cxpb.CreateVersionRequest, opts ...gax.CallOption) (*CreateVersionOperation, error) { +func (c *versionsGRPCClient) CreateVersion(ctx context.Context, req *cxpb.CreateVersionRequest, opts ...gax.CallOption) (*CreateVersionOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -298,7 +395,7 @@ func (c *VersionsClient) CreateVersion(ctx context.Context, req *cxpb.CreateVers } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateVersion[0:len(c.CallOptions.CreateVersion):len(c.CallOptions.CreateVersion)], opts...) + opts = append((*c.CallOptions).CreateVersion[0:len((*c.CallOptions).CreateVersion):len((*c.CallOptions).CreateVersion)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -309,12 +406,11 @@ func (c *VersionsClient) CreateVersion(ctx context.Context, req *cxpb.CreateVers return nil, err } return &CreateVersionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateVersion updates the specified Version. -func (c *VersionsClient) UpdateVersion(ctx context.Context, req *cxpb.UpdateVersionRequest, opts ...gax.CallOption) (*cxpb.Version, error) { +func (c *versionsGRPCClient) UpdateVersion(ctx context.Context, req *cxpb.UpdateVersionRequest, opts ...gax.CallOption) (*cxpb.Version, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -322,7 +418,7 @@ func (c *VersionsClient) UpdateVersion(ctx context.Context, req *cxpb.UpdateVers } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "version.name", url.QueryEscape(req.GetVersion().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateVersion[0:len(c.CallOptions.UpdateVersion):len(c.CallOptions.UpdateVersion)], opts...) + opts = append((*c.CallOptions).UpdateVersion[0:len((*c.CallOptions).UpdateVersion):len((*c.CallOptions).UpdateVersion)], opts...) var resp *cxpb.Version err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -335,8 +431,7 @@ func (c *VersionsClient) UpdateVersion(ctx context.Context, req *cxpb.UpdateVers return resp, nil } -// DeleteVersion deletes the specified Version. -func (c *VersionsClient) DeleteVersion(ctx context.Context, req *cxpb.DeleteVersionRequest, opts ...gax.CallOption) error { +func (c *versionsGRPCClient) DeleteVersion(ctx context.Context, req *cxpb.DeleteVersionRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -344,7 +439,7 @@ func (c *VersionsClient) DeleteVersion(ctx context.Context, req *cxpb.DeleteVers } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteVersion[0:len(c.CallOptions.DeleteVersion):len(c.CallOptions.DeleteVersion)], opts...) + opts = append((*c.CallOptions).DeleteVersion[0:len((*c.CallOptions).DeleteVersion):len((*c.CallOptions).DeleteVersion)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.versionsClient.DeleteVersion(ctx, req, settings.GRPC...) @@ -353,8 +448,7 @@ func (c *VersionsClient) DeleteVersion(ctx context.Context, req *cxpb.DeleteVers return err } -// LoadVersion loads resources in the specified version to the draft flow. -func (c *VersionsClient) LoadVersion(ctx context.Context, req *cxpb.LoadVersionRequest, opts ...gax.CallOption) (*LoadVersionOperation, error) { +func (c *versionsGRPCClient) LoadVersion(ctx context.Context, req *cxpb.LoadVersionRequest, opts ...gax.CallOption) (*LoadVersionOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -362,7 +456,7 @@ func (c *VersionsClient) LoadVersion(ctx context.Context, req *cxpb.LoadVersionR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.LoadVersion[0:len(c.CallOptions.LoadVersion):len(c.CallOptions.LoadVersion)], opts...) + opts = append((*c.CallOptions).LoadVersion[0:len((*c.CallOptions).LoadVersion):len((*c.CallOptions).LoadVersion)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -373,7 +467,7 @@ func (c *VersionsClient) LoadVersion(ctx context.Context, req *cxpb.LoadVersionR return nil, err } return &LoadVersionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -384,9 +478,9 @@ type CreateVersionOperation struct { // CreateVersionOperation returns a new CreateVersionOperation from a given name. // The name must be that of a previously created CreateVersionOperation, possibly from a different process. -func (c *VersionsClient) CreateVersionOperation(name string) *CreateVersionOperation { +func (c *versionsGRPCClient) CreateVersionOperation(name string) *CreateVersionOperation { return &CreateVersionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -453,9 +547,9 @@ type LoadVersionOperation struct { // LoadVersionOperation returns a new LoadVersionOperation from a given name. // The name must be that of a previously created LoadVersionOperation, possibly from a different process. -func (c *VersionsClient) LoadVersionOperation(name string) *LoadVersionOperation { +func (c *versionsGRPCClient) LoadVersionOperation(name string) *LoadVersionOperation { return &LoadVersionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dialogflow/cx/apiv3/versions_client_example_test.go b/dialogflow/cx/apiv3/versions_client_example_test.go index fe0503014f2f..9b9d1210146e 100644 --- a/dialogflow/cx/apiv3/versions_client_example_test.go +++ b/dialogflow/cx/apiv3/versions_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewVersionsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleVersionsClient_ListVersions() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListVersionsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleVersionsClient_ListVersions() { } func ExampleVersionsClient_GetVersion() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetVersionRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleVersionsClient_GetVersion() { } func ExampleVersionsClient_CreateVersion() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateVersionRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleVersionsClient_CreateVersion() { } func ExampleVersionsClient_UpdateVersion() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateVersionRequest{ // TODO: Fill request struct fields. @@ -132,6 +129,7 @@ func ExampleVersionsClient_DeleteVersion() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteVersionRequest{ // TODO: Fill request struct fields. @@ -143,13 +141,12 @@ func ExampleVersionsClient_DeleteVersion() { } func ExampleVersionsClient_LoadVersion() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.LoadVersionRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3/webhooks_client.go b/dialogflow/cx/apiv3/webhooks_client.go index 475468a4fdf1..22de97123c11 100644 --- a/dialogflow/cx/apiv3/webhooks_client.go +++ b/dialogflow/cx/apiv3/webhooks_client.go @@ -46,7 +46,7 @@ type WebhooksCallOptions struct { DeleteWebhook []gax.CallOption } -func defaultWebhooksClientOptions() []option.ClientOption { +func defaultWebhooksGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,103 @@ func defaultWebhooksCallOptions() *WebhooksCallOptions { } } +// internalWebhooksClient is an interface that defines the methods availaible from Dialogflow API. +type internalWebhooksClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListWebhooks(context.Context, *cxpb.ListWebhooksRequest, ...gax.CallOption) *WebhookIterator + GetWebhook(context.Context, *cxpb.GetWebhookRequest, ...gax.CallOption) (*cxpb.Webhook, error) + CreateWebhook(context.Context, *cxpb.CreateWebhookRequest, ...gax.CallOption) (*cxpb.Webhook, error) + UpdateWebhook(context.Context, *cxpb.UpdateWebhookRequest, ...gax.CallOption) (*cxpb.Webhook, error) + DeleteWebhook(context.Context, *cxpb.DeleteWebhookRequest, ...gax.CallOption) error +} + // WebhooksClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Webhooks. type WebhooksClient struct { + // The internal transport-dependent client. + internalClient internalWebhooksClient + + // The call options for this service. + CallOptions *WebhooksCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *WebhooksClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *WebhooksClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *WebhooksClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListWebhooks returns the list of all webhooks in the specified agent. +func (c *WebhooksClient) ListWebhooks(ctx context.Context, req *cxpb.ListWebhooksRequest, opts ...gax.CallOption) *WebhookIterator { + return c.internalClient.ListWebhooks(ctx, req, opts...) +} + +// GetWebhook retrieves the specified webhook. +func (c *WebhooksClient) GetWebhook(ctx context.Context, req *cxpb.GetWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { + return c.internalClient.GetWebhook(ctx, req, opts...) +} + +// CreateWebhook creates a webhook in the specified agent. +func (c *WebhooksClient) CreateWebhook(ctx context.Context, req *cxpb.CreateWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { + return c.internalClient.CreateWebhook(ctx, req, opts...) +} + +// UpdateWebhook updates the specified webhook. +func (c *WebhooksClient) UpdateWebhook(ctx context.Context, req *cxpb.UpdateWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { + return c.internalClient.UpdateWebhook(ctx, req, opts...) +} + +// DeleteWebhook deletes the specified webhook. +func (c *WebhooksClient) DeleteWebhook(ctx context.Context, req *cxpb.DeleteWebhookRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteWebhook(ctx, req, opts...) +} + +// webhooksGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type webhooksGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing WebhooksClient + CallOptions **WebhooksCallOptions + // The gRPC API client. webhooksClient cxpb.WebhooksClient - // The call options for this service. - CallOptions *WebhooksCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewWebhooksClient creates a new webhooks client. +// NewWebhooksClient creates a new webhooks client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Webhooks. func NewWebhooksClient(ctx context.Context, opts ...option.ClientOption) (*WebhooksClient, error) { - clientOpts := defaultWebhooksClientOptions() - + clientOpts := defaultWebhooksGRPCClientOptions() if newWebhooksClientHook != nil { hookOpts, err := newWebhooksClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,45 +232,47 @@ func NewWebhooksClient(ctx context.Context, opts ...option.ClientOption) (*Webho if err != nil { return nil, err } - c := &WebhooksClient{ + client := WebhooksClient{CallOptions: defaultWebhooksCallOptions()} + + c := &webhooksGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultWebhooksCallOptions(), - - webhooksClient: cxpb.NewWebhooksClient(connPool), + webhooksClient: cxpb.NewWebhooksClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *WebhooksClient) Connection() *grpc.ClientConn { +func (c *webhooksGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *WebhooksClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *WebhooksClient) setGoogleClientInfo(keyval ...string) { +func (c *webhooksGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListWebhooks returns the list of all webhooks in the specified agent. -func (c *WebhooksClient) ListWebhooks(ctx context.Context, req *cxpb.ListWebhooksRequest, opts ...gax.CallOption) *WebhookIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *webhooksGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *webhooksGRPCClient) ListWebhooks(ctx context.Context, req *cxpb.ListWebhooksRequest, opts ...gax.CallOption) *WebhookIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListWebhooks[0:len(c.CallOptions.ListWebhooks):len(c.CallOptions.ListWebhooks)], opts...) + opts = append((*c.CallOptions).ListWebhooks[0:len((*c.CallOptions).ListWebhooks):len((*c.CallOptions).ListWebhooks)], opts...) it := &WebhookIterator{} req = proto.Clone(req).(*cxpb.ListWebhooksRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Webhook, string, error) { @@ -236,8 +309,7 @@ func (c *WebhooksClient) ListWebhooks(ctx context.Context, req *cxpb.ListWebhook return it } -// GetWebhook retrieves the specified webhook. -func (c *WebhooksClient) GetWebhook(ctx context.Context, req *cxpb.GetWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { +func (c *webhooksGRPCClient) GetWebhook(ctx context.Context, req *cxpb.GetWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -245,7 +317,7 @@ func (c *WebhooksClient) GetWebhook(ctx context.Context, req *cxpb.GetWebhookReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetWebhook[0:len(c.CallOptions.GetWebhook):len(c.CallOptions.GetWebhook)], opts...) + opts = append((*c.CallOptions).GetWebhook[0:len((*c.CallOptions).GetWebhook):len((*c.CallOptions).GetWebhook)], opts...) var resp *cxpb.Webhook err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -258,8 +330,7 @@ func (c *WebhooksClient) GetWebhook(ctx context.Context, req *cxpb.GetWebhookReq return resp, nil } -// CreateWebhook creates a webhook in the specified agent. -func (c *WebhooksClient) CreateWebhook(ctx context.Context, req *cxpb.CreateWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { +func (c *webhooksGRPCClient) CreateWebhook(ctx context.Context, req *cxpb.CreateWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -267,7 +338,7 @@ func (c *WebhooksClient) CreateWebhook(ctx context.Context, req *cxpb.CreateWebh } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateWebhook[0:len(c.CallOptions.CreateWebhook):len(c.CallOptions.CreateWebhook)], opts...) + opts = append((*c.CallOptions).CreateWebhook[0:len((*c.CallOptions).CreateWebhook):len((*c.CallOptions).CreateWebhook)], opts...) var resp *cxpb.Webhook err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -280,8 +351,7 @@ func (c *WebhooksClient) CreateWebhook(ctx context.Context, req *cxpb.CreateWebh return resp, nil } -// UpdateWebhook updates the specified webhook. -func (c *WebhooksClient) UpdateWebhook(ctx context.Context, req *cxpb.UpdateWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { +func (c *webhooksGRPCClient) UpdateWebhook(ctx context.Context, req *cxpb.UpdateWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -289,7 +359,7 @@ func (c *WebhooksClient) UpdateWebhook(ctx context.Context, req *cxpb.UpdateWebh } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "webhook.name", url.QueryEscape(req.GetWebhook().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateWebhook[0:len(c.CallOptions.UpdateWebhook):len(c.CallOptions.UpdateWebhook)], opts...) + opts = append((*c.CallOptions).UpdateWebhook[0:len((*c.CallOptions).UpdateWebhook):len((*c.CallOptions).UpdateWebhook)], opts...) var resp *cxpb.Webhook err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -302,8 +372,7 @@ func (c *WebhooksClient) UpdateWebhook(ctx context.Context, req *cxpb.UpdateWebh return resp, nil } -// DeleteWebhook deletes the specified webhook. -func (c *WebhooksClient) DeleteWebhook(ctx context.Context, req *cxpb.DeleteWebhookRequest, opts ...gax.CallOption) error { +func (c *webhooksGRPCClient) DeleteWebhook(ctx context.Context, req *cxpb.DeleteWebhookRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -311,7 +380,7 @@ func (c *WebhooksClient) DeleteWebhook(ctx context.Context, req *cxpb.DeleteWebh } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteWebhook[0:len(c.CallOptions.DeleteWebhook):len(c.CallOptions.DeleteWebhook)], opts...) + opts = append((*c.CallOptions).DeleteWebhook[0:len((*c.CallOptions).DeleteWebhook):len((*c.CallOptions).DeleteWebhook)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.webhooksClient.DeleteWebhook(ctx, req, settings.GRPC...) diff --git a/dialogflow/cx/apiv3/webhooks_client_example_test.go b/dialogflow/cx/apiv3/webhooks_client_example_test.go index 930bc1d3ee5c..ab4142d2c60b 100644 --- a/dialogflow/cx/apiv3/webhooks_client_example_test.go +++ b/dialogflow/cx/apiv3/webhooks_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewWebhooksClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleWebhooksClient_ListWebhooks() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewWebhooksClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListWebhooksRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleWebhooksClient_ListWebhooks() { } func ExampleWebhooksClient_GetWebhook() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewWebhooksClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetWebhookRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleWebhooksClient_GetWebhook() { } func ExampleWebhooksClient_CreateWebhook() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewWebhooksClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateWebhookRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleWebhooksClient_CreateWebhook() { } func ExampleWebhooksClient_UpdateWebhook() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewWebhooksClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateWebhookRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleWebhooksClient_DeleteWebhook() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteWebhookRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3beta1/agents_client.go b/dialogflow/cx/apiv3beta1/agents_client.go index fc6ba2d0a5ec..e98382e5dcba 100644 --- a/dialogflow/cx/apiv3beta1/agents_client.go +++ b/dialogflow/cx/apiv3beta1/agents_client.go @@ -54,7 +54,7 @@ type AgentsCallOptions struct { GetAgentValidationResult []gax.CallOption } -func defaultAgentsClientOptions() []option.ClientOption { +func defaultAgentsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -170,37 +170,157 @@ func defaultAgentsCallOptions() *AgentsCallOptions { } } +// internalAgentsClient is an interface that defines the methods availaible from Dialogflow API. +type internalAgentsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListAgents(context.Context, *cxpb.ListAgentsRequest, ...gax.CallOption) *AgentIterator + GetAgent(context.Context, *cxpb.GetAgentRequest, ...gax.CallOption) (*cxpb.Agent, error) + CreateAgent(context.Context, *cxpb.CreateAgentRequest, ...gax.CallOption) (*cxpb.Agent, error) + UpdateAgent(context.Context, *cxpb.UpdateAgentRequest, ...gax.CallOption) (*cxpb.Agent, error) + DeleteAgent(context.Context, *cxpb.DeleteAgentRequest, ...gax.CallOption) error + ExportAgent(context.Context, *cxpb.ExportAgentRequest, ...gax.CallOption) (*ExportAgentOperation, error) + ExportAgentOperation(name string) *ExportAgentOperation + RestoreAgent(context.Context, *cxpb.RestoreAgentRequest, ...gax.CallOption) (*RestoreAgentOperation, error) + RestoreAgentOperation(name string) *RestoreAgentOperation + ValidateAgent(context.Context, *cxpb.ValidateAgentRequest, ...gax.CallOption) (*cxpb.AgentValidationResult, error) + GetAgentValidationResult(context.Context, *cxpb.GetAgentValidationResultRequest, ...gax.CallOption) (*cxpb.AgentValidationResult, error) +} + // AgentsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Agents. type AgentsClient struct { + // The internal transport-dependent client. + internalClient internalAgentsClient + + // The call options for this service. + CallOptions *AgentsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *AgentsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *AgentsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *AgentsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListAgents returns the list of all agents in the specified location. +func (c *AgentsClient) ListAgents(ctx context.Context, req *cxpb.ListAgentsRequest, opts ...gax.CallOption) *AgentIterator { + return c.internalClient.ListAgents(ctx, req, opts...) +} + +// GetAgent retrieves the specified agent. +func (c *AgentsClient) GetAgent(ctx context.Context, req *cxpb.GetAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { + return c.internalClient.GetAgent(ctx, req, opts...) +} + +// CreateAgent creates an agent in the specified location. +func (c *AgentsClient) CreateAgent(ctx context.Context, req *cxpb.CreateAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { + return c.internalClient.CreateAgent(ctx, req, opts...) +} + +// UpdateAgent updates the specified agent. +func (c *AgentsClient) UpdateAgent(ctx context.Context, req *cxpb.UpdateAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { + return c.internalClient.UpdateAgent(ctx, req, opts...) +} + +// DeleteAgent deletes the specified agent. +func (c *AgentsClient) DeleteAgent(ctx context.Context, req *cxpb.DeleteAgentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteAgent(ctx, req, opts...) +} + +// ExportAgent exports the specified agent to a binary file. +func (c *AgentsClient) ExportAgent(ctx context.Context, req *cxpb.ExportAgentRequest, opts ...gax.CallOption) (*ExportAgentOperation, error) { + return c.internalClient.ExportAgent(ctx, req, opts...) +} + +// ExportAgentOperation returns a new ExportAgentOperation from a given name. +// The name must be that of a previously created ExportAgentOperation, possibly from a different process. +func (c *AgentsClient) ExportAgentOperation(name string) *ExportAgentOperation { + return c.internalClient.ExportAgentOperation(name) +} + +// RestoreAgent restores the specified agent from a binary file. +// +// Replaces the current agent with a new one. Note that all existing resources +// in agent (e.g. intents, entity types, flows) will be removed. +func (c *AgentsClient) RestoreAgent(ctx context.Context, req *cxpb.RestoreAgentRequest, opts ...gax.CallOption) (*RestoreAgentOperation, error) { + return c.internalClient.RestoreAgent(ctx, req, opts...) +} + +// RestoreAgentOperation returns a new RestoreAgentOperation from a given name. +// The name must be that of a previously created RestoreAgentOperation, possibly from a different process. +func (c *AgentsClient) RestoreAgentOperation(name string) *RestoreAgentOperation { + return c.internalClient.RestoreAgentOperation(name) +} + +// ValidateAgent validates the specified agent and creates or updates validation results. +// The agent in draft version is validated. Please call this API after the +// training is completed to get the complete validation results. +func (c *AgentsClient) ValidateAgent(ctx context.Context, req *cxpb.ValidateAgentRequest, opts ...gax.CallOption) (*cxpb.AgentValidationResult, error) { + return c.internalClient.ValidateAgent(ctx, req, opts...) +} + +// GetAgentValidationResult gets the latest agent validation result. Agent validation is performed +// when ValidateAgent is called. +func (c *AgentsClient) GetAgentValidationResult(ctx context.Context, req *cxpb.GetAgentValidationResultRequest, opts ...gax.CallOption) (*cxpb.AgentValidationResult, error) { + return c.internalClient.GetAgentValidationResult(ctx, req, opts...) +} + +// agentsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type agentsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing AgentsClient + CallOptions **AgentsCallOptions + // The gRPC API client. agentsClient cxpb.AgentsClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *AgentsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewAgentsClient creates a new agents client. +// NewAgentsClient creates a new agents client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Agents. func NewAgentsClient(ctx context.Context, opts ...option.ClientOption) (*AgentsClient, error) { - clientOpts := defaultAgentsClientOptions() - + clientOpts := defaultAgentsGRPCClientOptions() if newAgentsClientHook != nil { hookOpts, err := newAgentsClientHook(ctx, clientHookParams{}) if err != nil { @@ -218,16 +338,19 @@ func NewAgentsClient(ctx context.Context, opts ...option.ClientOption) (*AgentsC if err != nil { return nil, err } - c := &AgentsClient{ + client := AgentsClient{CallOptions: defaultAgentsCallOptions()} + + c := &agentsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultAgentsCallOptions(), - - agentsClient: cxpb.NewAgentsClient(connPool), + agentsClient: cxpb.NewAgentsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -237,36 +360,36 @@ func NewAgentsClient(ctx context.Context, opts ...option.ClientOption) (*AgentsC // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *AgentsClient) Connection() *grpc.ClientConn { +func (c *agentsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *AgentsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *AgentsClient) setGoogleClientInfo(keyval ...string) { +func (c *agentsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListAgents returns the list of all agents in the specified location. -func (c *AgentsClient) ListAgents(ctx context.Context, req *cxpb.ListAgentsRequest, opts ...gax.CallOption) *AgentIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *agentsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *agentsGRPCClient) ListAgents(ctx context.Context, req *cxpb.ListAgentsRequest, opts ...gax.CallOption) *AgentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAgents[0:len(c.CallOptions.ListAgents):len(c.CallOptions.ListAgents)], opts...) + opts = append((*c.CallOptions).ListAgents[0:len((*c.CallOptions).ListAgents):len((*c.CallOptions).ListAgents)], opts...) it := &AgentIterator{} req = proto.Clone(req).(*cxpb.ListAgentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Agent, string, error) { @@ -303,8 +426,7 @@ func (c *AgentsClient) ListAgents(ctx context.Context, req *cxpb.ListAgentsReque return it } -// GetAgent retrieves the specified agent. -func (c *AgentsClient) GetAgent(ctx context.Context, req *cxpb.GetAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { +func (c *agentsGRPCClient) GetAgent(ctx context.Context, req *cxpb.GetAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -312,7 +434,7 @@ func (c *AgentsClient) GetAgent(ctx context.Context, req *cxpb.GetAgentRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetAgent[0:len(c.CallOptions.GetAgent):len(c.CallOptions.GetAgent)], opts...) + opts = append((*c.CallOptions).GetAgent[0:len((*c.CallOptions).GetAgent):len((*c.CallOptions).GetAgent)], opts...) var resp *cxpb.Agent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -325,8 +447,7 @@ func (c *AgentsClient) GetAgent(ctx context.Context, req *cxpb.GetAgentRequest, return resp, nil } -// CreateAgent creates an agent in the specified location. -func (c *AgentsClient) CreateAgent(ctx context.Context, req *cxpb.CreateAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { +func (c *agentsGRPCClient) CreateAgent(ctx context.Context, req *cxpb.CreateAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -334,7 +455,7 @@ func (c *AgentsClient) CreateAgent(ctx context.Context, req *cxpb.CreateAgentReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateAgent[0:len(c.CallOptions.CreateAgent):len(c.CallOptions.CreateAgent)], opts...) + opts = append((*c.CallOptions).CreateAgent[0:len((*c.CallOptions).CreateAgent):len((*c.CallOptions).CreateAgent)], opts...) var resp *cxpb.Agent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -347,8 +468,7 @@ func (c *AgentsClient) CreateAgent(ctx context.Context, req *cxpb.CreateAgentReq return resp, nil } -// UpdateAgent updates the specified agent. -func (c *AgentsClient) UpdateAgent(ctx context.Context, req *cxpb.UpdateAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { +func (c *agentsGRPCClient) UpdateAgent(ctx context.Context, req *cxpb.UpdateAgentRequest, opts ...gax.CallOption) (*cxpb.Agent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -356,7 +476,7 @@ func (c *AgentsClient) UpdateAgent(ctx context.Context, req *cxpb.UpdateAgentReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "agent.name", url.QueryEscape(req.GetAgent().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateAgent[0:len(c.CallOptions.UpdateAgent):len(c.CallOptions.UpdateAgent)], opts...) + opts = append((*c.CallOptions).UpdateAgent[0:len((*c.CallOptions).UpdateAgent):len((*c.CallOptions).UpdateAgent)], opts...) var resp *cxpb.Agent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -369,8 +489,7 @@ func (c *AgentsClient) UpdateAgent(ctx context.Context, req *cxpb.UpdateAgentReq return resp, nil } -// DeleteAgent deletes the specified agent. -func (c *AgentsClient) DeleteAgent(ctx context.Context, req *cxpb.DeleteAgentRequest, opts ...gax.CallOption) error { +func (c *agentsGRPCClient) DeleteAgent(ctx context.Context, req *cxpb.DeleteAgentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -378,7 +497,7 @@ func (c *AgentsClient) DeleteAgent(ctx context.Context, req *cxpb.DeleteAgentReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteAgent[0:len(c.CallOptions.DeleteAgent):len(c.CallOptions.DeleteAgent)], opts...) + opts = append((*c.CallOptions).DeleteAgent[0:len((*c.CallOptions).DeleteAgent):len((*c.CallOptions).DeleteAgent)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.agentsClient.DeleteAgent(ctx, req, settings.GRPC...) @@ -387,8 +506,7 @@ func (c *AgentsClient) DeleteAgent(ctx context.Context, req *cxpb.DeleteAgentReq return err } -// ExportAgent exports the specified agent to a binary file. -func (c *AgentsClient) ExportAgent(ctx context.Context, req *cxpb.ExportAgentRequest, opts ...gax.CallOption) (*ExportAgentOperation, error) { +func (c *agentsGRPCClient) ExportAgent(ctx context.Context, req *cxpb.ExportAgentRequest, opts ...gax.CallOption) (*ExportAgentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -396,7 +514,7 @@ func (c *AgentsClient) ExportAgent(ctx context.Context, req *cxpb.ExportAgentReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportAgent[0:len(c.CallOptions.ExportAgent):len(c.CallOptions.ExportAgent)], opts...) + opts = append((*c.CallOptions).ExportAgent[0:len((*c.CallOptions).ExportAgent):len((*c.CallOptions).ExportAgent)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -407,15 +525,11 @@ func (c *AgentsClient) ExportAgent(ctx context.Context, req *cxpb.ExportAgentReq return nil, err } return &ExportAgentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// RestoreAgent restores the specified agent from a binary file. -// -// Replaces the current agent with a new one. Note that all existing resources -// in agent (e.g. intents, entity types, flows) will be removed. -func (c *AgentsClient) RestoreAgent(ctx context.Context, req *cxpb.RestoreAgentRequest, opts ...gax.CallOption) (*RestoreAgentOperation, error) { +func (c *agentsGRPCClient) RestoreAgent(ctx context.Context, req *cxpb.RestoreAgentRequest, opts ...gax.CallOption) (*RestoreAgentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -423,7 +537,7 @@ func (c *AgentsClient) RestoreAgent(ctx context.Context, req *cxpb.RestoreAgentR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RestoreAgent[0:len(c.CallOptions.RestoreAgent):len(c.CallOptions.RestoreAgent)], opts...) + opts = append((*c.CallOptions).RestoreAgent[0:len((*c.CallOptions).RestoreAgent):len((*c.CallOptions).RestoreAgent)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -434,14 +548,11 @@ func (c *AgentsClient) RestoreAgent(ctx context.Context, req *cxpb.RestoreAgentR return nil, err } return &RestoreAgentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ValidateAgent validates the specified agent and creates or updates validation results. -// The agent in draft version is validated. Please call this API after the -// training is completed to get the complete validation results. -func (c *AgentsClient) ValidateAgent(ctx context.Context, req *cxpb.ValidateAgentRequest, opts ...gax.CallOption) (*cxpb.AgentValidationResult, error) { +func (c *agentsGRPCClient) ValidateAgent(ctx context.Context, req *cxpb.ValidateAgentRequest, opts ...gax.CallOption) (*cxpb.AgentValidationResult, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -449,7 +560,7 @@ func (c *AgentsClient) ValidateAgent(ctx context.Context, req *cxpb.ValidateAgen } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ValidateAgent[0:len(c.CallOptions.ValidateAgent):len(c.CallOptions.ValidateAgent)], opts...) + opts = append((*c.CallOptions).ValidateAgent[0:len((*c.CallOptions).ValidateAgent):len((*c.CallOptions).ValidateAgent)], opts...) var resp *cxpb.AgentValidationResult err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -462,9 +573,7 @@ func (c *AgentsClient) ValidateAgent(ctx context.Context, req *cxpb.ValidateAgen return resp, nil } -// GetAgentValidationResult gets the latest agent validation result. Agent validation is performed -// when ValidateAgent is called. -func (c *AgentsClient) GetAgentValidationResult(ctx context.Context, req *cxpb.GetAgentValidationResultRequest, opts ...gax.CallOption) (*cxpb.AgentValidationResult, error) { +func (c *agentsGRPCClient) GetAgentValidationResult(ctx context.Context, req *cxpb.GetAgentValidationResultRequest, opts ...gax.CallOption) (*cxpb.AgentValidationResult, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -472,7 +581,7 @@ func (c *AgentsClient) GetAgentValidationResult(ctx context.Context, req *cxpb.G } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetAgentValidationResult[0:len(c.CallOptions.GetAgentValidationResult):len(c.CallOptions.GetAgentValidationResult)], opts...) + opts = append((*c.CallOptions).GetAgentValidationResult[0:len((*c.CallOptions).GetAgentValidationResult):len((*c.CallOptions).GetAgentValidationResult)], opts...) var resp *cxpb.AgentValidationResult err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -492,9 +601,9 @@ type ExportAgentOperation struct { // ExportAgentOperation returns a new ExportAgentOperation from a given name. // The name must be that of a previously created ExportAgentOperation, possibly from a different process. -func (c *AgentsClient) ExportAgentOperation(name string) *ExportAgentOperation { +func (c *agentsGRPCClient) ExportAgentOperation(name string) *ExportAgentOperation { return &ExportAgentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -561,9 +670,9 @@ type RestoreAgentOperation struct { // RestoreAgentOperation returns a new RestoreAgentOperation from a given name. // The name must be that of a previously created RestoreAgentOperation, possibly from a different process. -func (c *AgentsClient) RestoreAgentOperation(name string) *RestoreAgentOperation { +func (c *agentsGRPCClient) RestoreAgentOperation(name string) *RestoreAgentOperation { return &RestoreAgentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dialogflow/cx/apiv3beta1/agents_client_example_test.go b/dialogflow/cx/apiv3beta1/agents_client_example_test.go index 561c834eade6..c09a8e5f6db3 100644 --- a/dialogflow/cx/apiv3beta1/agents_client_example_test.go +++ b/dialogflow/cx/apiv3beta1/agents_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewAgentsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleAgentsClient_ListAgents() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListAgentsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleAgentsClient_ListAgents() { } func ExampleAgentsClient_GetAgent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetAgentRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleAgentsClient_GetAgent() { } func ExampleAgentsClient_CreateAgent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateAgentRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleAgentsClient_CreateAgent() { } func ExampleAgentsClient_UpdateAgent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateAgentRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleAgentsClient_DeleteAgent() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteAgentRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleAgentsClient_DeleteAgent() { } func ExampleAgentsClient_ExportAgent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ExportAgentRequest{ // TODO: Fill request struct fields. @@ -163,13 +160,12 @@ func ExampleAgentsClient_ExportAgent() { } func ExampleAgentsClient_RestoreAgent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.RestoreAgentRequest{ // TODO: Fill request struct fields. @@ -186,13 +182,12 @@ func ExampleAgentsClient_RestoreAgent() { } func ExampleAgentsClient_ValidateAgent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ValidateAgentRequest{ // TODO: Fill request struct fields. @@ -206,13 +201,12 @@ func ExampleAgentsClient_ValidateAgent() { } func ExampleAgentsClient_GetAgentValidationResult() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetAgentValidationResultRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3beta1/doc.go b/dialogflow/cx/apiv3beta1/doc.go index bb52a0399c00..ed307531df70 100644 --- a/dialogflow/cx/apiv3beta1/doc.go +++ b/dialogflow/cx/apiv3beta1/doc.go @@ -20,6 +20,8 @@ // Builds conversational interfaces (for example, chatbots, and voice-powered // apps and devices). // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package cx // import "cloud.google.com/go/dialogflow/cx/apiv3beta1" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/dialogflow/cx/apiv3beta1/entity_types_client.go b/dialogflow/cx/apiv3beta1/entity_types_client.go index 8634f754146f..bd611b617ca0 100644 --- a/dialogflow/cx/apiv3beta1/entity_types_client.go +++ b/dialogflow/cx/apiv3beta1/entity_types_client.go @@ -46,7 +46,7 @@ type EntityTypesCallOptions struct { DeleteEntityType []gax.CallOption } -func defaultEntityTypesClientOptions() []option.ClientOption { +func defaultEntityTypesGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,103 @@ func defaultEntityTypesCallOptions() *EntityTypesCallOptions { } } +// internalEntityTypesClient is an interface that defines the methods availaible from Dialogflow API. +type internalEntityTypesClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListEntityTypes(context.Context, *cxpb.ListEntityTypesRequest, ...gax.CallOption) *EntityTypeIterator + GetEntityType(context.Context, *cxpb.GetEntityTypeRequest, ...gax.CallOption) (*cxpb.EntityType, error) + CreateEntityType(context.Context, *cxpb.CreateEntityTypeRequest, ...gax.CallOption) (*cxpb.EntityType, error) + UpdateEntityType(context.Context, *cxpb.UpdateEntityTypeRequest, ...gax.CallOption) (*cxpb.EntityType, error) + DeleteEntityType(context.Context, *cxpb.DeleteEntityTypeRequest, ...gax.CallOption) error +} + // EntityTypesClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing EntityTypes. type EntityTypesClient struct { + // The internal transport-dependent client. + internalClient internalEntityTypesClient + + // The call options for this service. + CallOptions *EntityTypesCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *EntityTypesClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *EntityTypesClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *EntityTypesClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListEntityTypes returns the list of all entity types in the specified agent. +func (c *EntityTypesClient) ListEntityTypes(ctx context.Context, req *cxpb.ListEntityTypesRequest, opts ...gax.CallOption) *EntityTypeIterator { + return c.internalClient.ListEntityTypes(ctx, req, opts...) +} + +// GetEntityType retrieves the specified entity type. +func (c *EntityTypesClient) GetEntityType(ctx context.Context, req *cxpb.GetEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { + return c.internalClient.GetEntityType(ctx, req, opts...) +} + +// CreateEntityType creates an entity type in the specified agent. +func (c *EntityTypesClient) CreateEntityType(ctx context.Context, req *cxpb.CreateEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { + return c.internalClient.CreateEntityType(ctx, req, opts...) +} + +// UpdateEntityType updates the specified entity type. +func (c *EntityTypesClient) UpdateEntityType(ctx context.Context, req *cxpb.UpdateEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { + return c.internalClient.UpdateEntityType(ctx, req, opts...) +} + +// DeleteEntityType deletes the specified entity type. +func (c *EntityTypesClient) DeleteEntityType(ctx context.Context, req *cxpb.DeleteEntityTypeRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteEntityType(ctx, req, opts...) +} + +// entityTypesGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type entityTypesGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing EntityTypesClient + CallOptions **EntityTypesCallOptions + // The gRPC API client. entityTypesClient cxpb.EntityTypesClient - // The call options for this service. - CallOptions *EntityTypesCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewEntityTypesClient creates a new entity types client. +// NewEntityTypesClient creates a new entity types client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing EntityTypes. func NewEntityTypesClient(ctx context.Context, opts ...option.ClientOption) (*EntityTypesClient, error) { - clientOpts := defaultEntityTypesClientOptions() - + clientOpts := defaultEntityTypesGRPCClientOptions() if newEntityTypesClientHook != nil { hookOpts, err := newEntityTypesClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,45 +232,47 @@ func NewEntityTypesClient(ctx context.Context, opts ...option.ClientOption) (*En if err != nil { return nil, err } - c := &EntityTypesClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultEntityTypesCallOptions(), + client := EntityTypesClient{CallOptions: defaultEntityTypesCallOptions()} + c := &entityTypesGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, entityTypesClient: cxpb.NewEntityTypesClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *EntityTypesClient) Connection() *grpc.ClientConn { +func (c *entityTypesGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *EntityTypesClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *EntityTypesClient) setGoogleClientInfo(keyval ...string) { +func (c *entityTypesGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListEntityTypes returns the list of all entity types in the specified agent. -func (c *EntityTypesClient) ListEntityTypes(ctx context.Context, req *cxpb.ListEntityTypesRequest, opts ...gax.CallOption) *EntityTypeIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *entityTypesGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *entityTypesGRPCClient) ListEntityTypes(ctx context.Context, req *cxpb.ListEntityTypesRequest, opts ...gax.CallOption) *EntityTypeIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListEntityTypes[0:len(c.CallOptions.ListEntityTypes):len(c.CallOptions.ListEntityTypes)], opts...) + opts = append((*c.CallOptions).ListEntityTypes[0:len((*c.CallOptions).ListEntityTypes):len((*c.CallOptions).ListEntityTypes)], opts...) it := &EntityTypeIterator{} req = proto.Clone(req).(*cxpb.ListEntityTypesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.EntityType, string, error) { @@ -236,8 +309,7 @@ func (c *EntityTypesClient) ListEntityTypes(ctx context.Context, req *cxpb.ListE return it } -// GetEntityType retrieves the specified entity type. -func (c *EntityTypesClient) GetEntityType(ctx context.Context, req *cxpb.GetEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { +func (c *entityTypesGRPCClient) GetEntityType(ctx context.Context, req *cxpb.GetEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -245,7 +317,7 @@ func (c *EntityTypesClient) GetEntityType(ctx context.Context, req *cxpb.GetEnti } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEntityType[0:len(c.CallOptions.GetEntityType):len(c.CallOptions.GetEntityType)], opts...) + opts = append((*c.CallOptions).GetEntityType[0:len((*c.CallOptions).GetEntityType):len((*c.CallOptions).GetEntityType)], opts...) var resp *cxpb.EntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -258,8 +330,7 @@ func (c *EntityTypesClient) GetEntityType(ctx context.Context, req *cxpb.GetEnti return resp, nil } -// CreateEntityType creates an entity type in the specified agent. -func (c *EntityTypesClient) CreateEntityType(ctx context.Context, req *cxpb.CreateEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { +func (c *entityTypesGRPCClient) CreateEntityType(ctx context.Context, req *cxpb.CreateEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -267,7 +338,7 @@ func (c *EntityTypesClient) CreateEntityType(ctx context.Context, req *cxpb.Crea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateEntityType[0:len(c.CallOptions.CreateEntityType):len(c.CallOptions.CreateEntityType)], opts...) + opts = append((*c.CallOptions).CreateEntityType[0:len((*c.CallOptions).CreateEntityType):len((*c.CallOptions).CreateEntityType)], opts...) var resp *cxpb.EntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -280,8 +351,7 @@ func (c *EntityTypesClient) CreateEntityType(ctx context.Context, req *cxpb.Crea return resp, nil } -// UpdateEntityType updates the specified entity type. -func (c *EntityTypesClient) UpdateEntityType(ctx context.Context, req *cxpb.UpdateEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { +func (c *entityTypesGRPCClient) UpdateEntityType(ctx context.Context, req *cxpb.UpdateEntityTypeRequest, opts ...gax.CallOption) (*cxpb.EntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -289,7 +359,7 @@ func (c *EntityTypesClient) UpdateEntityType(ctx context.Context, req *cxpb.Upda } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "entity_type.name", url.QueryEscape(req.GetEntityType().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateEntityType[0:len(c.CallOptions.UpdateEntityType):len(c.CallOptions.UpdateEntityType)], opts...) + opts = append((*c.CallOptions).UpdateEntityType[0:len((*c.CallOptions).UpdateEntityType):len((*c.CallOptions).UpdateEntityType)], opts...) var resp *cxpb.EntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -302,8 +372,7 @@ func (c *EntityTypesClient) UpdateEntityType(ctx context.Context, req *cxpb.Upda return resp, nil } -// DeleteEntityType deletes the specified entity type. -func (c *EntityTypesClient) DeleteEntityType(ctx context.Context, req *cxpb.DeleteEntityTypeRequest, opts ...gax.CallOption) error { +func (c *entityTypesGRPCClient) DeleteEntityType(ctx context.Context, req *cxpb.DeleteEntityTypeRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -311,7 +380,7 @@ func (c *EntityTypesClient) DeleteEntityType(ctx context.Context, req *cxpb.Dele } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteEntityType[0:len(c.CallOptions.DeleteEntityType):len(c.CallOptions.DeleteEntityType)], opts...) + opts = append((*c.CallOptions).DeleteEntityType[0:len((*c.CallOptions).DeleteEntityType):len((*c.CallOptions).DeleteEntityType)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.entityTypesClient.DeleteEntityType(ctx, req, settings.GRPC...) diff --git a/dialogflow/cx/apiv3beta1/entity_types_client_example_test.go b/dialogflow/cx/apiv3beta1/entity_types_client_example_test.go index 8660b4dcd1f8..c7a11f09051d 100644 --- a/dialogflow/cx/apiv3beta1/entity_types_client_example_test.go +++ b/dialogflow/cx/apiv3beta1/entity_types_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewEntityTypesClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleEntityTypesClient_ListEntityTypes() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListEntityTypesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleEntityTypesClient_ListEntityTypes() { } func ExampleEntityTypesClient_GetEntityType() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetEntityTypeRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleEntityTypesClient_GetEntityType() { } func ExampleEntityTypesClient_CreateEntityType() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateEntityTypeRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleEntityTypesClient_CreateEntityType() { } func ExampleEntityTypesClient_UpdateEntityType() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateEntityTypeRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleEntityTypesClient_DeleteEntityType() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3beta1/environments_client.go b/dialogflow/cx/apiv3beta1/environments_client.go index 1b4298990f1e..37af040dfedc 100644 --- a/dialogflow/cx/apiv3beta1/environments_client.go +++ b/dialogflow/cx/apiv3beta1/environments_client.go @@ -51,7 +51,7 @@ type EnvironmentsCallOptions struct { LookupEnvironmentHistory []gax.CallOption } -func defaultEnvironmentsClientOptions() []option.ClientOption { +func defaultEnvironmentsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -134,37 +134,133 @@ func defaultEnvironmentsCallOptions() *EnvironmentsCallOptions { } } +// internalEnvironmentsClient is an interface that defines the methods availaible from Dialogflow API. +type internalEnvironmentsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListEnvironments(context.Context, *cxpb.ListEnvironmentsRequest, ...gax.CallOption) *EnvironmentIterator + GetEnvironment(context.Context, *cxpb.GetEnvironmentRequest, ...gax.CallOption) (*cxpb.Environment, error) + CreateEnvironment(context.Context, *cxpb.CreateEnvironmentRequest, ...gax.CallOption) (*CreateEnvironmentOperation, error) + CreateEnvironmentOperation(name string) *CreateEnvironmentOperation + UpdateEnvironment(context.Context, *cxpb.UpdateEnvironmentRequest, ...gax.CallOption) (*UpdateEnvironmentOperation, error) + UpdateEnvironmentOperation(name string) *UpdateEnvironmentOperation + DeleteEnvironment(context.Context, *cxpb.DeleteEnvironmentRequest, ...gax.CallOption) error + LookupEnvironmentHistory(context.Context, *cxpb.LookupEnvironmentHistoryRequest, ...gax.CallOption) *EnvironmentIterator +} + // EnvironmentsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Environments. type EnvironmentsClient struct { + // The internal transport-dependent client. + internalClient internalEnvironmentsClient + + // The call options for this service. + CallOptions *EnvironmentsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *EnvironmentsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *EnvironmentsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *EnvironmentsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListEnvironments returns the list of all environments in the specified Agent. +func (c *EnvironmentsClient) ListEnvironments(ctx context.Context, req *cxpb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { + return c.internalClient.ListEnvironments(ctx, req, opts...) +} + +// GetEnvironment retrieves the specified Environment. +func (c *EnvironmentsClient) GetEnvironment(ctx context.Context, req *cxpb.GetEnvironmentRequest, opts ...gax.CallOption) (*cxpb.Environment, error) { + return c.internalClient.GetEnvironment(ctx, req, opts...) +} + +// CreateEnvironment creates an Environment in the specified Agent. +func (c *EnvironmentsClient) CreateEnvironment(ctx context.Context, req *cxpb.CreateEnvironmentRequest, opts ...gax.CallOption) (*CreateEnvironmentOperation, error) { + return c.internalClient.CreateEnvironment(ctx, req, opts...) +} + +// CreateEnvironmentOperation returns a new CreateEnvironmentOperation from a given name. +// The name must be that of a previously created CreateEnvironmentOperation, possibly from a different process. +func (c *EnvironmentsClient) CreateEnvironmentOperation(name string) *CreateEnvironmentOperation { + return c.internalClient.CreateEnvironmentOperation(name) +} + +// UpdateEnvironment updates the specified Environment. +func (c *EnvironmentsClient) UpdateEnvironment(ctx context.Context, req *cxpb.UpdateEnvironmentRequest, opts ...gax.CallOption) (*UpdateEnvironmentOperation, error) { + return c.internalClient.UpdateEnvironment(ctx, req, opts...) +} + +// UpdateEnvironmentOperation returns a new UpdateEnvironmentOperation from a given name. +// The name must be that of a previously created UpdateEnvironmentOperation, possibly from a different process. +func (c *EnvironmentsClient) UpdateEnvironmentOperation(name string) *UpdateEnvironmentOperation { + return c.internalClient.UpdateEnvironmentOperation(name) +} + +// DeleteEnvironment deletes the specified Environment. +func (c *EnvironmentsClient) DeleteEnvironment(ctx context.Context, req *cxpb.DeleteEnvironmentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteEnvironment(ctx, req, opts...) +} + +// LookupEnvironmentHistory looks up the history of the specified Environment. +func (c *EnvironmentsClient) LookupEnvironmentHistory(ctx context.Context, req *cxpb.LookupEnvironmentHistoryRequest, opts ...gax.CallOption) *EnvironmentIterator { + return c.internalClient.LookupEnvironmentHistory(ctx, req, opts...) +} + +// environmentsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type environmentsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing EnvironmentsClient + CallOptions **EnvironmentsCallOptions + // The gRPC API client. environmentsClient cxpb.EnvironmentsClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *EnvironmentsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewEnvironmentsClient creates a new environments client. +// NewEnvironmentsClient creates a new environments client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Environments. func NewEnvironmentsClient(ctx context.Context, opts ...option.ClientOption) (*EnvironmentsClient, error) { - clientOpts := defaultEnvironmentsClientOptions() - + clientOpts := defaultEnvironmentsGRPCClientOptions() if newEnvironmentsClientHook != nil { hookOpts, err := newEnvironmentsClientHook(ctx, clientHookParams{}) if err != nil { @@ -182,16 +278,19 @@ func NewEnvironmentsClient(ctx context.Context, opts ...option.ClientOption) (*E if err != nil { return nil, err } - c := &EnvironmentsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultEnvironmentsCallOptions(), + client := EnvironmentsClient{CallOptions: defaultEnvironmentsCallOptions()} + c := &environmentsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, environmentsClient: cxpb.NewEnvironmentsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -201,36 +300,36 @@ func NewEnvironmentsClient(ctx context.Context, opts ...option.ClientOption) (*E // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *EnvironmentsClient) Connection() *grpc.ClientConn { +func (c *environmentsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *EnvironmentsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *EnvironmentsClient) setGoogleClientInfo(keyval ...string) { +func (c *environmentsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListEnvironments returns the list of all environments in the specified Agent. -func (c *EnvironmentsClient) ListEnvironments(ctx context.Context, req *cxpb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *environmentsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *environmentsGRPCClient) ListEnvironments(ctx context.Context, req *cxpb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListEnvironments[0:len(c.CallOptions.ListEnvironments):len(c.CallOptions.ListEnvironments)], opts...) + opts = append((*c.CallOptions).ListEnvironments[0:len((*c.CallOptions).ListEnvironments):len((*c.CallOptions).ListEnvironments)], opts...) it := &EnvironmentIterator{} req = proto.Clone(req).(*cxpb.ListEnvironmentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Environment, string, error) { @@ -267,8 +366,7 @@ func (c *EnvironmentsClient) ListEnvironments(ctx context.Context, req *cxpb.Lis return it } -// GetEnvironment retrieves the specified Environment. -func (c *EnvironmentsClient) GetEnvironment(ctx context.Context, req *cxpb.GetEnvironmentRequest, opts ...gax.CallOption) (*cxpb.Environment, error) { +func (c *environmentsGRPCClient) GetEnvironment(ctx context.Context, req *cxpb.GetEnvironmentRequest, opts ...gax.CallOption) (*cxpb.Environment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -276,7 +374,7 @@ func (c *EnvironmentsClient) GetEnvironment(ctx context.Context, req *cxpb.GetEn } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEnvironment[0:len(c.CallOptions.GetEnvironment):len(c.CallOptions.GetEnvironment)], opts...) + opts = append((*c.CallOptions).GetEnvironment[0:len((*c.CallOptions).GetEnvironment):len((*c.CallOptions).GetEnvironment)], opts...) var resp *cxpb.Environment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -289,8 +387,7 @@ func (c *EnvironmentsClient) GetEnvironment(ctx context.Context, req *cxpb.GetEn return resp, nil } -// CreateEnvironment creates an Environment in the specified Agent. -func (c *EnvironmentsClient) CreateEnvironment(ctx context.Context, req *cxpb.CreateEnvironmentRequest, opts ...gax.CallOption) (*CreateEnvironmentOperation, error) { +func (c *environmentsGRPCClient) CreateEnvironment(ctx context.Context, req *cxpb.CreateEnvironmentRequest, opts ...gax.CallOption) (*CreateEnvironmentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -298,7 +395,7 @@ func (c *EnvironmentsClient) CreateEnvironment(ctx context.Context, req *cxpb.Cr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateEnvironment[0:len(c.CallOptions.CreateEnvironment):len(c.CallOptions.CreateEnvironment)], opts...) + opts = append((*c.CallOptions).CreateEnvironment[0:len((*c.CallOptions).CreateEnvironment):len((*c.CallOptions).CreateEnvironment)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -309,12 +406,11 @@ func (c *EnvironmentsClient) CreateEnvironment(ctx context.Context, req *cxpb.Cr return nil, err } return &CreateEnvironmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateEnvironment updates the specified Environment. -func (c *EnvironmentsClient) UpdateEnvironment(ctx context.Context, req *cxpb.UpdateEnvironmentRequest, opts ...gax.CallOption) (*UpdateEnvironmentOperation, error) { +func (c *environmentsGRPCClient) UpdateEnvironment(ctx context.Context, req *cxpb.UpdateEnvironmentRequest, opts ...gax.CallOption) (*UpdateEnvironmentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -322,7 +418,7 @@ func (c *EnvironmentsClient) UpdateEnvironment(ctx context.Context, req *cxpb.Up } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "environment.name", url.QueryEscape(req.GetEnvironment().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateEnvironment[0:len(c.CallOptions.UpdateEnvironment):len(c.CallOptions.UpdateEnvironment)], opts...) + opts = append((*c.CallOptions).UpdateEnvironment[0:len((*c.CallOptions).UpdateEnvironment):len((*c.CallOptions).UpdateEnvironment)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -333,12 +429,11 @@ func (c *EnvironmentsClient) UpdateEnvironment(ctx context.Context, req *cxpb.Up return nil, err } return &UpdateEnvironmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteEnvironment deletes the specified Environment. -func (c *EnvironmentsClient) DeleteEnvironment(ctx context.Context, req *cxpb.DeleteEnvironmentRequest, opts ...gax.CallOption) error { +func (c *environmentsGRPCClient) DeleteEnvironment(ctx context.Context, req *cxpb.DeleteEnvironmentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -346,7 +441,7 @@ func (c *EnvironmentsClient) DeleteEnvironment(ctx context.Context, req *cxpb.De } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteEnvironment[0:len(c.CallOptions.DeleteEnvironment):len(c.CallOptions.DeleteEnvironment)], opts...) + opts = append((*c.CallOptions).DeleteEnvironment[0:len((*c.CallOptions).DeleteEnvironment):len((*c.CallOptions).DeleteEnvironment)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.environmentsClient.DeleteEnvironment(ctx, req, settings.GRPC...) @@ -355,11 +450,10 @@ func (c *EnvironmentsClient) DeleteEnvironment(ctx context.Context, req *cxpb.De return err } -// LookupEnvironmentHistory looks up the history of the specified Environment. -func (c *EnvironmentsClient) LookupEnvironmentHistory(ctx context.Context, req *cxpb.LookupEnvironmentHistoryRequest, opts ...gax.CallOption) *EnvironmentIterator { +func (c *environmentsGRPCClient) LookupEnvironmentHistory(ctx context.Context, req *cxpb.LookupEnvironmentHistoryRequest, opts ...gax.CallOption) *EnvironmentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.LookupEnvironmentHistory[0:len(c.CallOptions.LookupEnvironmentHistory):len(c.CallOptions.LookupEnvironmentHistory)], opts...) + opts = append((*c.CallOptions).LookupEnvironmentHistory[0:len((*c.CallOptions).LookupEnvironmentHistory):len((*c.CallOptions).LookupEnvironmentHistory)], opts...) it := &EnvironmentIterator{} req = proto.Clone(req).(*cxpb.LookupEnvironmentHistoryRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Environment, string, error) { @@ -403,9 +497,9 @@ type CreateEnvironmentOperation struct { // CreateEnvironmentOperation returns a new CreateEnvironmentOperation from a given name. // The name must be that of a previously created CreateEnvironmentOperation, possibly from a different process. -func (c *EnvironmentsClient) CreateEnvironmentOperation(name string) *CreateEnvironmentOperation { +func (c *environmentsGRPCClient) CreateEnvironmentOperation(name string) *CreateEnvironmentOperation { return &CreateEnvironmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -472,9 +566,9 @@ type UpdateEnvironmentOperation struct { // UpdateEnvironmentOperation returns a new UpdateEnvironmentOperation from a given name. // The name must be that of a previously created UpdateEnvironmentOperation, possibly from a different process. -func (c *EnvironmentsClient) UpdateEnvironmentOperation(name string) *UpdateEnvironmentOperation { +func (c *environmentsGRPCClient) UpdateEnvironmentOperation(name string) *UpdateEnvironmentOperation { return &UpdateEnvironmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dialogflow/cx/apiv3beta1/environments_client_example_test.go b/dialogflow/cx/apiv3beta1/environments_client_example_test.go index 4e3eac017c63..4572377dcf56 100644 --- a/dialogflow/cx/apiv3beta1/environments_client_example_test.go +++ b/dialogflow/cx/apiv3beta1/environments_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewEnvironmentsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleEnvironmentsClient_ListEnvironments() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListEnvironmentsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleEnvironmentsClient_ListEnvironments() { } func ExampleEnvironmentsClient_GetEnvironment() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetEnvironmentRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleEnvironmentsClient_GetEnvironment() { } func ExampleEnvironmentsClient_CreateEnvironment() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateEnvironmentRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleEnvironmentsClient_CreateEnvironment() { } func ExampleEnvironmentsClient_UpdateEnvironment() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateEnvironmentRequest{ // TODO: Fill request struct fields. @@ -137,6 +134,7 @@ func ExampleEnvironmentsClient_DeleteEnvironment() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteEnvironmentRequest{ // TODO: Fill request struct fields. @@ -148,14 +146,12 @@ func ExampleEnvironmentsClient_DeleteEnvironment() { } func ExampleEnvironmentsClient_LookupEnvironmentHistory() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.LookupEnvironmentHistoryRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3beta1/experiments_client.go b/dialogflow/cx/apiv3beta1/experiments_client.go index 7a96e0121c81..ae313d57ec33 100644 --- a/dialogflow/cx/apiv3beta1/experiments_client.go +++ b/dialogflow/cx/apiv3beta1/experiments_client.go @@ -48,7 +48,7 @@ type ExperimentsCallOptions struct { StopExperiment []gax.CallOption } -func defaultExperimentsClientOptions() []option.ClientOption { +func defaultExperimentsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -142,32 +142,117 @@ func defaultExperimentsCallOptions() *ExperimentsCallOptions { } } +// internalExperimentsClient is an interface that defines the methods availaible from Dialogflow API. +type internalExperimentsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListExperiments(context.Context, *cxpb.ListExperimentsRequest, ...gax.CallOption) *ExperimentIterator + GetExperiment(context.Context, *cxpb.GetExperimentRequest, ...gax.CallOption) (*cxpb.Experiment, error) + CreateExperiment(context.Context, *cxpb.CreateExperimentRequest, ...gax.CallOption) (*cxpb.Experiment, error) + UpdateExperiment(context.Context, *cxpb.UpdateExperimentRequest, ...gax.CallOption) (*cxpb.Experiment, error) + DeleteExperiment(context.Context, *cxpb.DeleteExperimentRequest, ...gax.CallOption) error + StartExperiment(context.Context, *cxpb.StartExperimentRequest, ...gax.CallOption) (*cxpb.Experiment, error) + StopExperiment(context.Context, *cxpb.StopExperimentRequest, ...gax.CallOption) (*cxpb.Experiment, error) +} + // ExperimentsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Experiments. type ExperimentsClient struct { + // The internal transport-dependent client. + internalClient internalExperimentsClient + + // The call options for this service. + CallOptions *ExperimentsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ExperimentsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ExperimentsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ExperimentsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListExperiments returns the list of all experiments in the specified Environment. +func (c *ExperimentsClient) ListExperiments(ctx context.Context, req *cxpb.ListExperimentsRequest, opts ...gax.CallOption) *ExperimentIterator { + return c.internalClient.ListExperiments(ctx, req, opts...) +} + +// GetExperiment retrieves the specified Experiment. +func (c *ExperimentsClient) GetExperiment(ctx context.Context, req *cxpb.GetExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { + return c.internalClient.GetExperiment(ctx, req, opts...) +} + +// CreateExperiment creates an Experiment in the specified Environment. +func (c *ExperimentsClient) CreateExperiment(ctx context.Context, req *cxpb.CreateExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { + return c.internalClient.CreateExperiment(ctx, req, opts...) +} + +// UpdateExperiment updates the specified Experiment. +func (c *ExperimentsClient) UpdateExperiment(ctx context.Context, req *cxpb.UpdateExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { + return c.internalClient.UpdateExperiment(ctx, req, opts...) +} + +// DeleteExperiment deletes the specified Experiment. +func (c *ExperimentsClient) DeleteExperiment(ctx context.Context, req *cxpb.DeleteExperimentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteExperiment(ctx, req, opts...) +} + +// StartExperiment starts the specified Experiment. This rpc only changes the state of +// experiment from PENDING to RUNNING. +func (c *ExperimentsClient) StartExperiment(ctx context.Context, req *cxpb.StartExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { + return c.internalClient.StartExperiment(ctx, req, opts...) +} + +// StopExperiment stops the specified Experiment. This rpc only changes the state of +// experiment from RUNNING to DONE. +func (c *ExperimentsClient) StopExperiment(ctx context.Context, req *cxpb.StopExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { + return c.internalClient.StopExperiment(ctx, req, opts...) +} + +// experimentsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type experimentsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ExperimentsClient + CallOptions **ExperimentsCallOptions + // The gRPC API client. experimentsClient cxpb.ExperimentsClient - // The call options for this service. - CallOptions *ExperimentsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewExperimentsClient creates a new experiments client. +// NewExperimentsClient creates a new experiments client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Experiments. func NewExperimentsClient(ctx context.Context, opts ...option.ClientOption) (*ExperimentsClient, error) { - clientOpts := defaultExperimentsClientOptions() - + clientOpts := defaultExperimentsGRPCClientOptions() if newExperimentsClientHook != nil { hookOpts, err := newExperimentsClientHook(ctx, clientHookParams{}) if err != nil { @@ -185,45 +270,47 @@ func NewExperimentsClient(ctx context.Context, opts ...option.ClientOption) (*Ex if err != nil { return nil, err } - c := &ExperimentsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultExperimentsCallOptions(), + client := ExperimentsClient{CallOptions: defaultExperimentsCallOptions()} + c := &experimentsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, experimentsClient: cxpb.NewExperimentsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ExperimentsClient) Connection() *grpc.ClientConn { +func (c *experimentsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ExperimentsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ExperimentsClient) setGoogleClientInfo(keyval ...string) { +func (c *experimentsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListExperiments returns the list of all experiments in the specified Environment. -func (c *ExperimentsClient) ListExperiments(ctx context.Context, req *cxpb.ListExperimentsRequest, opts ...gax.CallOption) *ExperimentIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *experimentsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *experimentsGRPCClient) ListExperiments(ctx context.Context, req *cxpb.ListExperimentsRequest, opts ...gax.CallOption) *ExperimentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListExperiments[0:len(c.CallOptions.ListExperiments):len(c.CallOptions.ListExperiments)], opts...) + opts = append((*c.CallOptions).ListExperiments[0:len((*c.CallOptions).ListExperiments):len((*c.CallOptions).ListExperiments)], opts...) it := &ExperimentIterator{} req = proto.Clone(req).(*cxpb.ListExperimentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Experiment, string, error) { @@ -260,8 +347,7 @@ func (c *ExperimentsClient) ListExperiments(ctx context.Context, req *cxpb.ListE return it } -// GetExperiment retrieves the specified Experiment. -func (c *ExperimentsClient) GetExperiment(ctx context.Context, req *cxpb.GetExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { +func (c *experimentsGRPCClient) GetExperiment(ctx context.Context, req *cxpb.GetExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -269,7 +355,7 @@ func (c *ExperimentsClient) GetExperiment(ctx context.Context, req *cxpb.GetExpe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetExperiment[0:len(c.CallOptions.GetExperiment):len(c.CallOptions.GetExperiment)], opts...) + opts = append((*c.CallOptions).GetExperiment[0:len((*c.CallOptions).GetExperiment):len((*c.CallOptions).GetExperiment)], opts...) var resp *cxpb.Experiment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -282,8 +368,7 @@ func (c *ExperimentsClient) GetExperiment(ctx context.Context, req *cxpb.GetExpe return resp, nil } -// CreateExperiment creates an Experiment in the specified Environment. -func (c *ExperimentsClient) CreateExperiment(ctx context.Context, req *cxpb.CreateExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { +func (c *experimentsGRPCClient) CreateExperiment(ctx context.Context, req *cxpb.CreateExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -291,7 +376,7 @@ func (c *ExperimentsClient) CreateExperiment(ctx context.Context, req *cxpb.Crea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateExperiment[0:len(c.CallOptions.CreateExperiment):len(c.CallOptions.CreateExperiment)], opts...) + opts = append((*c.CallOptions).CreateExperiment[0:len((*c.CallOptions).CreateExperiment):len((*c.CallOptions).CreateExperiment)], opts...) var resp *cxpb.Experiment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -304,8 +389,7 @@ func (c *ExperimentsClient) CreateExperiment(ctx context.Context, req *cxpb.Crea return resp, nil } -// UpdateExperiment updates the specified Experiment. -func (c *ExperimentsClient) UpdateExperiment(ctx context.Context, req *cxpb.UpdateExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { +func (c *experimentsGRPCClient) UpdateExperiment(ctx context.Context, req *cxpb.UpdateExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -313,7 +397,7 @@ func (c *ExperimentsClient) UpdateExperiment(ctx context.Context, req *cxpb.Upda } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "experiment.name", url.QueryEscape(req.GetExperiment().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateExperiment[0:len(c.CallOptions.UpdateExperiment):len(c.CallOptions.UpdateExperiment)], opts...) + opts = append((*c.CallOptions).UpdateExperiment[0:len((*c.CallOptions).UpdateExperiment):len((*c.CallOptions).UpdateExperiment)], opts...) var resp *cxpb.Experiment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -326,8 +410,7 @@ func (c *ExperimentsClient) UpdateExperiment(ctx context.Context, req *cxpb.Upda return resp, nil } -// DeleteExperiment deletes the specified Experiment. -func (c *ExperimentsClient) DeleteExperiment(ctx context.Context, req *cxpb.DeleteExperimentRequest, opts ...gax.CallOption) error { +func (c *experimentsGRPCClient) DeleteExperiment(ctx context.Context, req *cxpb.DeleteExperimentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -335,7 +418,7 @@ func (c *ExperimentsClient) DeleteExperiment(ctx context.Context, req *cxpb.Dele } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteExperiment[0:len(c.CallOptions.DeleteExperiment):len(c.CallOptions.DeleteExperiment)], opts...) + opts = append((*c.CallOptions).DeleteExperiment[0:len((*c.CallOptions).DeleteExperiment):len((*c.CallOptions).DeleteExperiment)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.experimentsClient.DeleteExperiment(ctx, req, settings.GRPC...) @@ -344,9 +427,7 @@ func (c *ExperimentsClient) DeleteExperiment(ctx context.Context, req *cxpb.Dele return err } -// StartExperiment starts the specified Experiment. This rpc only changes the state of -// experiment from PENDING to RUNNING. -func (c *ExperimentsClient) StartExperiment(ctx context.Context, req *cxpb.StartExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { +func (c *experimentsGRPCClient) StartExperiment(ctx context.Context, req *cxpb.StartExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -354,7 +435,7 @@ func (c *ExperimentsClient) StartExperiment(ctx context.Context, req *cxpb.Start } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.StartExperiment[0:len(c.CallOptions.StartExperiment):len(c.CallOptions.StartExperiment)], opts...) + opts = append((*c.CallOptions).StartExperiment[0:len((*c.CallOptions).StartExperiment):len((*c.CallOptions).StartExperiment)], opts...) var resp *cxpb.Experiment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -367,9 +448,7 @@ func (c *ExperimentsClient) StartExperiment(ctx context.Context, req *cxpb.Start return resp, nil } -// StopExperiment stops the specified Experiment. This rpc only changes the state of -// experiment from RUNNING to DONE. -func (c *ExperimentsClient) StopExperiment(ctx context.Context, req *cxpb.StopExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { +func (c *experimentsGRPCClient) StopExperiment(ctx context.Context, req *cxpb.StopExperimentRequest, opts ...gax.CallOption) (*cxpb.Experiment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -377,7 +456,7 @@ func (c *ExperimentsClient) StopExperiment(ctx context.Context, req *cxpb.StopEx } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.StopExperiment[0:len(c.CallOptions.StopExperiment):len(c.CallOptions.StopExperiment)], opts...) + opts = append((*c.CallOptions).StopExperiment[0:len((*c.CallOptions).StopExperiment):len((*c.CallOptions).StopExperiment)], opts...) var resp *cxpb.Experiment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/dialogflow/cx/apiv3beta1/experiments_client_example_test.go b/dialogflow/cx/apiv3beta1/experiments_client_example_test.go index 22641399ff54..07476ac198ce 100644 --- a/dialogflow/cx/apiv3beta1/experiments_client_example_test.go +++ b/dialogflow/cx/apiv3beta1/experiments_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewExperimentsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleExperimentsClient_ListExperiments() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListExperimentsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleExperimentsClient_ListExperiments() { } func ExampleExperimentsClient_GetExperiment() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetExperimentRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleExperimentsClient_GetExperiment() { } func ExampleExperimentsClient_CreateExperiment() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateExperimentRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleExperimentsClient_CreateExperiment() { } func ExampleExperimentsClient_UpdateExperiment() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateExperimentRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleExperimentsClient_DeleteExperiment() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteExperimentRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleExperimentsClient_DeleteExperiment() { } func ExampleExperimentsClient_StartExperiment() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.StartExperimentRequest{ // TODO: Fill request struct fields. @@ -158,13 +155,12 @@ func ExampleExperimentsClient_StartExperiment() { } func ExampleExperimentsClient_StopExperiment() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.StopExperimentRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3beta1/flows_client.go b/dialogflow/cx/apiv3beta1/flows_client.go index 8190eb12e09b..5cfce01fe73c 100644 --- a/dialogflow/cx/apiv3beta1/flows_client.go +++ b/dialogflow/cx/apiv3beta1/flows_client.go @@ -55,7 +55,7 @@ type FlowsCallOptions struct { ExportFlow []gax.CallOption } -func defaultFlowsClientOptions() []option.ClientOption { +func defaultFlowsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -182,37 +182,171 @@ func defaultFlowsCallOptions() *FlowsCallOptions { } } +// internalFlowsClient is an interface that defines the methods availaible from Dialogflow API. +type internalFlowsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateFlow(context.Context, *cxpb.CreateFlowRequest, ...gax.CallOption) (*cxpb.Flow, error) + DeleteFlow(context.Context, *cxpb.DeleteFlowRequest, ...gax.CallOption) error + ListFlows(context.Context, *cxpb.ListFlowsRequest, ...gax.CallOption) *FlowIterator + GetFlow(context.Context, *cxpb.GetFlowRequest, ...gax.CallOption) (*cxpb.Flow, error) + UpdateFlow(context.Context, *cxpb.UpdateFlowRequest, ...gax.CallOption) (*cxpb.Flow, error) + TrainFlow(context.Context, *cxpb.TrainFlowRequest, ...gax.CallOption) (*TrainFlowOperation, error) + TrainFlowOperation(name string) *TrainFlowOperation + ValidateFlow(context.Context, *cxpb.ValidateFlowRequest, ...gax.CallOption) (*cxpb.FlowValidationResult, error) + GetFlowValidationResult(context.Context, *cxpb.GetFlowValidationResultRequest, ...gax.CallOption) (*cxpb.FlowValidationResult, error) + ImportFlow(context.Context, *cxpb.ImportFlowRequest, ...gax.CallOption) (*ImportFlowOperation, error) + ImportFlowOperation(name string) *ImportFlowOperation + ExportFlow(context.Context, *cxpb.ExportFlowRequest, ...gax.CallOption) (*ExportFlowOperation, error) + ExportFlowOperation(name string) *ExportFlowOperation +} + // FlowsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Flows. type FlowsClient struct { + // The internal transport-dependent client. + internalClient internalFlowsClient + + // The call options for this service. + CallOptions *FlowsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *FlowsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *FlowsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *FlowsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateFlow creates a flow in the specified agent. +func (c *FlowsClient) CreateFlow(ctx context.Context, req *cxpb.CreateFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { + return c.internalClient.CreateFlow(ctx, req, opts...) +} + +// DeleteFlow deletes a specified flow. +func (c *FlowsClient) DeleteFlow(ctx context.Context, req *cxpb.DeleteFlowRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteFlow(ctx, req, opts...) +} + +// ListFlows returns the list of all flows in the specified agent. +func (c *FlowsClient) ListFlows(ctx context.Context, req *cxpb.ListFlowsRequest, opts ...gax.CallOption) *FlowIterator { + return c.internalClient.ListFlows(ctx, req, opts...) +} + +// GetFlow retrieves the specified flow. +func (c *FlowsClient) GetFlow(ctx context.Context, req *cxpb.GetFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { + return c.internalClient.GetFlow(ctx, req, opts...) +} + +// UpdateFlow updates the specified flow. +func (c *FlowsClient) UpdateFlow(ctx context.Context, req *cxpb.UpdateFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { + return c.internalClient.UpdateFlow(ctx, req, opts...) +} + +// TrainFlow trains the specified flow. Note that only the flow in ‘draft’ environment +// is trained. +func (c *FlowsClient) TrainFlow(ctx context.Context, req *cxpb.TrainFlowRequest, opts ...gax.CallOption) (*TrainFlowOperation, error) { + return c.internalClient.TrainFlow(ctx, req, opts...) +} + +// TrainFlowOperation returns a new TrainFlowOperation from a given name. +// The name must be that of a previously created TrainFlowOperation, possibly from a different process. +func (c *FlowsClient) TrainFlowOperation(name string) *TrainFlowOperation { + return c.internalClient.TrainFlowOperation(name) +} + +// ValidateFlow validates the specified flow and creates or updates validation results. +// Please call this API after the training is completed to get the complete +// validation results. +func (c *FlowsClient) ValidateFlow(ctx context.Context, req *cxpb.ValidateFlowRequest, opts ...gax.CallOption) (*cxpb.FlowValidationResult, error) { + return c.internalClient.ValidateFlow(ctx, req, opts...) +} + +// GetFlowValidationResult gets the latest flow validation result. Flow validation is performed +// when ValidateFlow is called. +func (c *FlowsClient) GetFlowValidationResult(ctx context.Context, req *cxpb.GetFlowValidationResultRequest, opts ...gax.CallOption) (*cxpb.FlowValidationResult, error) { + return c.internalClient.GetFlowValidationResult(ctx, req, opts...) +} + +// ImportFlow imports the specified flow to the specified agent from a binary file. +func (c *FlowsClient) ImportFlow(ctx context.Context, req *cxpb.ImportFlowRequest, opts ...gax.CallOption) (*ImportFlowOperation, error) { + return c.internalClient.ImportFlow(ctx, req, opts...) +} + +// ImportFlowOperation returns a new ImportFlowOperation from a given name. +// The name must be that of a previously created ImportFlowOperation, possibly from a different process. +func (c *FlowsClient) ImportFlowOperation(name string) *ImportFlowOperation { + return c.internalClient.ImportFlowOperation(name) +} + +// ExportFlow exports the specified flow to a binary file. +// +// Note that resources (e.g. intents, entities, webhooks) that the flow +// references will also be exported. +func (c *FlowsClient) ExportFlow(ctx context.Context, req *cxpb.ExportFlowRequest, opts ...gax.CallOption) (*ExportFlowOperation, error) { + return c.internalClient.ExportFlow(ctx, req, opts...) +} + +// ExportFlowOperation returns a new ExportFlowOperation from a given name. +// The name must be that of a previously created ExportFlowOperation, possibly from a different process. +func (c *FlowsClient) ExportFlowOperation(name string) *ExportFlowOperation { + return c.internalClient.ExportFlowOperation(name) +} + +// flowsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type flowsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing FlowsClient + CallOptions **FlowsCallOptions + // The gRPC API client. flowsClient cxpb.FlowsClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *FlowsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewFlowsClient creates a new flows client. +// NewFlowsClient creates a new flows client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Flows. func NewFlowsClient(ctx context.Context, opts ...option.ClientOption) (*FlowsClient, error) { - clientOpts := defaultFlowsClientOptions() - + clientOpts := defaultFlowsGRPCClientOptions() if newFlowsClientHook != nil { hookOpts, err := newFlowsClientHook(ctx, clientHookParams{}) if err != nil { @@ -230,16 +364,19 @@ func NewFlowsClient(ctx context.Context, opts ...option.ClientOption) (*FlowsCli if err != nil { return nil, err } - c := &FlowsClient{ + client := FlowsClient{CallOptions: defaultFlowsCallOptions()} + + c := &flowsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultFlowsCallOptions(), - - flowsClient: cxpb.NewFlowsClient(connPool), + flowsClient: cxpb.NewFlowsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -249,33 +386,33 @@ func NewFlowsClient(ctx context.Context, opts ...option.ClientOption) (*FlowsCli // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *FlowsClient) Connection() *grpc.ClientConn { +func (c *flowsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *FlowsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *FlowsClient) setGoogleClientInfo(keyval ...string) { +func (c *flowsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateFlow creates a flow in the specified agent. -func (c *FlowsClient) CreateFlow(ctx context.Context, req *cxpb.CreateFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *flowsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *flowsGRPCClient) CreateFlow(ctx context.Context, req *cxpb.CreateFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -283,7 +420,7 @@ func (c *FlowsClient) CreateFlow(ctx context.Context, req *cxpb.CreateFlowReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateFlow[0:len(c.CallOptions.CreateFlow):len(c.CallOptions.CreateFlow)], opts...) + opts = append((*c.CallOptions).CreateFlow[0:len((*c.CallOptions).CreateFlow):len((*c.CallOptions).CreateFlow)], opts...) var resp *cxpb.Flow err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -296,8 +433,7 @@ func (c *FlowsClient) CreateFlow(ctx context.Context, req *cxpb.CreateFlowReques return resp, nil } -// DeleteFlow deletes a specified flow. -func (c *FlowsClient) DeleteFlow(ctx context.Context, req *cxpb.DeleteFlowRequest, opts ...gax.CallOption) error { +func (c *flowsGRPCClient) DeleteFlow(ctx context.Context, req *cxpb.DeleteFlowRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -305,7 +441,7 @@ func (c *FlowsClient) DeleteFlow(ctx context.Context, req *cxpb.DeleteFlowReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteFlow[0:len(c.CallOptions.DeleteFlow):len(c.CallOptions.DeleteFlow)], opts...) + opts = append((*c.CallOptions).DeleteFlow[0:len((*c.CallOptions).DeleteFlow):len((*c.CallOptions).DeleteFlow)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.flowsClient.DeleteFlow(ctx, req, settings.GRPC...) @@ -314,11 +450,10 @@ func (c *FlowsClient) DeleteFlow(ctx context.Context, req *cxpb.DeleteFlowReques return err } -// ListFlows returns the list of all flows in the specified agent. -func (c *FlowsClient) ListFlows(ctx context.Context, req *cxpb.ListFlowsRequest, opts ...gax.CallOption) *FlowIterator { +func (c *flowsGRPCClient) ListFlows(ctx context.Context, req *cxpb.ListFlowsRequest, opts ...gax.CallOption) *FlowIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListFlows[0:len(c.CallOptions.ListFlows):len(c.CallOptions.ListFlows)], opts...) + opts = append((*c.CallOptions).ListFlows[0:len((*c.CallOptions).ListFlows):len((*c.CallOptions).ListFlows)], opts...) it := &FlowIterator{} req = proto.Clone(req).(*cxpb.ListFlowsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Flow, string, error) { @@ -355,8 +490,7 @@ func (c *FlowsClient) ListFlows(ctx context.Context, req *cxpb.ListFlowsRequest, return it } -// GetFlow retrieves the specified flow. -func (c *FlowsClient) GetFlow(ctx context.Context, req *cxpb.GetFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { +func (c *flowsGRPCClient) GetFlow(ctx context.Context, req *cxpb.GetFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -364,7 +498,7 @@ func (c *FlowsClient) GetFlow(ctx context.Context, req *cxpb.GetFlowRequest, opt } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetFlow[0:len(c.CallOptions.GetFlow):len(c.CallOptions.GetFlow)], opts...) + opts = append((*c.CallOptions).GetFlow[0:len((*c.CallOptions).GetFlow):len((*c.CallOptions).GetFlow)], opts...) var resp *cxpb.Flow err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -377,8 +511,7 @@ func (c *FlowsClient) GetFlow(ctx context.Context, req *cxpb.GetFlowRequest, opt return resp, nil } -// UpdateFlow updates the specified flow. -func (c *FlowsClient) UpdateFlow(ctx context.Context, req *cxpb.UpdateFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { +func (c *flowsGRPCClient) UpdateFlow(ctx context.Context, req *cxpb.UpdateFlowRequest, opts ...gax.CallOption) (*cxpb.Flow, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -386,7 +519,7 @@ func (c *FlowsClient) UpdateFlow(ctx context.Context, req *cxpb.UpdateFlowReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "flow.name", url.QueryEscape(req.GetFlow().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateFlow[0:len(c.CallOptions.UpdateFlow):len(c.CallOptions.UpdateFlow)], opts...) + opts = append((*c.CallOptions).UpdateFlow[0:len((*c.CallOptions).UpdateFlow):len((*c.CallOptions).UpdateFlow)], opts...) var resp *cxpb.Flow err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -399,9 +532,7 @@ func (c *FlowsClient) UpdateFlow(ctx context.Context, req *cxpb.UpdateFlowReques return resp, nil } -// TrainFlow trains the specified flow. Note that only the flow in ‘draft’ environment -// is trained. -func (c *FlowsClient) TrainFlow(ctx context.Context, req *cxpb.TrainFlowRequest, opts ...gax.CallOption) (*TrainFlowOperation, error) { +func (c *flowsGRPCClient) TrainFlow(ctx context.Context, req *cxpb.TrainFlowRequest, opts ...gax.CallOption) (*TrainFlowOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -409,7 +540,7 @@ func (c *FlowsClient) TrainFlow(ctx context.Context, req *cxpb.TrainFlowRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TrainFlow[0:len(c.CallOptions.TrainFlow):len(c.CallOptions.TrainFlow)], opts...) + opts = append((*c.CallOptions).TrainFlow[0:len((*c.CallOptions).TrainFlow):len((*c.CallOptions).TrainFlow)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -420,14 +551,11 @@ func (c *FlowsClient) TrainFlow(ctx context.Context, req *cxpb.TrainFlowRequest, return nil, err } return &TrainFlowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ValidateFlow validates the specified flow and creates or updates validation results. -// Please call this API after the training is completed to get the complete -// validation results. -func (c *FlowsClient) ValidateFlow(ctx context.Context, req *cxpb.ValidateFlowRequest, opts ...gax.CallOption) (*cxpb.FlowValidationResult, error) { +func (c *flowsGRPCClient) ValidateFlow(ctx context.Context, req *cxpb.ValidateFlowRequest, opts ...gax.CallOption) (*cxpb.FlowValidationResult, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -435,7 +563,7 @@ func (c *FlowsClient) ValidateFlow(ctx context.Context, req *cxpb.ValidateFlowRe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ValidateFlow[0:len(c.CallOptions.ValidateFlow):len(c.CallOptions.ValidateFlow)], opts...) + opts = append((*c.CallOptions).ValidateFlow[0:len((*c.CallOptions).ValidateFlow):len((*c.CallOptions).ValidateFlow)], opts...) var resp *cxpb.FlowValidationResult err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -448,9 +576,7 @@ func (c *FlowsClient) ValidateFlow(ctx context.Context, req *cxpb.ValidateFlowRe return resp, nil } -// GetFlowValidationResult gets the latest flow validation result. Flow validation is performed -// when ValidateFlow is called. -func (c *FlowsClient) GetFlowValidationResult(ctx context.Context, req *cxpb.GetFlowValidationResultRequest, opts ...gax.CallOption) (*cxpb.FlowValidationResult, error) { +func (c *flowsGRPCClient) GetFlowValidationResult(ctx context.Context, req *cxpb.GetFlowValidationResultRequest, opts ...gax.CallOption) (*cxpb.FlowValidationResult, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -458,7 +584,7 @@ func (c *FlowsClient) GetFlowValidationResult(ctx context.Context, req *cxpb.Get } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetFlowValidationResult[0:len(c.CallOptions.GetFlowValidationResult):len(c.CallOptions.GetFlowValidationResult)], opts...) + opts = append((*c.CallOptions).GetFlowValidationResult[0:len((*c.CallOptions).GetFlowValidationResult):len((*c.CallOptions).GetFlowValidationResult)], opts...) var resp *cxpb.FlowValidationResult err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -471,8 +597,7 @@ func (c *FlowsClient) GetFlowValidationResult(ctx context.Context, req *cxpb.Get return resp, nil } -// ImportFlow imports the specified flow to the specified agent from a binary file. -func (c *FlowsClient) ImportFlow(ctx context.Context, req *cxpb.ImportFlowRequest, opts ...gax.CallOption) (*ImportFlowOperation, error) { +func (c *flowsGRPCClient) ImportFlow(ctx context.Context, req *cxpb.ImportFlowRequest, opts ...gax.CallOption) (*ImportFlowOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -480,7 +605,7 @@ func (c *FlowsClient) ImportFlow(ctx context.Context, req *cxpb.ImportFlowReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportFlow[0:len(c.CallOptions.ImportFlow):len(c.CallOptions.ImportFlow)], opts...) + opts = append((*c.CallOptions).ImportFlow[0:len((*c.CallOptions).ImportFlow):len((*c.CallOptions).ImportFlow)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -491,15 +616,11 @@ func (c *FlowsClient) ImportFlow(ctx context.Context, req *cxpb.ImportFlowReques return nil, err } return &ImportFlowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ExportFlow exports the specified flow to a binary file. -// -// Note that resources (e.g. intents, entities, webhooks) that the flow -// references will also be exported. -func (c *FlowsClient) ExportFlow(ctx context.Context, req *cxpb.ExportFlowRequest, opts ...gax.CallOption) (*ExportFlowOperation, error) { +func (c *flowsGRPCClient) ExportFlow(ctx context.Context, req *cxpb.ExportFlowRequest, opts ...gax.CallOption) (*ExportFlowOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -507,7 +628,7 @@ func (c *FlowsClient) ExportFlow(ctx context.Context, req *cxpb.ExportFlowReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportFlow[0:len(c.CallOptions.ExportFlow):len(c.CallOptions.ExportFlow)], opts...) + opts = append((*c.CallOptions).ExportFlow[0:len((*c.CallOptions).ExportFlow):len((*c.CallOptions).ExportFlow)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -518,7 +639,7 @@ func (c *FlowsClient) ExportFlow(ctx context.Context, req *cxpb.ExportFlowReques return nil, err } return &ExportFlowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -529,9 +650,9 @@ type ExportFlowOperation struct { // ExportFlowOperation returns a new ExportFlowOperation from a given name. // The name must be that of a previously created ExportFlowOperation, possibly from a different process. -func (c *FlowsClient) ExportFlowOperation(name string) *ExportFlowOperation { +func (c *flowsGRPCClient) ExportFlowOperation(name string) *ExportFlowOperation { return &ExportFlowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -598,9 +719,9 @@ type ImportFlowOperation struct { // ImportFlowOperation returns a new ImportFlowOperation from a given name. // The name must be that of a previously created ImportFlowOperation, possibly from a different process. -func (c *FlowsClient) ImportFlowOperation(name string) *ImportFlowOperation { +func (c *flowsGRPCClient) ImportFlowOperation(name string) *ImportFlowOperation { return &ImportFlowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -667,9 +788,9 @@ type TrainFlowOperation struct { // TrainFlowOperation returns a new TrainFlowOperation from a given name. // The name must be that of a previously created TrainFlowOperation, possibly from a different process. -func (c *FlowsClient) TrainFlowOperation(name string) *TrainFlowOperation { +func (c *flowsGRPCClient) TrainFlowOperation(name string) *TrainFlowOperation { return &TrainFlowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dialogflow/cx/apiv3beta1/flows_client_example_test.go b/dialogflow/cx/apiv3beta1/flows_client_example_test.go index 90778cea00e3..b1aa5e02120f 100644 --- a/dialogflow/cx/apiv3beta1/flows_client_example_test.go +++ b/dialogflow/cx/apiv3beta1/flows_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewFlowsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleFlowsClient_CreateFlow() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateFlowRequest{ // TODO: Fill request struct fields. @@ -60,6 +61,7 @@ func ExampleFlowsClient_DeleteFlow() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteFlowRequest{ // TODO: Fill request struct fields. @@ -71,14 +73,12 @@ func ExampleFlowsClient_DeleteFlow() { } func ExampleFlowsClient_ListFlows() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListFlowsRequest{ // TODO: Fill request struct fields. @@ -98,13 +98,12 @@ func ExampleFlowsClient_ListFlows() { } func ExampleFlowsClient_GetFlow() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetFlowRequest{ // TODO: Fill request struct fields. @@ -118,13 +117,12 @@ func ExampleFlowsClient_GetFlow() { } func ExampleFlowsClient_UpdateFlow() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateFlowRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleFlowsClient_UpdateFlow() { } func ExampleFlowsClient_TrainFlow() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.TrainFlowRequest{ // TODO: Fill request struct fields. @@ -161,13 +158,12 @@ func ExampleFlowsClient_TrainFlow() { } func ExampleFlowsClient_ValidateFlow() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ValidateFlowRequest{ // TODO: Fill request struct fields. @@ -181,13 +177,12 @@ func ExampleFlowsClient_ValidateFlow() { } func ExampleFlowsClient_GetFlowValidationResult() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetFlowValidationResultRequest{ // TODO: Fill request struct fields. @@ -201,13 +196,12 @@ func ExampleFlowsClient_GetFlowValidationResult() { } func ExampleFlowsClient_ImportFlow() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ImportFlowRequest{ // TODO: Fill request struct fields. @@ -226,13 +220,12 @@ func ExampleFlowsClient_ImportFlow() { } func ExampleFlowsClient_ExportFlow() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ExportFlowRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3beta1/intents_client.go b/dialogflow/cx/apiv3beta1/intents_client.go index 9c64e1619839..89521c5ec1f5 100644 --- a/dialogflow/cx/apiv3beta1/intents_client.go +++ b/dialogflow/cx/apiv3beta1/intents_client.go @@ -46,7 +46,7 @@ type IntentsCallOptions struct { DeleteIntent []gax.CallOption } -func defaultIntentsClientOptions() []option.ClientOption { +func defaultIntentsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,103 @@ func defaultIntentsCallOptions() *IntentsCallOptions { } } +// internalIntentsClient is an interface that defines the methods availaible from Dialogflow API. +type internalIntentsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListIntents(context.Context, *cxpb.ListIntentsRequest, ...gax.CallOption) *IntentIterator + GetIntent(context.Context, *cxpb.GetIntentRequest, ...gax.CallOption) (*cxpb.Intent, error) + CreateIntent(context.Context, *cxpb.CreateIntentRequest, ...gax.CallOption) (*cxpb.Intent, error) + UpdateIntent(context.Context, *cxpb.UpdateIntentRequest, ...gax.CallOption) (*cxpb.Intent, error) + DeleteIntent(context.Context, *cxpb.DeleteIntentRequest, ...gax.CallOption) error +} + // IntentsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Intents. type IntentsClient struct { + // The internal transport-dependent client. + internalClient internalIntentsClient + + // The call options for this service. + CallOptions *IntentsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *IntentsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *IntentsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *IntentsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListIntents returns the list of all intents in the specified agent. +func (c *IntentsClient) ListIntents(ctx context.Context, req *cxpb.ListIntentsRequest, opts ...gax.CallOption) *IntentIterator { + return c.internalClient.ListIntents(ctx, req, opts...) +} + +// GetIntent retrieves the specified intent. +func (c *IntentsClient) GetIntent(ctx context.Context, req *cxpb.GetIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { + return c.internalClient.GetIntent(ctx, req, opts...) +} + +// CreateIntent creates an intent in the specified agent. +func (c *IntentsClient) CreateIntent(ctx context.Context, req *cxpb.CreateIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { + return c.internalClient.CreateIntent(ctx, req, opts...) +} + +// UpdateIntent updates the specified intent. +func (c *IntentsClient) UpdateIntent(ctx context.Context, req *cxpb.UpdateIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { + return c.internalClient.UpdateIntent(ctx, req, opts...) +} + +// DeleteIntent deletes the specified intent. +func (c *IntentsClient) DeleteIntent(ctx context.Context, req *cxpb.DeleteIntentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteIntent(ctx, req, opts...) +} + +// intentsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type intentsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing IntentsClient + CallOptions **IntentsCallOptions + // The gRPC API client. intentsClient cxpb.IntentsClient - // The call options for this service. - CallOptions *IntentsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewIntentsClient creates a new intents client. +// NewIntentsClient creates a new intents client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Intents. func NewIntentsClient(ctx context.Context, opts ...option.ClientOption) (*IntentsClient, error) { - clientOpts := defaultIntentsClientOptions() - + clientOpts := defaultIntentsGRPCClientOptions() if newIntentsClientHook != nil { hookOpts, err := newIntentsClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,45 +232,47 @@ func NewIntentsClient(ctx context.Context, opts ...option.ClientOption) (*Intent if err != nil { return nil, err } - c := &IntentsClient{ + client := IntentsClient{CallOptions: defaultIntentsCallOptions()} + + c := &intentsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultIntentsCallOptions(), - - intentsClient: cxpb.NewIntentsClient(connPool), + intentsClient: cxpb.NewIntentsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *IntentsClient) Connection() *grpc.ClientConn { +func (c *intentsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *IntentsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *IntentsClient) setGoogleClientInfo(keyval ...string) { +func (c *intentsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListIntents returns the list of all intents in the specified agent. -func (c *IntentsClient) ListIntents(ctx context.Context, req *cxpb.ListIntentsRequest, opts ...gax.CallOption) *IntentIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *intentsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *intentsGRPCClient) ListIntents(ctx context.Context, req *cxpb.ListIntentsRequest, opts ...gax.CallOption) *IntentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListIntents[0:len(c.CallOptions.ListIntents):len(c.CallOptions.ListIntents)], opts...) + opts = append((*c.CallOptions).ListIntents[0:len((*c.CallOptions).ListIntents):len((*c.CallOptions).ListIntents)], opts...) it := &IntentIterator{} req = proto.Clone(req).(*cxpb.ListIntentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Intent, string, error) { @@ -236,8 +309,7 @@ func (c *IntentsClient) ListIntents(ctx context.Context, req *cxpb.ListIntentsRe return it } -// GetIntent retrieves the specified intent. -func (c *IntentsClient) GetIntent(ctx context.Context, req *cxpb.GetIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { +func (c *intentsGRPCClient) GetIntent(ctx context.Context, req *cxpb.GetIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -245,7 +317,7 @@ func (c *IntentsClient) GetIntent(ctx context.Context, req *cxpb.GetIntentReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIntent[0:len(c.CallOptions.GetIntent):len(c.CallOptions.GetIntent)], opts...) + opts = append((*c.CallOptions).GetIntent[0:len((*c.CallOptions).GetIntent):len((*c.CallOptions).GetIntent)], opts...) var resp *cxpb.Intent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -258,8 +330,7 @@ func (c *IntentsClient) GetIntent(ctx context.Context, req *cxpb.GetIntentReques return resp, nil } -// CreateIntent creates an intent in the specified agent. -func (c *IntentsClient) CreateIntent(ctx context.Context, req *cxpb.CreateIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { +func (c *intentsGRPCClient) CreateIntent(ctx context.Context, req *cxpb.CreateIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -267,7 +338,7 @@ func (c *IntentsClient) CreateIntent(ctx context.Context, req *cxpb.CreateIntent } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateIntent[0:len(c.CallOptions.CreateIntent):len(c.CallOptions.CreateIntent)], opts...) + opts = append((*c.CallOptions).CreateIntent[0:len((*c.CallOptions).CreateIntent):len((*c.CallOptions).CreateIntent)], opts...) var resp *cxpb.Intent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -280,8 +351,7 @@ func (c *IntentsClient) CreateIntent(ctx context.Context, req *cxpb.CreateIntent return resp, nil } -// UpdateIntent updates the specified intent. -func (c *IntentsClient) UpdateIntent(ctx context.Context, req *cxpb.UpdateIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { +func (c *intentsGRPCClient) UpdateIntent(ctx context.Context, req *cxpb.UpdateIntentRequest, opts ...gax.CallOption) (*cxpb.Intent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -289,7 +359,7 @@ func (c *IntentsClient) UpdateIntent(ctx context.Context, req *cxpb.UpdateIntent } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "intent.name", url.QueryEscape(req.GetIntent().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateIntent[0:len(c.CallOptions.UpdateIntent):len(c.CallOptions.UpdateIntent)], opts...) + opts = append((*c.CallOptions).UpdateIntent[0:len((*c.CallOptions).UpdateIntent):len((*c.CallOptions).UpdateIntent)], opts...) var resp *cxpb.Intent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -302,8 +372,7 @@ func (c *IntentsClient) UpdateIntent(ctx context.Context, req *cxpb.UpdateIntent return resp, nil } -// DeleteIntent deletes the specified intent. -func (c *IntentsClient) DeleteIntent(ctx context.Context, req *cxpb.DeleteIntentRequest, opts ...gax.CallOption) error { +func (c *intentsGRPCClient) DeleteIntent(ctx context.Context, req *cxpb.DeleteIntentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -311,7 +380,7 @@ func (c *IntentsClient) DeleteIntent(ctx context.Context, req *cxpb.DeleteIntent } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteIntent[0:len(c.CallOptions.DeleteIntent):len(c.CallOptions.DeleteIntent)], opts...) + opts = append((*c.CallOptions).DeleteIntent[0:len((*c.CallOptions).DeleteIntent):len((*c.CallOptions).DeleteIntent)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.intentsClient.DeleteIntent(ctx, req, settings.GRPC...) diff --git a/dialogflow/cx/apiv3beta1/intents_client_example_test.go b/dialogflow/cx/apiv3beta1/intents_client_example_test.go index 6d89b961ca7f..1eef51bc6fbb 100644 --- a/dialogflow/cx/apiv3beta1/intents_client_example_test.go +++ b/dialogflow/cx/apiv3beta1/intents_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewIntentsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleIntentsClient_ListIntents() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListIntentsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleIntentsClient_ListIntents() { } func ExampleIntentsClient_GetIntent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetIntentRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleIntentsClient_GetIntent() { } func ExampleIntentsClient_CreateIntent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateIntentRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleIntentsClient_CreateIntent() { } func ExampleIntentsClient_UpdateIntent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateIntentRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleIntentsClient_DeleteIntent() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteIntentRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3beta1/pages_client.go b/dialogflow/cx/apiv3beta1/pages_client.go index 7b9b305e153c..6d352d3e21a4 100644 --- a/dialogflow/cx/apiv3beta1/pages_client.go +++ b/dialogflow/cx/apiv3beta1/pages_client.go @@ -46,7 +46,7 @@ type PagesCallOptions struct { DeletePage []gax.CallOption } -func defaultPagesClientOptions() []option.ClientOption { +func defaultPagesGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,103 @@ func defaultPagesCallOptions() *PagesCallOptions { } } +// internalPagesClient is an interface that defines the methods availaible from Dialogflow API. +type internalPagesClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListPages(context.Context, *cxpb.ListPagesRequest, ...gax.CallOption) *PageIterator + GetPage(context.Context, *cxpb.GetPageRequest, ...gax.CallOption) (*cxpb.Page, error) + CreatePage(context.Context, *cxpb.CreatePageRequest, ...gax.CallOption) (*cxpb.Page, error) + UpdatePage(context.Context, *cxpb.UpdatePageRequest, ...gax.CallOption) (*cxpb.Page, error) + DeletePage(context.Context, *cxpb.DeletePageRequest, ...gax.CallOption) error +} + // PagesClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing [Pages][google.cloud.dialogflow.cx.v3beta1.Page (at http://google.cloud.dialogflow.cx.v3beta1.Page)]. type PagesClient struct { + // The internal transport-dependent client. + internalClient internalPagesClient + + // The call options for this service. + CallOptions *PagesCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *PagesClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *PagesClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *PagesClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListPages returns the list of all pages in the specified flow. +func (c *PagesClient) ListPages(ctx context.Context, req *cxpb.ListPagesRequest, opts ...gax.CallOption) *PageIterator { + return c.internalClient.ListPages(ctx, req, opts...) +} + +// GetPage retrieves the specified page. +func (c *PagesClient) GetPage(ctx context.Context, req *cxpb.GetPageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { + return c.internalClient.GetPage(ctx, req, opts...) +} + +// CreatePage creates a page in the specified flow. +func (c *PagesClient) CreatePage(ctx context.Context, req *cxpb.CreatePageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { + return c.internalClient.CreatePage(ctx, req, opts...) +} + +// UpdatePage updates the specified page. +func (c *PagesClient) UpdatePage(ctx context.Context, req *cxpb.UpdatePageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { + return c.internalClient.UpdatePage(ctx, req, opts...) +} + +// DeletePage deletes the specified page. +func (c *PagesClient) DeletePage(ctx context.Context, req *cxpb.DeletePageRequest, opts ...gax.CallOption) error { + return c.internalClient.DeletePage(ctx, req, opts...) +} + +// pagesGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type pagesGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing PagesClient + CallOptions **PagesCallOptions + // The gRPC API client. pagesClient cxpb.PagesClient - // The call options for this service. - CallOptions *PagesCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewPagesClient creates a new pages client. +// NewPagesClient creates a new pages client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing [Pages][google.cloud.dialogflow.cx.v3beta1.Page (at http://google.cloud.dialogflow.cx.v3beta1.Page)]. func NewPagesClient(ctx context.Context, opts ...option.ClientOption) (*PagesClient, error) { - clientOpts := defaultPagesClientOptions() - + clientOpts := defaultPagesGRPCClientOptions() if newPagesClientHook != nil { hookOpts, err := newPagesClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,45 +232,47 @@ func NewPagesClient(ctx context.Context, opts ...option.ClientOption) (*PagesCli if err != nil { return nil, err } - c := &PagesClient{ + client := PagesClient{CallOptions: defaultPagesCallOptions()} + + c := &pagesGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultPagesCallOptions(), - - pagesClient: cxpb.NewPagesClient(connPool), + pagesClient: cxpb.NewPagesClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *PagesClient) Connection() *grpc.ClientConn { +func (c *pagesGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *PagesClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *PagesClient) setGoogleClientInfo(keyval ...string) { +func (c *pagesGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListPages returns the list of all pages in the specified flow. -func (c *PagesClient) ListPages(ctx context.Context, req *cxpb.ListPagesRequest, opts ...gax.CallOption) *PageIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *pagesGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *pagesGRPCClient) ListPages(ctx context.Context, req *cxpb.ListPagesRequest, opts ...gax.CallOption) *PageIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListPages[0:len(c.CallOptions.ListPages):len(c.CallOptions.ListPages)], opts...) + opts = append((*c.CallOptions).ListPages[0:len((*c.CallOptions).ListPages):len((*c.CallOptions).ListPages)], opts...) it := &PageIterator{} req = proto.Clone(req).(*cxpb.ListPagesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Page, string, error) { @@ -236,8 +309,7 @@ func (c *PagesClient) ListPages(ctx context.Context, req *cxpb.ListPagesRequest, return it } -// GetPage retrieves the specified page. -func (c *PagesClient) GetPage(ctx context.Context, req *cxpb.GetPageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { +func (c *pagesGRPCClient) GetPage(ctx context.Context, req *cxpb.GetPageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -245,7 +317,7 @@ func (c *PagesClient) GetPage(ctx context.Context, req *cxpb.GetPageRequest, opt } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetPage[0:len(c.CallOptions.GetPage):len(c.CallOptions.GetPage)], opts...) + opts = append((*c.CallOptions).GetPage[0:len((*c.CallOptions).GetPage):len((*c.CallOptions).GetPage)], opts...) var resp *cxpb.Page err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -258,8 +330,7 @@ func (c *PagesClient) GetPage(ctx context.Context, req *cxpb.GetPageRequest, opt return resp, nil } -// CreatePage creates a page in the specified flow. -func (c *PagesClient) CreatePage(ctx context.Context, req *cxpb.CreatePageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { +func (c *pagesGRPCClient) CreatePage(ctx context.Context, req *cxpb.CreatePageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -267,7 +338,7 @@ func (c *PagesClient) CreatePage(ctx context.Context, req *cxpb.CreatePageReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreatePage[0:len(c.CallOptions.CreatePage):len(c.CallOptions.CreatePage)], opts...) + opts = append((*c.CallOptions).CreatePage[0:len((*c.CallOptions).CreatePage):len((*c.CallOptions).CreatePage)], opts...) var resp *cxpb.Page err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -280,8 +351,7 @@ func (c *PagesClient) CreatePage(ctx context.Context, req *cxpb.CreatePageReques return resp, nil } -// UpdatePage updates the specified page. -func (c *PagesClient) UpdatePage(ctx context.Context, req *cxpb.UpdatePageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { +func (c *pagesGRPCClient) UpdatePage(ctx context.Context, req *cxpb.UpdatePageRequest, opts ...gax.CallOption) (*cxpb.Page, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -289,7 +359,7 @@ func (c *PagesClient) UpdatePage(ctx context.Context, req *cxpb.UpdatePageReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "page.name", url.QueryEscape(req.GetPage().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdatePage[0:len(c.CallOptions.UpdatePage):len(c.CallOptions.UpdatePage)], opts...) + opts = append((*c.CallOptions).UpdatePage[0:len((*c.CallOptions).UpdatePage):len((*c.CallOptions).UpdatePage)], opts...) var resp *cxpb.Page err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -302,8 +372,7 @@ func (c *PagesClient) UpdatePage(ctx context.Context, req *cxpb.UpdatePageReques return resp, nil } -// DeletePage deletes the specified page. -func (c *PagesClient) DeletePage(ctx context.Context, req *cxpb.DeletePageRequest, opts ...gax.CallOption) error { +func (c *pagesGRPCClient) DeletePage(ctx context.Context, req *cxpb.DeletePageRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -311,7 +380,7 @@ func (c *PagesClient) DeletePage(ctx context.Context, req *cxpb.DeletePageReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeletePage[0:len(c.CallOptions.DeletePage):len(c.CallOptions.DeletePage)], opts...) + opts = append((*c.CallOptions).DeletePage[0:len((*c.CallOptions).DeletePage):len((*c.CallOptions).DeletePage)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.pagesClient.DeletePage(ctx, req, settings.GRPC...) diff --git a/dialogflow/cx/apiv3beta1/pages_client_example_test.go b/dialogflow/cx/apiv3beta1/pages_client_example_test.go index e7e9f72164ca..e4e4c10a31e4 100644 --- a/dialogflow/cx/apiv3beta1/pages_client_example_test.go +++ b/dialogflow/cx/apiv3beta1/pages_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewPagesClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExamplePagesClient_ListPages() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewPagesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListPagesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExamplePagesClient_ListPages() { } func ExamplePagesClient_GetPage() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewPagesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetPageRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExamplePagesClient_GetPage() { } func ExamplePagesClient_CreatePage() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewPagesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreatePageRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExamplePagesClient_CreatePage() { } func ExamplePagesClient_UpdatePage() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewPagesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdatePageRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExamplePagesClient_DeletePage() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeletePageRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3beta1/security_settings_client.go b/dialogflow/cx/apiv3beta1/security_settings_client.go index 6a8c65ee0658..8b17954b6b9b 100644 --- a/dialogflow/cx/apiv3beta1/security_settings_client.go +++ b/dialogflow/cx/apiv3beta1/security_settings_client.go @@ -46,7 +46,7 @@ type SecuritySettingsCallOptions struct { DeleteSecuritySettings []gax.CallOption } -func defaultSecuritySettingsClientOptions() []option.ClientOption { +func defaultSecuritySettingsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,104 @@ func defaultSecuritySettingsCallOptions() *SecuritySettingsCallOptions { } } +// internalSecuritySettingsClient is an interface that defines the methods availaible from Dialogflow API. +type internalSecuritySettingsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateSecuritySettings(context.Context, *cxpb.CreateSecuritySettingsRequest, ...gax.CallOption) (*cxpb.SecuritySettings, error) + GetSecuritySettings(context.Context, *cxpb.GetSecuritySettingsRequest, ...gax.CallOption) (*cxpb.SecuritySettings, error) + UpdateSecuritySettings(context.Context, *cxpb.UpdateSecuritySettingsRequest, ...gax.CallOption) (*cxpb.SecuritySettings, error) + ListSecuritySettings(context.Context, *cxpb.ListSecuritySettingsRequest, ...gax.CallOption) *SecuritySettingsIterator + DeleteSecuritySettings(context.Context, *cxpb.DeleteSecuritySettingsRequest, ...gax.CallOption) error +} + // SecuritySettingsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing security settings for Dialogflow. type SecuritySettingsClient struct { + // The internal transport-dependent client. + internalClient internalSecuritySettingsClient + + // The call options for this service. + CallOptions *SecuritySettingsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *SecuritySettingsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *SecuritySettingsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *SecuritySettingsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateSecuritySettings create security settings in the specified location. +func (c *SecuritySettingsClient) CreateSecuritySettings(ctx context.Context, req *cxpb.CreateSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { + return c.internalClient.CreateSecuritySettings(ctx, req, opts...) +} + +// GetSecuritySettings retrieves the specified SecuritySettings. +// The returned settings may be stale by up to 1 minute. +func (c *SecuritySettingsClient) GetSecuritySettings(ctx context.Context, req *cxpb.GetSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { + return c.internalClient.GetSecuritySettings(ctx, req, opts...) +} + +// UpdateSecuritySettings updates the specified SecuritySettings. +func (c *SecuritySettingsClient) UpdateSecuritySettings(ctx context.Context, req *cxpb.UpdateSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { + return c.internalClient.UpdateSecuritySettings(ctx, req, opts...) +} + +// ListSecuritySettings returns the list of all security settings in the specified location. +func (c *SecuritySettingsClient) ListSecuritySettings(ctx context.Context, req *cxpb.ListSecuritySettingsRequest, opts ...gax.CallOption) *SecuritySettingsIterator { + return c.internalClient.ListSecuritySettings(ctx, req, opts...) +} + +// DeleteSecuritySettings deletes the specified SecuritySettings. +func (c *SecuritySettingsClient) DeleteSecuritySettings(ctx context.Context, req *cxpb.DeleteSecuritySettingsRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteSecuritySettings(ctx, req, opts...) +} + +// securitySettingsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type securitySettingsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing SecuritySettingsClient + CallOptions **SecuritySettingsCallOptions + // The gRPC API client. securitySettingsClient cxpb.SecuritySettingsServiceClient - // The call options for this service. - CallOptions *SecuritySettingsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewSecuritySettingsClient creates a new security settings service client. +// NewSecuritySettingsClient creates a new security settings service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing security settings for Dialogflow. func NewSecuritySettingsClient(ctx context.Context, opts ...option.ClientOption) (*SecuritySettingsClient, error) { - clientOpts := defaultSecuritySettingsClientOptions() - + clientOpts := defaultSecuritySettingsGRPCClientOptions() if newSecuritySettingsClientHook != nil { hookOpts, err := newSecuritySettingsClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,42 +233,44 @@ func NewSecuritySettingsClient(ctx context.Context, opts ...option.ClientOption) if err != nil { return nil, err } - c := &SecuritySettingsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultSecuritySettingsCallOptions(), + client := SecuritySettingsClient{CallOptions: defaultSecuritySettingsCallOptions()} + c := &securitySettingsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, securitySettingsClient: cxpb.NewSecuritySettingsServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *SecuritySettingsClient) Connection() *grpc.ClientConn { +func (c *securitySettingsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *SecuritySettingsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *SecuritySettingsClient) setGoogleClientInfo(keyval ...string) { +func (c *securitySettingsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateSecuritySettings create security settings in the specified location. -func (c *SecuritySettingsClient) CreateSecuritySettings(ctx context.Context, req *cxpb.CreateSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *securitySettingsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *securitySettingsGRPCClient) CreateSecuritySettings(ctx context.Context, req *cxpb.CreateSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -204,7 +278,7 @@ func (c *SecuritySettingsClient) CreateSecuritySettings(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSecuritySettings[0:len(c.CallOptions.CreateSecuritySettings):len(c.CallOptions.CreateSecuritySettings)], opts...) + opts = append((*c.CallOptions).CreateSecuritySettings[0:len((*c.CallOptions).CreateSecuritySettings):len((*c.CallOptions).CreateSecuritySettings)], opts...) var resp *cxpb.SecuritySettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -217,9 +291,7 @@ func (c *SecuritySettingsClient) CreateSecuritySettings(ctx context.Context, req return resp, nil } -// GetSecuritySettings retrieves the specified SecuritySettings. -// The returned settings may be stale by up to 1 minute. -func (c *SecuritySettingsClient) GetSecuritySettings(ctx context.Context, req *cxpb.GetSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { +func (c *securitySettingsGRPCClient) GetSecuritySettings(ctx context.Context, req *cxpb.GetSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -227,7 +299,7 @@ func (c *SecuritySettingsClient) GetSecuritySettings(ctx context.Context, req *c } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSecuritySettings[0:len(c.CallOptions.GetSecuritySettings):len(c.CallOptions.GetSecuritySettings)], opts...) + opts = append((*c.CallOptions).GetSecuritySettings[0:len((*c.CallOptions).GetSecuritySettings):len((*c.CallOptions).GetSecuritySettings)], opts...) var resp *cxpb.SecuritySettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -240,8 +312,7 @@ func (c *SecuritySettingsClient) GetSecuritySettings(ctx context.Context, req *c return resp, nil } -// UpdateSecuritySettings updates the specified SecuritySettings. -func (c *SecuritySettingsClient) UpdateSecuritySettings(ctx context.Context, req *cxpb.UpdateSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { +func (c *securitySettingsGRPCClient) UpdateSecuritySettings(ctx context.Context, req *cxpb.UpdateSecuritySettingsRequest, opts ...gax.CallOption) (*cxpb.SecuritySettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -249,7 +320,7 @@ func (c *SecuritySettingsClient) UpdateSecuritySettings(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "security_settings.name", url.QueryEscape(req.GetSecuritySettings().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSecuritySettings[0:len(c.CallOptions.UpdateSecuritySettings):len(c.CallOptions.UpdateSecuritySettings)], opts...) + opts = append((*c.CallOptions).UpdateSecuritySettings[0:len((*c.CallOptions).UpdateSecuritySettings):len((*c.CallOptions).UpdateSecuritySettings)], opts...) var resp *cxpb.SecuritySettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -262,11 +333,10 @@ func (c *SecuritySettingsClient) UpdateSecuritySettings(ctx context.Context, req return resp, nil } -// ListSecuritySettings returns the list of all security settings in the specified location. -func (c *SecuritySettingsClient) ListSecuritySettings(ctx context.Context, req *cxpb.ListSecuritySettingsRequest, opts ...gax.CallOption) *SecuritySettingsIterator { +func (c *securitySettingsGRPCClient) ListSecuritySettings(ctx context.Context, req *cxpb.ListSecuritySettingsRequest, opts ...gax.CallOption) *SecuritySettingsIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSecuritySettings[0:len(c.CallOptions.ListSecuritySettings):len(c.CallOptions.ListSecuritySettings)], opts...) + opts = append((*c.CallOptions).ListSecuritySettings[0:len((*c.CallOptions).ListSecuritySettings):len((*c.CallOptions).ListSecuritySettings)], opts...) it := &SecuritySettingsIterator{} req = proto.Clone(req).(*cxpb.ListSecuritySettingsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.SecuritySettings, string, error) { @@ -303,8 +373,7 @@ func (c *SecuritySettingsClient) ListSecuritySettings(ctx context.Context, req * return it } -// DeleteSecuritySettings deletes the specified SecuritySettings. -func (c *SecuritySettingsClient) DeleteSecuritySettings(ctx context.Context, req *cxpb.DeleteSecuritySettingsRequest, opts ...gax.CallOption) error { +func (c *securitySettingsGRPCClient) DeleteSecuritySettings(ctx context.Context, req *cxpb.DeleteSecuritySettingsRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -312,7 +381,7 @@ func (c *SecuritySettingsClient) DeleteSecuritySettings(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteSecuritySettings[0:len(c.CallOptions.DeleteSecuritySettings):len(c.CallOptions.DeleteSecuritySettings)], opts...) + opts = append((*c.CallOptions).DeleteSecuritySettings[0:len((*c.CallOptions).DeleteSecuritySettings):len((*c.CallOptions).DeleteSecuritySettings)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.securitySettingsClient.DeleteSecuritySettings(ctx, req, settings.GRPC...) diff --git a/dialogflow/cx/apiv3beta1/security_settings_client_example_test.go b/dialogflow/cx/apiv3beta1/security_settings_client_example_test.go index 82eb30922497..31c326f5be71 100644 --- a/dialogflow/cx/apiv3beta1/security_settings_client_example_test.go +++ b/dialogflow/cx/apiv3beta1/security_settings_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewSecuritySettingsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleSecuritySettingsClient_CreateSecuritySettings() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSecuritySettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateSecuritySettingsRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleSecuritySettingsClient_CreateSecuritySettings() { } func ExampleSecuritySettingsClient_GetSecuritySettings() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSecuritySettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetSecuritySettingsRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleSecuritySettingsClient_GetSecuritySettings() { } func ExampleSecuritySettingsClient_UpdateSecuritySettings() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSecuritySettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateSecuritySettingsRequest{ // TODO: Fill request struct fields. @@ -95,14 +94,12 @@ func ExampleSecuritySettingsClient_UpdateSecuritySettings() { } func ExampleSecuritySettingsClient_ListSecuritySettings() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewSecuritySettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListSecuritySettingsRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleSecuritySettingsClient_DeleteSecuritySettings() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteSecuritySettingsRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3beta1/session_entity_types_client.go b/dialogflow/cx/apiv3beta1/session_entity_types_client.go index 6767ac738900..caa6870dcc5f 100644 --- a/dialogflow/cx/apiv3beta1/session_entity_types_client.go +++ b/dialogflow/cx/apiv3beta1/session_entity_types_client.go @@ -46,7 +46,7 @@ type SessionEntityTypesCallOptions struct { DeleteSessionEntityType []gax.CallOption } -func defaultSessionEntityTypesClientOptions() []option.ClientOption { +func defaultSessionEntityTypesGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,103 @@ func defaultSessionEntityTypesCallOptions() *SessionEntityTypesCallOptions { } } +// internalSessionEntityTypesClient is an interface that defines the methods availaible from Dialogflow API. +type internalSessionEntityTypesClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListSessionEntityTypes(context.Context, *cxpb.ListSessionEntityTypesRequest, ...gax.CallOption) *SessionEntityTypeIterator + GetSessionEntityType(context.Context, *cxpb.GetSessionEntityTypeRequest, ...gax.CallOption) (*cxpb.SessionEntityType, error) + CreateSessionEntityType(context.Context, *cxpb.CreateSessionEntityTypeRequest, ...gax.CallOption) (*cxpb.SessionEntityType, error) + UpdateSessionEntityType(context.Context, *cxpb.UpdateSessionEntityTypeRequest, ...gax.CallOption) (*cxpb.SessionEntityType, error) + DeleteSessionEntityType(context.Context, *cxpb.DeleteSessionEntityTypeRequest, ...gax.CallOption) error +} + // SessionEntityTypesClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing SessionEntityTypes. type SessionEntityTypesClient struct { + // The internal transport-dependent client. + internalClient internalSessionEntityTypesClient + + // The call options for this service. + CallOptions *SessionEntityTypesCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *SessionEntityTypesClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *SessionEntityTypesClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *SessionEntityTypesClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListSessionEntityTypes returns the list of all session entity types in the specified session. +func (c *SessionEntityTypesClient) ListSessionEntityTypes(ctx context.Context, req *cxpb.ListSessionEntityTypesRequest, opts ...gax.CallOption) *SessionEntityTypeIterator { + return c.internalClient.ListSessionEntityTypes(ctx, req, opts...) +} + +// GetSessionEntityType retrieves the specified session entity type. +func (c *SessionEntityTypesClient) GetSessionEntityType(ctx context.Context, req *cxpb.GetSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { + return c.internalClient.GetSessionEntityType(ctx, req, opts...) +} + +// CreateSessionEntityType creates a session entity type. +func (c *SessionEntityTypesClient) CreateSessionEntityType(ctx context.Context, req *cxpb.CreateSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { + return c.internalClient.CreateSessionEntityType(ctx, req, opts...) +} + +// UpdateSessionEntityType updates the specified session entity type. +func (c *SessionEntityTypesClient) UpdateSessionEntityType(ctx context.Context, req *cxpb.UpdateSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { + return c.internalClient.UpdateSessionEntityType(ctx, req, opts...) +} + +// DeleteSessionEntityType deletes the specified session entity type. +func (c *SessionEntityTypesClient) DeleteSessionEntityType(ctx context.Context, req *cxpb.DeleteSessionEntityTypeRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteSessionEntityType(ctx, req, opts...) +} + +// sessionEntityTypesGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type sessionEntityTypesGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing SessionEntityTypesClient + CallOptions **SessionEntityTypesCallOptions + // The gRPC API client. sessionEntityTypesClient cxpb.SessionEntityTypesClient - // The call options for this service. - CallOptions *SessionEntityTypesCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewSessionEntityTypesClient creates a new session entity types client. +// NewSessionEntityTypesClient creates a new session entity types client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing SessionEntityTypes. func NewSessionEntityTypesClient(ctx context.Context, opts ...option.ClientOption) (*SessionEntityTypesClient, error) { - clientOpts := defaultSessionEntityTypesClientOptions() - + clientOpts := defaultSessionEntityTypesGRPCClientOptions() if newSessionEntityTypesClientHook != nil { hookOpts, err := newSessionEntityTypesClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,45 +232,47 @@ func NewSessionEntityTypesClient(ctx context.Context, opts ...option.ClientOptio if err != nil { return nil, err } - c := &SessionEntityTypesClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultSessionEntityTypesCallOptions(), + client := SessionEntityTypesClient{CallOptions: defaultSessionEntityTypesCallOptions()} + c := &sessionEntityTypesGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, sessionEntityTypesClient: cxpb.NewSessionEntityTypesClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *SessionEntityTypesClient) Connection() *grpc.ClientConn { +func (c *sessionEntityTypesGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *SessionEntityTypesClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *SessionEntityTypesClient) setGoogleClientInfo(keyval ...string) { +func (c *sessionEntityTypesGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListSessionEntityTypes returns the list of all session entity types in the specified session. -func (c *SessionEntityTypesClient) ListSessionEntityTypes(ctx context.Context, req *cxpb.ListSessionEntityTypesRequest, opts ...gax.CallOption) *SessionEntityTypeIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *sessionEntityTypesGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *sessionEntityTypesGRPCClient) ListSessionEntityTypes(ctx context.Context, req *cxpb.ListSessionEntityTypesRequest, opts ...gax.CallOption) *SessionEntityTypeIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSessionEntityTypes[0:len(c.CallOptions.ListSessionEntityTypes):len(c.CallOptions.ListSessionEntityTypes)], opts...) + opts = append((*c.CallOptions).ListSessionEntityTypes[0:len((*c.CallOptions).ListSessionEntityTypes):len((*c.CallOptions).ListSessionEntityTypes)], opts...) it := &SessionEntityTypeIterator{} req = proto.Clone(req).(*cxpb.ListSessionEntityTypesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.SessionEntityType, string, error) { @@ -236,8 +309,7 @@ func (c *SessionEntityTypesClient) ListSessionEntityTypes(ctx context.Context, r return it } -// GetSessionEntityType retrieves the specified session entity type. -func (c *SessionEntityTypesClient) GetSessionEntityType(ctx context.Context, req *cxpb.GetSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { +func (c *sessionEntityTypesGRPCClient) GetSessionEntityType(ctx context.Context, req *cxpb.GetSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -245,7 +317,7 @@ func (c *SessionEntityTypesClient) GetSessionEntityType(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSessionEntityType[0:len(c.CallOptions.GetSessionEntityType):len(c.CallOptions.GetSessionEntityType)], opts...) + opts = append((*c.CallOptions).GetSessionEntityType[0:len((*c.CallOptions).GetSessionEntityType):len((*c.CallOptions).GetSessionEntityType)], opts...) var resp *cxpb.SessionEntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -258,8 +330,7 @@ func (c *SessionEntityTypesClient) GetSessionEntityType(ctx context.Context, req return resp, nil } -// CreateSessionEntityType creates a session entity type. -func (c *SessionEntityTypesClient) CreateSessionEntityType(ctx context.Context, req *cxpb.CreateSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { +func (c *sessionEntityTypesGRPCClient) CreateSessionEntityType(ctx context.Context, req *cxpb.CreateSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -267,7 +338,7 @@ func (c *SessionEntityTypesClient) CreateSessionEntityType(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSessionEntityType[0:len(c.CallOptions.CreateSessionEntityType):len(c.CallOptions.CreateSessionEntityType)], opts...) + opts = append((*c.CallOptions).CreateSessionEntityType[0:len((*c.CallOptions).CreateSessionEntityType):len((*c.CallOptions).CreateSessionEntityType)], opts...) var resp *cxpb.SessionEntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -280,8 +351,7 @@ func (c *SessionEntityTypesClient) CreateSessionEntityType(ctx context.Context, return resp, nil } -// UpdateSessionEntityType updates the specified session entity type. -func (c *SessionEntityTypesClient) UpdateSessionEntityType(ctx context.Context, req *cxpb.UpdateSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { +func (c *sessionEntityTypesGRPCClient) UpdateSessionEntityType(ctx context.Context, req *cxpb.UpdateSessionEntityTypeRequest, opts ...gax.CallOption) (*cxpb.SessionEntityType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -289,7 +359,7 @@ func (c *SessionEntityTypesClient) UpdateSessionEntityType(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session_entity_type.name", url.QueryEscape(req.GetSessionEntityType().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSessionEntityType[0:len(c.CallOptions.UpdateSessionEntityType):len(c.CallOptions.UpdateSessionEntityType)], opts...) + opts = append((*c.CallOptions).UpdateSessionEntityType[0:len((*c.CallOptions).UpdateSessionEntityType):len((*c.CallOptions).UpdateSessionEntityType)], opts...) var resp *cxpb.SessionEntityType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -302,8 +372,7 @@ func (c *SessionEntityTypesClient) UpdateSessionEntityType(ctx context.Context, return resp, nil } -// DeleteSessionEntityType deletes the specified session entity type. -func (c *SessionEntityTypesClient) DeleteSessionEntityType(ctx context.Context, req *cxpb.DeleteSessionEntityTypeRequest, opts ...gax.CallOption) error { +func (c *sessionEntityTypesGRPCClient) DeleteSessionEntityType(ctx context.Context, req *cxpb.DeleteSessionEntityTypeRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -311,7 +380,7 @@ func (c *SessionEntityTypesClient) DeleteSessionEntityType(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteSessionEntityType[0:len(c.CallOptions.DeleteSessionEntityType):len(c.CallOptions.DeleteSessionEntityType)], opts...) + opts = append((*c.CallOptions).DeleteSessionEntityType[0:len((*c.CallOptions).DeleteSessionEntityType):len((*c.CallOptions).DeleteSessionEntityType)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.sessionEntityTypesClient.DeleteSessionEntityType(ctx, req, settings.GRPC...) diff --git a/dialogflow/cx/apiv3beta1/session_entity_types_client_example_test.go b/dialogflow/cx/apiv3beta1/session_entity_types_client_example_test.go index 159e7de972e4..13024ba97cce 100644 --- a/dialogflow/cx/apiv3beta1/session_entity_types_client_example_test.go +++ b/dialogflow/cx/apiv3beta1/session_entity_types_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewSessionEntityTypesClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleSessionEntityTypesClient_ListSessionEntityTypes() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListSessionEntityTypesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleSessionEntityTypesClient_ListSessionEntityTypes() { } func ExampleSessionEntityTypesClient_GetSessionEntityType() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetSessionEntityTypeRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleSessionEntityTypesClient_GetSessionEntityType() { } func ExampleSessionEntityTypesClient_CreateSessionEntityType() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateSessionEntityTypeRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleSessionEntityTypesClient_CreateSessionEntityType() { } func ExampleSessionEntityTypesClient_UpdateSessionEntityType() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateSessionEntityTypeRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleSessionEntityTypesClient_DeleteSessionEntityType() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteSessionEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3beta1/sessions_client.go b/dialogflow/cx/apiv3beta1/sessions_client.go index d89ca1936422..14b800681024 100644 --- a/dialogflow/cx/apiv3beta1/sessions_client.go +++ b/dialogflow/cx/apiv3beta1/sessions_client.go @@ -43,7 +43,7 @@ type SessionsCallOptions struct { FulfillIntent []gax.CallOption } -func defaultSessionsClientOptions() []option.ClientOption { +func defaultSessionsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -94,34 +94,117 @@ func defaultSessionsCallOptions() *SessionsCallOptions { } } +// internalSessionsClient is an interface that defines the methods availaible from Dialogflow API. +type internalSessionsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + DetectIntent(context.Context, *cxpb.DetectIntentRequest, ...gax.CallOption) (*cxpb.DetectIntentResponse, error) + StreamingDetectIntent(context.Context, ...gax.CallOption) (cxpb.Sessions_StreamingDetectIntentClient, error) + MatchIntent(context.Context, *cxpb.MatchIntentRequest, ...gax.CallOption) (*cxpb.MatchIntentResponse, error) + FulfillIntent(context.Context, *cxpb.FulfillIntentRequest, ...gax.CallOption) (*cxpb.FulfillIntentResponse, error) +} + // SessionsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A session represents an interaction with a user. You retrieve user input +// and pass it to the DetectIntent method to determine +// user intent and respond. type SessionsClient struct { + // The internal transport-dependent client. + internalClient internalSessionsClient + + // The call options for this service. + CallOptions *SessionsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *SessionsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *SessionsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *SessionsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// DetectIntent processes a natural language query and returns structured, actionable data +// as a result. This method is not idempotent, because it may cause session +// entity types to be updated, which in turn might affect results of future +// queries. +// +// Note: Always use agent versions for production traffic. +// See Versions and +// environments (at https://cloud.google.com/dialogflow/cx/docs/concept/version). +func (c *SessionsClient) DetectIntent(ctx context.Context, req *cxpb.DetectIntentRequest, opts ...gax.CallOption) (*cxpb.DetectIntentResponse, error) { + return c.internalClient.DetectIntent(ctx, req, opts...) +} + +// StreamingDetectIntent processes a natural language query in audio format in a streaming fashion +// and returns structured, actionable data as a result. This method is only +// available via the gRPC API (not REST). +// +// Note: Always use agent versions for production traffic. +// See Versions and +// environments (at https://cloud.google.com/dialogflow/cx/docs/concept/version). +func (c *SessionsClient) StreamingDetectIntent(ctx context.Context, opts ...gax.CallOption) (cxpb.Sessions_StreamingDetectIntentClient, error) { + return c.internalClient.StreamingDetectIntent(ctx, opts...) +} + +// MatchIntent returns preliminary intent match results, doesn’t change the session +// status. +func (c *SessionsClient) MatchIntent(ctx context.Context, req *cxpb.MatchIntentRequest, opts ...gax.CallOption) (*cxpb.MatchIntentResponse, error) { + return c.internalClient.MatchIntent(ctx, req, opts...) +} + +// FulfillIntent fulfills a matched intent returned by MatchIntent. +// Must be called after MatchIntent, with input from +// MatchIntentResponse. Otherwise, the behavior is undefined. +func (c *SessionsClient) FulfillIntent(ctx context.Context, req *cxpb.FulfillIntentRequest, opts ...gax.CallOption) (*cxpb.FulfillIntentResponse, error) { + return c.internalClient.FulfillIntent(ctx, req, opts...) +} + +// sessionsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type sessionsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing SessionsClient + CallOptions **SessionsCallOptions + // The gRPC API client. sessionsClient cxpb.SessionsClient - // The call options for this service. - CallOptions *SessionsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewSessionsClient creates a new sessions client. +// NewSessionsClient creates a new sessions client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A session represents an interaction with a user. You retrieve user input // and pass it to the DetectIntent method to determine // user intent and respond. func NewSessionsClient(ctx context.Context, opts ...option.ClientOption) (*SessionsClient, error) { - clientOpts := defaultSessionsClientOptions() - + clientOpts := defaultSessionsGRPCClientOptions() if newSessionsClientHook != nil { hookOpts, err := newSessionsClientHook(ctx, clientHookParams{}) if err != nil { @@ -139,49 +222,44 @@ func NewSessionsClient(ctx context.Context, opts ...option.ClientOption) (*Sessi if err != nil { return nil, err } - c := &SessionsClient{ + client := SessionsClient{CallOptions: defaultSessionsCallOptions()} + + c := &sessionsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultSessionsCallOptions(), - - sessionsClient: cxpb.NewSessionsClient(connPool), + sessionsClient: cxpb.NewSessionsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *SessionsClient) Connection() *grpc.ClientConn { +func (c *sessionsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *SessionsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *SessionsClient) setGoogleClientInfo(keyval ...string) { +func (c *sessionsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// DetectIntent processes a natural language query and returns structured, actionable data -// as a result. This method is not idempotent, because it may cause session -// entity types to be updated, which in turn might affect results of future -// queries. -// -// Note: Always use agent versions for production traffic. -// See Versions and -// environments (at https://cloud.google.com/dialogflow/cx/docs/concept/version). -func (c *SessionsClient) DetectIntent(ctx context.Context, req *cxpb.DetectIntentRequest, opts ...gax.CallOption) (*cxpb.DetectIntentResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *sessionsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *sessionsGRPCClient) DetectIntent(ctx context.Context, req *cxpb.DetectIntentRequest, opts ...gax.CallOption) (*cxpb.DetectIntentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 220000*time.Millisecond) defer cancel() @@ -189,7 +267,7 @@ func (c *SessionsClient) DetectIntent(ctx context.Context, req *cxpb.DetectInten } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DetectIntent[0:len(c.CallOptions.DetectIntent):len(c.CallOptions.DetectIntent)], opts...) + opts = append((*c.CallOptions).DetectIntent[0:len((*c.CallOptions).DetectIntent):len((*c.CallOptions).DetectIntent)], opts...) var resp *cxpb.DetectIntentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -202,17 +280,10 @@ func (c *SessionsClient) DetectIntent(ctx context.Context, req *cxpb.DetectInten return resp, nil } -// StreamingDetectIntent processes a natural language query in audio format in a streaming fashion -// and returns structured, actionable data as a result. This method is only -// available via the gRPC API (not REST). -// -// Note: Always use agent versions for production traffic. -// See Versions and -// environments (at https://cloud.google.com/dialogflow/cx/docs/concept/version). -func (c *SessionsClient) StreamingDetectIntent(ctx context.Context, opts ...gax.CallOption) (cxpb.Sessions_StreamingDetectIntentClient, error) { +func (c *sessionsGRPCClient) StreamingDetectIntent(ctx context.Context, opts ...gax.CallOption) (cxpb.Sessions_StreamingDetectIntentClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.StreamingDetectIntent[0:len(c.CallOptions.StreamingDetectIntent):len(c.CallOptions.StreamingDetectIntent)], opts...) var resp cxpb.Sessions_StreamingDetectIntentClient + opts = append((*c.CallOptions).StreamingDetectIntent[0:len((*c.CallOptions).StreamingDetectIntent):len((*c.CallOptions).StreamingDetectIntent)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.sessionsClient.StreamingDetectIntent(ctx, settings.GRPC...) @@ -224,9 +295,7 @@ func (c *SessionsClient) StreamingDetectIntent(ctx context.Context, opts ...gax. return resp, nil } -// MatchIntent returns preliminary intent match results, doesn’t change the session -// status. -func (c *SessionsClient) MatchIntent(ctx context.Context, req *cxpb.MatchIntentRequest, opts ...gax.CallOption) (*cxpb.MatchIntentResponse, error) { +func (c *sessionsGRPCClient) MatchIntent(ctx context.Context, req *cxpb.MatchIntentRequest, opts ...gax.CallOption) (*cxpb.MatchIntentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -234,7 +303,7 @@ func (c *SessionsClient) MatchIntent(ctx context.Context, req *cxpb.MatchIntentR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.MatchIntent[0:len(c.CallOptions.MatchIntent):len(c.CallOptions.MatchIntent)], opts...) + opts = append((*c.CallOptions).MatchIntent[0:len((*c.CallOptions).MatchIntent):len((*c.CallOptions).MatchIntent)], opts...) var resp *cxpb.MatchIntentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -247,10 +316,7 @@ func (c *SessionsClient) MatchIntent(ctx context.Context, req *cxpb.MatchIntentR return resp, nil } -// FulfillIntent fulfills a matched intent returned by MatchIntent. -// Must be called after MatchIntent, with input from -// MatchIntentResponse. Otherwise, the behavior is undefined. -func (c *SessionsClient) FulfillIntent(ctx context.Context, req *cxpb.FulfillIntentRequest, opts ...gax.CallOption) (*cxpb.FulfillIntentResponse, error) { +func (c *sessionsGRPCClient) FulfillIntent(ctx context.Context, req *cxpb.FulfillIntentRequest, opts ...gax.CallOption) (*cxpb.FulfillIntentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -258,7 +324,7 @@ func (c *SessionsClient) FulfillIntent(ctx context.Context, req *cxpb.FulfillInt } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "match_intent_request.session", url.QueryEscape(req.GetMatchIntentRequest().GetSession()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.FulfillIntent[0:len(c.CallOptions.FulfillIntent):len(c.CallOptions.FulfillIntent)], opts...) + opts = append((*c.CallOptions).FulfillIntent[0:len((*c.CallOptions).FulfillIntent):len((*c.CallOptions).FulfillIntent)], opts...) var resp *cxpb.FulfillIntentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/dialogflow/cx/apiv3beta1/sessions_client_example_test.go b/dialogflow/cx/apiv3beta1/sessions_client_example_test.go index 9773ad04f02a..60cae843c437 100644 --- a/dialogflow/cx/apiv3beta1/sessions_client_example_test.go +++ b/dialogflow/cx/apiv3beta1/sessions_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewSessionsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleSessionsClient_DetectIntent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DetectIntentRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleSessionsClient_DetectIntent() { } func ExampleSessionsClient_StreamingDetectIntent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.StreamingDetectIntent(ctx) if err != nil { // TODO: Handle error. @@ -91,13 +91,12 @@ func ExampleSessionsClient_StreamingDetectIntent() { } func ExampleSessionsClient_MatchIntent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.MatchIntentRequest{ // TODO: Fill request struct fields. @@ -111,13 +110,12 @@ func ExampleSessionsClient_MatchIntent() { } func ExampleSessionsClient_FulfillIntent() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.FulfillIntentRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3beta1/test_cases_client.go b/dialogflow/cx/apiv3beta1/test_cases_client.go index 33b63dbf8218..1c9783dc2c16 100644 --- a/dialogflow/cx/apiv3beta1/test_cases_client.go +++ b/dialogflow/cx/apiv3beta1/test_cases_client.go @@ -56,7 +56,7 @@ type TestCasesCallOptions struct { GetTestCaseResult []gax.CallOption } -func defaultTestCasesClientOptions() []option.ClientOption { +func defaultTestCasesGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -205,38 +205,188 @@ func defaultTestCasesCallOptions() *TestCasesCallOptions { } } +// internalTestCasesClient is an interface that defines the methods availaible from Dialogflow API. +type internalTestCasesClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListTestCases(context.Context, *cxpb.ListTestCasesRequest, ...gax.CallOption) *TestCaseIterator + BatchDeleteTestCases(context.Context, *cxpb.BatchDeleteTestCasesRequest, ...gax.CallOption) error + GetTestCase(context.Context, *cxpb.GetTestCaseRequest, ...gax.CallOption) (*cxpb.TestCase, error) + CreateTestCase(context.Context, *cxpb.CreateTestCaseRequest, ...gax.CallOption) (*cxpb.TestCase, error) + UpdateTestCase(context.Context, *cxpb.UpdateTestCaseRequest, ...gax.CallOption) (*cxpb.TestCase, error) + RunTestCase(context.Context, *cxpb.RunTestCaseRequest, ...gax.CallOption) (*RunTestCaseOperation, error) + RunTestCaseOperation(name string) *RunTestCaseOperation + BatchRunTestCases(context.Context, *cxpb.BatchRunTestCasesRequest, ...gax.CallOption) (*BatchRunTestCasesOperation, error) + BatchRunTestCasesOperation(name string) *BatchRunTestCasesOperation + CalculateCoverage(context.Context, *cxpb.CalculateCoverageRequest, ...gax.CallOption) (*cxpb.CalculateCoverageResponse, error) + ImportTestCases(context.Context, *cxpb.ImportTestCasesRequest, ...gax.CallOption) (*ImportTestCasesOperation, error) + ImportTestCasesOperation(name string) *ImportTestCasesOperation + ExportTestCases(context.Context, *cxpb.ExportTestCasesRequest, ...gax.CallOption) (*ExportTestCasesOperation, error) + ExportTestCasesOperation(name string) *ExportTestCasesOperation + ListTestCaseResults(context.Context, *cxpb.ListTestCaseResultsRequest, ...gax.CallOption) *TestCaseResultIterator + GetTestCaseResult(context.Context, *cxpb.GetTestCaseResultRequest, ...gax.CallOption) (*cxpb.TestCaseResult, error) +} + // TestCasesClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing [Test Cases][google.cloud.dialogflow.cx.v3beta1.TestCase] and +// [Test Case Results][google.cloud.dialogflow.cx.v3beta1.TestCaseResult]. type TestCasesClient struct { + // The internal transport-dependent client. + internalClient internalTestCasesClient + + // The call options for this service. + CallOptions *TestCasesCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *TestCasesClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *TestCasesClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *TestCasesClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListTestCases fetches a list of test cases for a given agent. +func (c *TestCasesClient) ListTestCases(ctx context.Context, req *cxpb.ListTestCasesRequest, opts ...gax.CallOption) *TestCaseIterator { + return c.internalClient.ListTestCases(ctx, req, opts...) +} + +// BatchDeleteTestCases batch deletes test cases. +func (c *TestCasesClient) BatchDeleteTestCases(ctx context.Context, req *cxpb.BatchDeleteTestCasesRequest, opts ...gax.CallOption) error { + return c.internalClient.BatchDeleteTestCases(ctx, req, opts...) +} + +// GetTestCase gets a test case. +func (c *TestCasesClient) GetTestCase(ctx context.Context, req *cxpb.GetTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { + return c.internalClient.GetTestCase(ctx, req, opts...) +} + +// CreateTestCase creates a test case for the given agent. +func (c *TestCasesClient) CreateTestCase(ctx context.Context, req *cxpb.CreateTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { + return c.internalClient.CreateTestCase(ctx, req, opts...) +} + +// UpdateTestCase updates the specified test case. +func (c *TestCasesClient) UpdateTestCase(ctx context.Context, req *cxpb.UpdateTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { + return c.internalClient.UpdateTestCase(ctx, req, opts...) +} + +// RunTestCase kicks off a test case run. +func (c *TestCasesClient) RunTestCase(ctx context.Context, req *cxpb.RunTestCaseRequest, opts ...gax.CallOption) (*RunTestCaseOperation, error) { + return c.internalClient.RunTestCase(ctx, req, opts...) +} + +// RunTestCaseOperation returns a new RunTestCaseOperation from a given name. +// The name must be that of a previously created RunTestCaseOperation, possibly from a different process. +func (c *TestCasesClient) RunTestCaseOperation(name string) *RunTestCaseOperation { + return c.internalClient.RunTestCaseOperation(name) +} + +// BatchRunTestCases kicks off a batch run of test cases. +func (c *TestCasesClient) BatchRunTestCases(ctx context.Context, req *cxpb.BatchRunTestCasesRequest, opts ...gax.CallOption) (*BatchRunTestCasesOperation, error) { + return c.internalClient.BatchRunTestCases(ctx, req, opts...) +} + +// BatchRunTestCasesOperation returns a new BatchRunTestCasesOperation from a given name. +// The name must be that of a previously created BatchRunTestCasesOperation, possibly from a different process. +func (c *TestCasesClient) BatchRunTestCasesOperation(name string) *BatchRunTestCasesOperation { + return c.internalClient.BatchRunTestCasesOperation(name) +} + +// CalculateCoverage calculates the test coverage for an agent. +func (c *TestCasesClient) CalculateCoverage(ctx context.Context, req *cxpb.CalculateCoverageRequest, opts ...gax.CallOption) (*cxpb.CalculateCoverageResponse, error) { + return c.internalClient.CalculateCoverage(ctx, req, opts...) +} + +// ImportTestCases imports the test cases from a Cloud Storage bucket or a local file. It +// always creates new test cases and won’t overwite any existing ones. The +// provided ID in the imported test case is neglected. +func (c *TestCasesClient) ImportTestCases(ctx context.Context, req *cxpb.ImportTestCasesRequest, opts ...gax.CallOption) (*ImportTestCasesOperation, error) { + return c.internalClient.ImportTestCases(ctx, req, opts...) +} + +// ImportTestCasesOperation returns a new ImportTestCasesOperation from a given name. +// The name must be that of a previously created ImportTestCasesOperation, possibly from a different process. +func (c *TestCasesClient) ImportTestCasesOperation(name string) *ImportTestCasesOperation { + return c.internalClient.ImportTestCasesOperation(name) +} + +// ExportTestCases exports the test cases under the agent to a Cloud Storage bucket or a local +// file. Filter can be applied to export a subset of test cases. +func (c *TestCasesClient) ExportTestCases(ctx context.Context, req *cxpb.ExportTestCasesRequest, opts ...gax.CallOption) (*ExportTestCasesOperation, error) { + return c.internalClient.ExportTestCases(ctx, req, opts...) +} + +// ExportTestCasesOperation returns a new ExportTestCasesOperation from a given name. +// The name must be that of a previously created ExportTestCasesOperation, possibly from a different process. +func (c *TestCasesClient) ExportTestCasesOperation(name string) *ExportTestCasesOperation { + return c.internalClient.ExportTestCasesOperation(name) +} + +// ListTestCaseResults fetches a list of results for a given test case. +func (c *TestCasesClient) ListTestCaseResults(ctx context.Context, req *cxpb.ListTestCaseResultsRequest, opts ...gax.CallOption) *TestCaseResultIterator { + return c.internalClient.ListTestCaseResults(ctx, req, opts...) +} + +// GetTestCaseResult gets a test case result. +func (c *TestCasesClient) GetTestCaseResult(ctx context.Context, req *cxpb.GetTestCaseResultRequest, opts ...gax.CallOption) (*cxpb.TestCaseResult, error) { + return c.internalClient.GetTestCaseResult(ctx, req, opts...) +} + +// testCasesGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type testCasesGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing TestCasesClient + CallOptions **TestCasesCallOptions + // The gRPC API client. testCasesClient cxpb.TestCasesClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *TestCasesCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewTestCasesClient creates a new test cases client. +// NewTestCasesClient creates a new test cases client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing [Test Cases][google.cloud.dialogflow.cx.v3beta1.TestCase] and // [Test Case Results][google.cloud.dialogflow.cx.v3beta1.TestCaseResult]. func NewTestCasesClient(ctx context.Context, opts ...option.ClientOption) (*TestCasesClient, error) { - clientOpts := defaultTestCasesClientOptions() - + clientOpts := defaultTestCasesGRPCClientOptions() if newTestCasesClientHook != nil { hookOpts, err := newTestCasesClientHook(ctx, clientHookParams{}) if err != nil { @@ -254,16 +404,19 @@ func NewTestCasesClient(ctx context.Context, opts ...option.ClientOption) (*Test if err != nil { return nil, err } - c := &TestCasesClient{ + client := TestCasesClient{CallOptions: defaultTestCasesCallOptions()} + + c := &testCasesGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultTestCasesCallOptions(), - - testCasesClient: cxpb.NewTestCasesClient(connPool), + testCasesClient: cxpb.NewTestCasesClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -273,36 +426,36 @@ func NewTestCasesClient(ctx context.Context, opts ...option.ClientOption) (*Test // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *TestCasesClient) Connection() *grpc.ClientConn { +func (c *testCasesGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *TestCasesClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *TestCasesClient) setGoogleClientInfo(keyval ...string) { +func (c *testCasesGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListTestCases fetches a list of test cases for a given agent. -func (c *TestCasesClient) ListTestCases(ctx context.Context, req *cxpb.ListTestCasesRequest, opts ...gax.CallOption) *TestCaseIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *testCasesGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *testCasesGRPCClient) ListTestCases(ctx context.Context, req *cxpb.ListTestCasesRequest, opts ...gax.CallOption) *TestCaseIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTestCases[0:len(c.CallOptions.ListTestCases):len(c.CallOptions.ListTestCases)], opts...) + opts = append((*c.CallOptions).ListTestCases[0:len((*c.CallOptions).ListTestCases):len((*c.CallOptions).ListTestCases)], opts...) it := &TestCaseIterator{} req = proto.Clone(req).(*cxpb.ListTestCasesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.TestCase, string, error) { @@ -339,8 +492,7 @@ func (c *TestCasesClient) ListTestCases(ctx context.Context, req *cxpb.ListTestC return it } -// BatchDeleteTestCases batch deletes test cases. -func (c *TestCasesClient) BatchDeleteTestCases(ctx context.Context, req *cxpb.BatchDeleteTestCasesRequest, opts ...gax.CallOption) error { +func (c *testCasesGRPCClient) BatchDeleteTestCases(ctx context.Context, req *cxpb.BatchDeleteTestCasesRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -348,7 +500,7 @@ func (c *TestCasesClient) BatchDeleteTestCases(ctx context.Context, req *cxpb.Ba } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchDeleteTestCases[0:len(c.CallOptions.BatchDeleteTestCases):len(c.CallOptions.BatchDeleteTestCases)], opts...) + opts = append((*c.CallOptions).BatchDeleteTestCases[0:len((*c.CallOptions).BatchDeleteTestCases):len((*c.CallOptions).BatchDeleteTestCases)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.testCasesClient.BatchDeleteTestCases(ctx, req, settings.GRPC...) @@ -357,8 +509,7 @@ func (c *TestCasesClient) BatchDeleteTestCases(ctx context.Context, req *cxpb.Ba return err } -// GetTestCase gets a test case. -func (c *TestCasesClient) GetTestCase(ctx context.Context, req *cxpb.GetTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { +func (c *testCasesGRPCClient) GetTestCase(ctx context.Context, req *cxpb.GetTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -366,7 +517,7 @@ func (c *TestCasesClient) GetTestCase(ctx context.Context, req *cxpb.GetTestCase } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTestCase[0:len(c.CallOptions.GetTestCase):len(c.CallOptions.GetTestCase)], opts...) + opts = append((*c.CallOptions).GetTestCase[0:len((*c.CallOptions).GetTestCase):len((*c.CallOptions).GetTestCase)], opts...) var resp *cxpb.TestCase err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -379,8 +530,7 @@ func (c *TestCasesClient) GetTestCase(ctx context.Context, req *cxpb.GetTestCase return resp, nil } -// CreateTestCase creates a test case for the given agent. -func (c *TestCasesClient) CreateTestCase(ctx context.Context, req *cxpb.CreateTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { +func (c *testCasesGRPCClient) CreateTestCase(ctx context.Context, req *cxpb.CreateTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -388,7 +538,7 @@ func (c *TestCasesClient) CreateTestCase(ctx context.Context, req *cxpb.CreateTe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTestCase[0:len(c.CallOptions.CreateTestCase):len(c.CallOptions.CreateTestCase)], opts...) + opts = append((*c.CallOptions).CreateTestCase[0:len((*c.CallOptions).CreateTestCase):len((*c.CallOptions).CreateTestCase)], opts...) var resp *cxpb.TestCase err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -401,8 +551,7 @@ func (c *TestCasesClient) CreateTestCase(ctx context.Context, req *cxpb.CreateTe return resp, nil } -// UpdateTestCase updates the specified test case. -func (c *TestCasesClient) UpdateTestCase(ctx context.Context, req *cxpb.UpdateTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { +func (c *testCasesGRPCClient) UpdateTestCase(ctx context.Context, req *cxpb.UpdateTestCaseRequest, opts ...gax.CallOption) (*cxpb.TestCase, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -410,7 +559,7 @@ func (c *TestCasesClient) UpdateTestCase(ctx context.Context, req *cxpb.UpdateTe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "test_case.name", url.QueryEscape(req.GetTestCase().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTestCase[0:len(c.CallOptions.UpdateTestCase):len(c.CallOptions.UpdateTestCase)], opts...) + opts = append((*c.CallOptions).UpdateTestCase[0:len((*c.CallOptions).UpdateTestCase):len((*c.CallOptions).UpdateTestCase)], opts...) var resp *cxpb.TestCase err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -423,8 +572,7 @@ func (c *TestCasesClient) UpdateTestCase(ctx context.Context, req *cxpb.UpdateTe return resp, nil } -// RunTestCase kicks off a test case run. -func (c *TestCasesClient) RunTestCase(ctx context.Context, req *cxpb.RunTestCaseRequest, opts ...gax.CallOption) (*RunTestCaseOperation, error) { +func (c *testCasesGRPCClient) RunTestCase(ctx context.Context, req *cxpb.RunTestCaseRequest, opts ...gax.CallOption) (*RunTestCaseOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -432,7 +580,7 @@ func (c *TestCasesClient) RunTestCase(ctx context.Context, req *cxpb.RunTestCase } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RunTestCase[0:len(c.CallOptions.RunTestCase):len(c.CallOptions.RunTestCase)], opts...) + opts = append((*c.CallOptions).RunTestCase[0:len((*c.CallOptions).RunTestCase):len((*c.CallOptions).RunTestCase)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -443,12 +591,11 @@ func (c *TestCasesClient) RunTestCase(ctx context.Context, req *cxpb.RunTestCase return nil, err } return &RunTestCaseOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// BatchRunTestCases kicks off a batch run of test cases. -func (c *TestCasesClient) BatchRunTestCases(ctx context.Context, req *cxpb.BatchRunTestCasesRequest, opts ...gax.CallOption) (*BatchRunTestCasesOperation, error) { +func (c *testCasesGRPCClient) BatchRunTestCases(ctx context.Context, req *cxpb.BatchRunTestCasesRequest, opts ...gax.CallOption) (*BatchRunTestCasesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -456,7 +603,7 @@ func (c *TestCasesClient) BatchRunTestCases(ctx context.Context, req *cxpb.Batch } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchRunTestCases[0:len(c.CallOptions.BatchRunTestCases):len(c.CallOptions.BatchRunTestCases)], opts...) + opts = append((*c.CallOptions).BatchRunTestCases[0:len((*c.CallOptions).BatchRunTestCases):len((*c.CallOptions).BatchRunTestCases)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -467,12 +614,11 @@ func (c *TestCasesClient) BatchRunTestCases(ctx context.Context, req *cxpb.Batch return nil, err } return &BatchRunTestCasesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// CalculateCoverage calculates the test coverage for an agent. -func (c *TestCasesClient) CalculateCoverage(ctx context.Context, req *cxpb.CalculateCoverageRequest, opts ...gax.CallOption) (*cxpb.CalculateCoverageResponse, error) { +func (c *testCasesGRPCClient) CalculateCoverage(ctx context.Context, req *cxpb.CalculateCoverageRequest, opts ...gax.CallOption) (*cxpb.CalculateCoverageResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -480,7 +626,7 @@ func (c *TestCasesClient) CalculateCoverage(ctx context.Context, req *cxpb.Calcu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "agent", url.QueryEscape(req.GetAgent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CalculateCoverage[0:len(c.CallOptions.CalculateCoverage):len(c.CallOptions.CalculateCoverage)], opts...) + opts = append((*c.CallOptions).CalculateCoverage[0:len((*c.CallOptions).CalculateCoverage):len((*c.CallOptions).CalculateCoverage)], opts...) var resp *cxpb.CalculateCoverageResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -493,10 +639,7 @@ func (c *TestCasesClient) CalculateCoverage(ctx context.Context, req *cxpb.Calcu return resp, nil } -// ImportTestCases imports the test cases from a Cloud Storage bucket or a local file. It -// always creates new test cases and won’t overwite any existing ones. The -// provided ID in the imported test case is neglected. -func (c *TestCasesClient) ImportTestCases(ctx context.Context, req *cxpb.ImportTestCasesRequest, opts ...gax.CallOption) (*ImportTestCasesOperation, error) { +func (c *testCasesGRPCClient) ImportTestCases(ctx context.Context, req *cxpb.ImportTestCasesRequest, opts ...gax.CallOption) (*ImportTestCasesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -504,7 +647,7 @@ func (c *TestCasesClient) ImportTestCases(ctx context.Context, req *cxpb.ImportT } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportTestCases[0:len(c.CallOptions.ImportTestCases):len(c.CallOptions.ImportTestCases)], opts...) + opts = append((*c.CallOptions).ImportTestCases[0:len((*c.CallOptions).ImportTestCases):len((*c.CallOptions).ImportTestCases)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -515,13 +658,11 @@ func (c *TestCasesClient) ImportTestCases(ctx context.Context, req *cxpb.ImportT return nil, err } return &ImportTestCasesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ExportTestCases exports the test cases under the agent to a Cloud Storage bucket or a local -// file. Filter can be applied to export a subset of test cases. -func (c *TestCasesClient) ExportTestCases(ctx context.Context, req *cxpb.ExportTestCasesRequest, opts ...gax.CallOption) (*ExportTestCasesOperation, error) { +func (c *testCasesGRPCClient) ExportTestCases(ctx context.Context, req *cxpb.ExportTestCasesRequest, opts ...gax.CallOption) (*ExportTestCasesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -529,7 +670,7 @@ func (c *TestCasesClient) ExportTestCases(ctx context.Context, req *cxpb.ExportT } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportTestCases[0:len(c.CallOptions.ExportTestCases):len(c.CallOptions.ExportTestCases)], opts...) + opts = append((*c.CallOptions).ExportTestCases[0:len((*c.CallOptions).ExportTestCases):len((*c.CallOptions).ExportTestCases)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -540,15 +681,14 @@ func (c *TestCasesClient) ExportTestCases(ctx context.Context, req *cxpb.ExportT return nil, err } return &ExportTestCasesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListTestCaseResults fetches a list of results for a given test case. -func (c *TestCasesClient) ListTestCaseResults(ctx context.Context, req *cxpb.ListTestCaseResultsRequest, opts ...gax.CallOption) *TestCaseResultIterator { +func (c *testCasesGRPCClient) ListTestCaseResults(ctx context.Context, req *cxpb.ListTestCaseResultsRequest, opts ...gax.CallOption) *TestCaseResultIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTestCaseResults[0:len(c.CallOptions.ListTestCaseResults):len(c.CallOptions.ListTestCaseResults)], opts...) + opts = append((*c.CallOptions).ListTestCaseResults[0:len((*c.CallOptions).ListTestCaseResults):len((*c.CallOptions).ListTestCaseResults)], opts...) it := &TestCaseResultIterator{} req = proto.Clone(req).(*cxpb.ListTestCaseResultsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.TestCaseResult, string, error) { @@ -585,8 +725,7 @@ func (c *TestCasesClient) ListTestCaseResults(ctx context.Context, req *cxpb.Lis return it } -// GetTestCaseResult gets a test case result. -func (c *TestCasesClient) GetTestCaseResult(ctx context.Context, req *cxpb.GetTestCaseResultRequest, opts ...gax.CallOption) (*cxpb.TestCaseResult, error) { +func (c *testCasesGRPCClient) GetTestCaseResult(ctx context.Context, req *cxpb.GetTestCaseResultRequest, opts ...gax.CallOption) (*cxpb.TestCaseResult, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -594,7 +733,7 @@ func (c *TestCasesClient) GetTestCaseResult(ctx context.Context, req *cxpb.GetTe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTestCaseResult[0:len(c.CallOptions.GetTestCaseResult):len(c.CallOptions.GetTestCaseResult)], opts...) + opts = append((*c.CallOptions).GetTestCaseResult[0:len((*c.CallOptions).GetTestCaseResult):len((*c.CallOptions).GetTestCaseResult)], opts...) var resp *cxpb.TestCaseResult err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -614,9 +753,9 @@ type BatchRunTestCasesOperation struct { // BatchRunTestCasesOperation returns a new BatchRunTestCasesOperation from a given name. // The name must be that of a previously created BatchRunTestCasesOperation, possibly from a different process. -func (c *TestCasesClient) BatchRunTestCasesOperation(name string) *BatchRunTestCasesOperation { +func (c *testCasesGRPCClient) BatchRunTestCasesOperation(name string) *BatchRunTestCasesOperation { return &BatchRunTestCasesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -683,9 +822,9 @@ type ExportTestCasesOperation struct { // ExportTestCasesOperation returns a new ExportTestCasesOperation from a given name. // The name must be that of a previously created ExportTestCasesOperation, possibly from a different process. -func (c *TestCasesClient) ExportTestCasesOperation(name string) *ExportTestCasesOperation { +func (c *testCasesGRPCClient) ExportTestCasesOperation(name string) *ExportTestCasesOperation { return &ExportTestCasesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -752,9 +891,9 @@ type ImportTestCasesOperation struct { // ImportTestCasesOperation returns a new ImportTestCasesOperation from a given name. // The name must be that of a previously created ImportTestCasesOperation, possibly from a different process. -func (c *TestCasesClient) ImportTestCasesOperation(name string) *ImportTestCasesOperation { +func (c *testCasesGRPCClient) ImportTestCasesOperation(name string) *ImportTestCasesOperation { return &ImportTestCasesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -821,9 +960,9 @@ type RunTestCaseOperation struct { // RunTestCaseOperation returns a new RunTestCaseOperation from a given name. // The name must be that of a previously created RunTestCaseOperation, possibly from a different process. -func (c *TestCasesClient) RunTestCaseOperation(name string) *RunTestCaseOperation { +func (c *testCasesGRPCClient) RunTestCaseOperation(name string) *RunTestCaseOperation { return &RunTestCaseOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dialogflow/cx/apiv3beta1/test_cases_client_example_test.go b/dialogflow/cx/apiv3beta1/test_cases_client_example_test.go index 5e65f90d99a1..ee900d47707d 100644 --- a/dialogflow/cx/apiv3beta1/test_cases_client_example_test.go +++ b/dialogflow/cx/apiv3beta1/test_cases_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewTestCasesClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleTestCasesClient_ListTestCases() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListTestCasesRequest{ // TODO: Fill request struct fields. @@ -67,6 +67,7 @@ func ExampleTestCasesClient_BatchDeleteTestCases() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.BatchDeleteTestCasesRequest{ // TODO: Fill request struct fields. @@ -78,13 +79,12 @@ func ExampleTestCasesClient_BatchDeleteTestCases() { } func ExampleTestCasesClient_GetTestCase() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetTestCaseRequest{ // TODO: Fill request struct fields. @@ -98,13 +98,12 @@ func ExampleTestCasesClient_GetTestCase() { } func ExampleTestCasesClient_CreateTestCase() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateTestCaseRequest{ // TODO: Fill request struct fields. @@ -118,13 +117,12 @@ func ExampleTestCasesClient_CreateTestCase() { } func ExampleTestCasesClient_UpdateTestCase() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateTestCaseRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleTestCasesClient_UpdateTestCase() { } func ExampleTestCasesClient_RunTestCase() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.RunTestCaseRequest{ // TODO: Fill request struct fields. @@ -163,13 +160,12 @@ func ExampleTestCasesClient_RunTestCase() { } func ExampleTestCasesClient_BatchRunTestCases() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.BatchRunTestCasesRequest{ // TODO: Fill request struct fields. @@ -188,13 +184,12 @@ func ExampleTestCasesClient_BatchRunTestCases() { } func ExampleTestCasesClient_CalculateCoverage() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CalculateCoverageRequest{ // TODO: Fill request struct fields. @@ -208,13 +203,12 @@ func ExampleTestCasesClient_CalculateCoverage() { } func ExampleTestCasesClient_ImportTestCases() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ImportTestCasesRequest{ // TODO: Fill request struct fields. @@ -233,13 +227,12 @@ func ExampleTestCasesClient_ImportTestCases() { } func ExampleTestCasesClient_ExportTestCases() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ExportTestCasesRequest{ // TODO: Fill request struct fields. @@ -258,14 +251,12 @@ func ExampleTestCasesClient_ExportTestCases() { } func ExampleTestCasesClient_ListTestCaseResults() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListTestCaseResultsRequest{ // TODO: Fill request struct fields. @@ -285,13 +276,12 @@ func ExampleTestCasesClient_ListTestCaseResults() { } func ExampleTestCasesClient_GetTestCaseResult() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetTestCaseResultRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3beta1/transition_route_groups_client.go b/dialogflow/cx/apiv3beta1/transition_route_groups_client.go index 0a012006d28f..710e287e83c7 100644 --- a/dialogflow/cx/apiv3beta1/transition_route_groups_client.go +++ b/dialogflow/cx/apiv3beta1/transition_route_groups_client.go @@ -46,7 +46,7 @@ type TransitionRouteGroupsCallOptions struct { DeleteTransitionRouteGroup []gax.CallOption } -func defaultTransitionRouteGroupsClientOptions() []option.ClientOption { +func defaultTransitionRouteGroupsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,103 @@ func defaultTransitionRouteGroupsCallOptions() *TransitionRouteGroupsCallOptions } } +// internalTransitionRouteGroupsClient is an interface that defines the methods availaible from Dialogflow API. +type internalTransitionRouteGroupsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListTransitionRouteGroups(context.Context, *cxpb.ListTransitionRouteGroupsRequest, ...gax.CallOption) *TransitionRouteGroupIterator + GetTransitionRouteGroup(context.Context, *cxpb.GetTransitionRouteGroupRequest, ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) + CreateTransitionRouteGroup(context.Context, *cxpb.CreateTransitionRouteGroupRequest, ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) + UpdateTransitionRouteGroup(context.Context, *cxpb.UpdateTransitionRouteGroupRequest, ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) + DeleteTransitionRouteGroup(context.Context, *cxpb.DeleteTransitionRouteGroupRequest, ...gax.CallOption) error +} + // TransitionRouteGroupsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing TransitionRouteGroups. type TransitionRouteGroupsClient struct { + // The internal transport-dependent client. + internalClient internalTransitionRouteGroupsClient + + // The call options for this service. + CallOptions *TransitionRouteGroupsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *TransitionRouteGroupsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *TransitionRouteGroupsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *TransitionRouteGroupsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListTransitionRouteGroups returns the list of all transition route groups in the specified flow. +func (c *TransitionRouteGroupsClient) ListTransitionRouteGroups(ctx context.Context, req *cxpb.ListTransitionRouteGroupsRequest, opts ...gax.CallOption) *TransitionRouteGroupIterator { + return c.internalClient.ListTransitionRouteGroups(ctx, req, opts...) +} + +// GetTransitionRouteGroup retrieves the specified TransitionRouteGroup. +func (c *TransitionRouteGroupsClient) GetTransitionRouteGroup(ctx context.Context, req *cxpb.GetTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { + return c.internalClient.GetTransitionRouteGroup(ctx, req, opts...) +} + +// CreateTransitionRouteGroup creates an TransitionRouteGroup in the specified flow. +func (c *TransitionRouteGroupsClient) CreateTransitionRouteGroup(ctx context.Context, req *cxpb.CreateTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { + return c.internalClient.CreateTransitionRouteGroup(ctx, req, opts...) +} + +// UpdateTransitionRouteGroup updates the specified TransitionRouteGroup. +func (c *TransitionRouteGroupsClient) UpdateTransitionRouteGroup(ctx context.Context, req *cxpb.UpdateTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { + return c.internalClient.UpdateTransitionRouteGroup(ctx, req, opts...) +} + +// DeleteTransitionRouteGroup deletes the specified TransitionRouteGroup. +func (c *TransitionRouteGroupsClient) DeleteTransitionRouteGroup(ctx context.Context, req *cxpb.DeleteTransitionRouteGroupRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTransitionRouteGroup(ctx, req, opts...) +} + +// transitionRouteGroupsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type transitionRouteGroupsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing TransitionRouteGroupsClient + CallOptions **TransitionRouteGroupsCallOptions + // The gRPC API client. transitionRouteGroupsClient cxpb.TransitionRouteGroupsClient - // The call options for this service. - CallOptions *TransitionRouteGroupsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewTransitionRouteGroupsClient creates a new transition route groups client. +// NewTransitionRouteGroupsClient creates a new transition route groups client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing TransitionRouteGroups. func NewTransitionRouteGroupsClient(ctx context.Context, opts ...option.ClientOption) (*TransitionRouteGroupsClient, error) { - clientOpts := defaultTransitionRouteGroupsClientOptions() - + clientOpts := defaultTransitionRouteGroupsGRPCClientOptions() if newTransitionRouteGroupsClientHook != nil { hookOpts, err := newTransitionRouteGroupsClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,45 +232,47 @@ func NewTransitionRouteGroupsClient(ctx context.Context, opts ...option.ClientOp if err != nil { return nil, err } - c := &TransitionRouteGroupsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultTransitionRouteGroupsCallOptions(), + client := TransitionRouteGroupsClient{CallOptions: defaultTransitionRouteGroupsCallOptions()} + c := &transitionRouteGroupsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, transitionRouteGroupsClient: cxpb.NewTransitionRouteGroupsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *TransitionRouteGroupsClient) Connection() *grpc.ClientConn { +func (c *transitionRouteGroupsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *TransitionRouteGroupsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *TransitionRouteGroupsClient) setGoogleClientInfo(keyval ...string) { +func (c *transitionRouteGroupsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListTransitionRouteGroups returns the list of all transition route groups in the specified flow. -func (c *TransitionRouteGroupsClient) ListTransitionRouteGroups(ctx context.Context, req *cxpb.ListTransitionRouteGroupsRequest, opts ...gax.CallOption) *TransitionRouteGroupIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *transitionRouteGroupsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *transitionRouteGroupsGRPCClient) ListTransitionRouteGroups(ctx context.Context, req *cxpb.ListTransitionRouteGroupsRequest, opts ...gax.CallOption) *TransitionRouteGroupIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTransitionRouteGroups[0:len(c.CallOptions.ListTransitionRouteGroups):len(c.CallOptions.ListTransitionRouteGroups)], opts...) + opts = append((*c.CallOptions).ListTransitionRouteGroups[0:len((*c.CallOptions).ListTransitionRouteGroups):len((*c.CallOptions).ListTransitionRouteGroups)], opts...) it := &TransitionRouteGroupIterator{} req = proto.Clone(req).(*cxpb.ListTransitionRouteGroupsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.TransitionRouteGroup, string, error) { @@ -236,8 +309,7 @@ func (c *TransitionRouteGroupsClient) ListTransitionRouteGroups(ctx context.Cont return it } -// GetTransitionRouteGroup retrieves the specified TransitionRouteGroup. -func (c *TransitionRouteGroupsClient) GetTransitionRouteGroup(ctx context.Context, req *cxpb.GetTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { +func (c *transitionRouteGroupsGRPCClient) GetTransitionRouteGroup(ctx context.Context, req *cxpb.GetTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -245,7 +317,7 @@ func (c *TransitionRouteGroupsClient) GetTransitionRouteGroup(ctx context.Contex } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTransitionRouteGroup[0:len(c.CallOptions.GetTransitionRouteGroup):len(c.CallOptions.GetTransitionRouteGroup)], opts...) + opts = append((*c.CallOptions).GetTransitionRouteGroup[0:len((*c.CallOptions).GetTransitionRouteGroup):len((*c.CallOptions).GetTransitionRouteGroup)], opts...) var resp *cxpb.TransitionRouteGroup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -258,8 +330,7 @@ func (c *TransitionRouteGroupsClient) GetTransitionRouteGroup(ctx context.Contex return resp, nil } -// CreateTransitionRouteGroup creates an TransitionRouteGroup in the specified flow. -func (c *TransitionRouteGroupsClient) CreateTransitionRouteGroup(ctx context.Context, req *cxpb.CreateTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { +func (c *transitionRouteGroupsGRPCClient) CreateTransitionRouteGroup(ctx context.Context, req *cxpb.CreateTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -267,7 +338,7 @@ func (c *TransitionRouteGroupsClient) CreateTransitionRouteGroup(ctx context.Con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTransitionRouteGroup[0:len(c.CallOptions.CreateTransitionRouteGroup):len(c.CallOptions.CreateTransitionRouteGroup)], opts...) + opts = append((*c.CallOptions).CreateTransitionRouteGroup[0:len((*c.CallOptions).CreateTransitionRouteGroup):len((*c.CallOptions).CreateTransitionRouteGroup)], opts...) var resp *cxpb.TransitionRouteGroup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -280,8 +351,7 @@ func (c *TransitionRouteGroupsClient) CreateTransitionRouteGroup(ctx context.Con return resp, nil } -// UpdateTransitionRouteGroup updates the specified TransitionRouteGroup. -func (c *TransitionRouteGroupsClient) UpdateTransitionRouteGroup(ctx context.Context, req *cxpb.UpdateTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { +func (c *transitionRouteGroupsGRPCClient) UpdateTransitionRouteGroup(ctx context.Context, req *cxpb.UpdateTransitionRouteGroupRequest, opts ...gax.CallOption) (*cxpb.TransitionRouteGroup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -289,7 +359,7 @@ func (c *TransitionRouteGroupsClient) UpdateTransitionRouteGroup(ctx context.Con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "transition_route_group.name", url.QueryEscape(req.GetTransitionRouteGroup().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTransitionRouteGroup[0:len(c.CallOptions.UpdateTransitionRouteGroup):len(c.CallOptions.UpdateTransitionRouteGroup)], opts...) + opts = append((*c.CallOptions).UpdateTransitionRouteGroup[0:len((*c.CallOptions).UpdateTransitionRouteGroup):len((*c.CallOptions).UpdateTransitionRouteGroup)], opts...) var resp *cxpb.TransitionRouteGroup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -302,8 +372,7 @@ func (c *TransitionRouteGroupsClient) UpdateTransitionRouteGroup(ctx context.Con return resp, nil } -// DeleteTransitionRouteGroup deletes the specified TransitionRouteGroup. -func (c *TransitionRouteGroupsClient) DeleteTransitionRouteGroup(ctx context.Context, req *cxpb.DeleteTransitionRouteGroupRequest, opts ...gax.CallOption) error { +func (c *transitionRouteGroupsGRPCClient) DeleteTransitionRouteGroup(ctx context.Context, req *cxpb.DeleteTransitionRouteGroupRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -311,7 +380,7 @@ func (c *TransitionRouteGroupsClient) DeleteTransitionRouteGroup(ctx context.Con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTransitionRouteGroup[0:len(c.CallOptions.DeleteTransitionRouteGroup):len(c.CallOptions.DeleteTransitionRouteGroup)], opts...) + opts = append((*c.CallOptions).DeleteTransitionRouteGroup[0:len((*c.CallOptions).DeleteTransitionRouteGroup):len((*c.CallOptions).DeleteTransitionRouteGroup)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.transitionRouteGroupsClient.DeleteTransitionRouteGroup(ctx, req, settings.GRPC...) diff --git a/dialogflow/cx/apiv3beta1/transition_route_groups_client_example_test.go b/dialogflow/cx/apiv3beta1/transition_route_groups_client_example_test.go index 5e3b3996cd23..f0ea4667f164 100644 --- a/dialogflow/cx/apiv3beta1/transition_route_groups_client_example_test.go +++ b/dialogflow/cx/apiv3beta1/transition_route_groups_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewTransitionRouteGroupsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleTransitionRouteGroupsClient_ListTransitionRouteGroups() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewTransitionRouteGroupsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListTransitionRouteGroupsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleTransitionRouteGroupsClient_ListTransitionRouteGroups() { } func ExampleTransitionRouteGroupsClient_GetTransitionRouteGroup() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTransitionRouteGroupsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetTransitionRouteGroupRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleTransitionRouteGroupsClient_GetTransitionRouteGroup() { } func ExampleTransitionRouteGroupsClient_CreateTransitionRouteGroup() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTransitionRouteGroupsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateTransitionRouteGroupRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleTransitionRouteGroupsClient_CreateTransitionRouteGroup() { } func ExampleTransitionRouteGroupsClient_UpdateTransitionRouteGroup() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTransitionRouteGroupsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateTransitionRouteGroupRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleTransitionRouteGroupsClient_DeleteTransitionRouteGroup() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteTransitionRouteGroupRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3beta1/versions_client.go b/dialogflow/cx/apiv3beta1/versions_client.go index 7b8cc52c975c..7bc51119e19d 100644 --- a/dialogflow/cx/apiv3beta1/versions_client.go +++ b/dialogflow/cx/apiv3beta1/versions_client.go @@ -51,7 +51,7 @@ type VersionsCallOptions struct { LoadVersion []gax.CallOption } -func defaultVersionsClientOptions() []option.ClientOption { +func defaultVersionsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -134,37 +134,133 @@ func defaultVersionsCallOptions() *VersionsCallOptions { } } +// internalVersionsClient is an interface that defines the methods availaible from Dialogflow API. +type internalVersionsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListVersions(context.Context, *cxpb.ListVersionsRequest, ...gax.CallOption) *VersionIterator + GetVersion(context.Context, *cxpb.GetVersionRequest, ...gax.CallOption) (*cxpb.Version, error) + CreateVersion(context.Context, *cxpb.CreateVersionRequest, ...gax.CallOption) (*CreateVersionOperation, error) + CreateVersionOperation(name string) *CreateVersionOperation + UpdateVersion(context.Context, *cxpb.UpdateVersionRequest, ...gax.CallOption) (*cxpb.Version, error) + DeleteVersion(context.Context, *cxpb.DeleteVersionRequest, ...gax.CallOption) error + LoadVersion(context.Context, *cxpb.LoadVersionRequest, ...gax.CallOption) (*LoadVersionOperation, error) + LoadVersionOperation(name string) *LoadVersionOperation +} + // VersionsClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Versions. type VersionsClient struct { + // The internal transport-dependent client. + internalClient internalVersionsClient + + // The call options for this service. + CallOptions *VersionsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *VersionsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *VersionsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *VersionsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListVersions returns the list of all versions in the specified Flow. +func (c *VersionsClient) ListVersions(ctx context.Context, req *cxpb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { + return c.internalClient.ListVersions(ctx, req, opts...) +} + +// GetVersion retrieves the specified Version. +func (c *VersionsClient) GetVersion(ctx context.Context, req *cxpb.GetVersionRequest, opts ...gax.CallOption) (*cxpb.Version, error) { + return c.internalClient.GetVersion(ctx, req, opts...) +} + +// CreateVersion creates a Version in the specified Flow. +func (c *VersionsClient) CreateVersion(ctx context.Context, req *cxpb.CreateVersionRequest, opts ...gax.CallOption) (*CreateVersionOperation, error) { + return c.internalClient.CreateVersion(ctx, req, opts...) +} + +// CreateVersionOperation returns a new CreateVersionOperation from a given name. +// The name must be that of a previously created CreateVersionOperation, possibly from a different process. +func (c *VersionsClient) CreateVersionOperation(name string) *CreateVersionOperation { + return c.internalClient.CreateVersionOperation(name) +} + +// UpdateVersion updates the specified Version. +func (c *VersionsClient) UpdateVersion(ctx context.Context, req *cxpb.UpdateVersionRequest, opts ...gax.CallOption) (*cxpb.Version, error) { + return c.internalClient.UpdateVersion(ctx, req, opts...) +} + +// DeleteVersion deletes the specified Version. +func (c *VersionsClient) DeleteVersion(ctx context.Context, req *cxpb.DeleteVersionRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteVersion(ctx, req, opts...) +} + +// LoadVersion loads resources in the specified version to the draft flow. +func (c *VersionsClient) LoadVersion(ctx context.Context, req *cxpb.LoadVersionRequest, opts ...gax.CallOption) (*LoadVersionOperation, error) { + return c.internalClient.LoadVersion(ctx, req, opts...) +} + +// LoadVersionOperation returns a new LoadVersionOperation from a given name. +// The name must be that of a previously created LoadVersionOperation, possibly from a different process. +func (c *VersionsClient) LoadVersionOperation(name string) *LoadVersionOperation { + return c.internalClient.LoadVersionOperation(name) +} + +// versionsGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type versionsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing VersionsClient + CallOptions **VersionsCallOptions + // The gRPC API client. versionsClient cxpb.VersionsClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *VersionsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewVersionsClient creates a new versions client. +// NewVersionsClient creates a new versions client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Versions. func NewVersionsClient(ctx context.Context, opts ...option.ClientOption) (*VersionsClient, error) { - clientOpts := defaultVersionsClientOptions() - + clientOpts := defaultVersionsGRPCClientOptions() if newVersionsClientHook != nil { hookOpts, err := newVersionsClientHook(ctx, clientHookParams{}) if err != nil { @@ -182,16 +278,19 @@ func NewVersionsClient(ctx context.Context, opts ...option.ClientOption) (*Versi if err != nil { return nil, err } - c := &VersionsClient{ + client := VersionsClient{CallOptions: defaultVersionsCallOptions()} + + c := &versionsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultVersionsCallOptions(), - - versionsClient: cxpb.NewVersionsClient(connPool), + versionsClient: cxpb.NewVersionsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -201,36 +300,36 @@ func NewVersionsClient(ctx context.Context, opts ...option.ClientOption) (*Versi // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *VersionsClient) Connection() *grpc.ClientConn { +func (c *versionsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *VersionsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *VersionsClient) setGoogleClientInfo(keyval ...string) { +func (c *versionsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListVersions returns the list of all versions in the specified Flow. -func (c *VersionsClient) ListVersions(ctx context.Context, req *cxpb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *versionsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *versionsGRPCClient) ListVersions(ctx context.Context, req *cxpb.ListVersionsRequest, opts ...gax.CallOption) *VersionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListVersions[0:len(c.CallOptions.ListVersions):len(c.CallOptions.ListVersions)], opts...) + opts = append((*c.CallOptions).ListVersions[0:len((*c.CallOptions).ListVersions):len((*c.CallOptions).ListVersions)], opts...) it := &VersionIterator{} req = proto.Clone(req).(*cxpb.ListVersionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Version, string, error) { @@ -267,8 +366,7 @@ func (c *VersionsClient) ListVersions(ctx context.Context, req *cxpb.ListVersion return it } -// GetVersion retrieves the specified Version. -func (c *VersionsClient) GetVersion(ctx context.Context, req *cxpb.GetVersionRequest, opts ...gax.CallOption) (*cxpb.Version, error) { +func (c *versionsGRPCClient) GetVersion(ctx context.Context, req *cxpb.GetVersionRequest, opts ...gax.CallOption) (*cxpb.Version, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -276,7 +374,7 @@ func (c *VersionsClient) GetVersion(ctx context.Context, req *cxpb.GetVersionReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetVersion[0:len(c.CallOptions.GetVersion):len(c.CallOptions.GetVersion)], opts...) + opts = append((*c.CallOptions).GetVersion[0:len((*c.CallOptions).GetVersion):len((*c.CallOptions).GetVersion)], opts...) var resp *cxpb.Version err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -289,8 +387,7 @@ func (c *VersionsClient) GetVersion(ctx context.Context, req *cxpb.GetVersionReq return resp, nil } -// CreateVersion creates a Version in the specified Flow. -func (c *VersionsClient) CreateVersion(ctx context.Context, req *cxpb.CreateVersionRequest, opts ...gax.CallOption) (*CreateVersionOperation, error) { +func (c *versionsGRPCClient) CreateVersion(ctx context.Context, req *cxpb.CreateVersionRequest, opts ...gax.CallOption) (*CreateVersionOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -298,7 +395,7 @@ func (c *VersionsClient) CreateVersion(ctx context.Context, req *cxpb.CreateVers } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateVersion[0:len(c.CallOptions.CreateVersion):len(c.CallOptions.CreateVersion)], opts...) + opts = append((*c.CallOptions).CreateVersion[0:len((*c.CallOptions).CreateVersion):len((*c.CallOptions).CreateVersion)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -309,12 +406,11 @@ func (c *VersionsClient) CreateVersion(ctx context.Context, req *cxpb.CreateVers return nil, err } return &CreateVersionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateVersion updates the specified Version. -func (c *VersionsClient) UpdateVersion(ctx context.Context, req *cxpb.UpdateVersionRequest, opts ...gax.CallOption) (*cxpb.Version, error) { +func (c *versionsGRPCClient) UpdateVersion(ctx context.Context, req *cxpb.UpdateVersionRequest, opts ...gax.CallOption) (*cxpb.Version, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -322,7 +418,7 @@ func (c *VersionsClient) UpdateVersion(ctx context.Context, req *cxpb.UpdateVers } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "version.name", url.QueryEscape(req.GetVersion().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateVersion[0:len(c.CallOptions.UpdateVersion):len(c.CallOptions.UpdateVersion)], opts...) + opts = append((*c.CallOptions).UpdateVersion[0:len((*c.CallOptions).UpdateVersion):len((*c.CallOptions).UpdateVersion)], opts...) var resp *cxpb.Version err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -335,8 +431,7 @@ func (c *VersionsClient) UpdateVersion(ctx context.Context, req *cxpb.UpdateVers return resp, nil } -// DeleteVersion deletes the specified Version. -func (c *VersionsClient) DeleteVersion(ctx context.Context, req *cxpb.DeleteVersionRequest, opts ...gax.CallOption) error { +func (c *versionsGRPCClient) DeleteVersion(ctx context.Context, req *cxpb.DeleteVersionRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -344,7 +439,7 @@ func (c *VersionsClient) DeleteVersion(ctx context.Context, req *cxpb.DeleteVers } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteVersion[0:len(c.CallOptions.DeleteVersion):len(c.CallOptions.DeleteVersion)], opts...) + opts = append((*c.CallOptions).DeleteVersion[0:len((*c.CallOptions).DeleteVersion):len((*c.CallOptions).DeleteVersion)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.versionsClient.DeleteVersion(ctx, req, settings.GRPC...) @@ -353,8 +448,7 @@ func (c *VersionsClient) DeleteVersion(ctx context.Context, req *cxpb.DeleteVers return err } -// LoadVersion loads resources in the specified version to the draft flow. -func (c *VersionsClient) LoadVersion(ctx context.Context, req *cxpb.LoadVersionRequest, opts ...gax.CallOption) (*LoadVersionOperation, error) { +func (c *versionsGRPCClient) LoadVersion(ctx context.Context, req *cxpb.LoadVersionRequest, opts ...gax.CallOption) (*LoadVersionOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -362,7 +456,7 @@ func (c *VersionsClient) LoadVersion(ctx context.Context, req *cxpb.LoadVersionR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.LoadVersion[0:len(c.CallOptions.LoadVersion):len(c.CallOptions.LoadVersion)], opts...) + opts = append((*c.CallOptions).LoadVersion[0:len((*c.CallOptions).LoadVersion):len((*c.CallOptions).LoadVersion)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -373,7 +467,7 @@ func (c *VersionsClient) LoadVersion(ctx context.Context, req *cxpb.LoadVersionR return nil, err } return &LoadVersionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -384,9 +478,9 @@ type CreateVersionOperation struct { // CreateVersionOperation returns a new CreateVersionOperation from a given name. // The name must be that of a previously created CreateVersionOperation, possibly from a different process. -func (c *VersionsClient) CreateVersionOperation(name string) *CreateVersionOperation { +func (c *versionsGRPCClient) CreateVersionOperation(name string) *CreateVersionOperation { return &CreateVersionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -453,9 +547,9 @@ type LoadVersionOperation struct { // LoadVersionOperation returns a new LoadVersionOperation from a given name. // The name must be that of a previously created LoadVersionOperation, possibly from a different process. -func (c *VersionsClient) LoadVersionOperation(name string) *LoadVersionOperation { +func (c *versionsGRPCClient) LoadVersionOperation(name string) *LoadVersionOperation { return &LoadVersionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/dialogflow/cx/apiv3beta1/versions_client_example_test.go b/dialogflow/cx/apiv3beta1/versions_client_example_test.go index 4e993797fad4..2145e38def5f 100644 --- a/dialogflow/cx/apiv3beta1/versions_client_example_test.go +++ b/dialogflow/cx/apiv3beta1/versions_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewVersionsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleVersionsClient_ListVersions() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListVersionsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleVersionsClient_ListVersions() { } func ExampleVersionsClient_GetVersion() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetVersionRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleVersionsClient_GetVersion() { } func ExampleVersionsClient_CreateVersion() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateVersionRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleVersionsClient_CreateVersion() { } func ExampleVersionsClient_UpdateVersion() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateVersionRequest{ // TODO: Fill request struct fields. @@ -132,6 +129,7 @@ func ExampleVersionsClient_DeleteVersion() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteVersionRequest{ // TODO: Fill request struct fields. @@ -143,13 +141,12 @@ func ExampleVersionsClient_DeleteVersion() { } func ExampleVersionsClient_LoadVersion() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.LoadVersionRequest{ // TODO: Fill request struct fields. diff --git a/dialogflow/cx/apiv3beta1/webhooks_client.go b/dialogflow/cx/apiv3beta1/webhooks_client.go index ffaf920f71bd..8450145adb61 100644 --- a/dialogflow/cx/apiv3beta1/webhooks_client.go +++ b/dialogflow/cx/apiv3beta1/webhooks_client.go @@ -46,7 +46,7 @@ type WebhooksCallOptions struct { DeleteWebhook []gax.CallOption } -func defaultWebhooksClientOptions() []option.ClientOption { +func defaultWebhooksGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dialogflow.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dialogflow.mtls.googleapis.com:443"), @@ -118,32 +118,103 @@ func defaultWebhooksCallOptions() *WebhooksCallOptions { } } +// internalWebhooksClient is an interface that defines the methods availaible from Dialogflow API. +type internalWebhooksClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListWebhooks(context.Context, *cxpb.ListWebhooksRequest, ...gax.CallOption) *WebhookIterator + GetWebhook(context.Context, *cxpb.GetWebhookRequest, ...gax.CallOption) (*cxpb.Webhook, error) + CreateWebhook(context.Context, *cxpb.CreateWebhookRequest, ...gax.CallOption) (*cxpb.Webhook, error) + UpdateWebhook(context.Context, *cxpb.UpdateWebhookRequest, ...gax.CallOption) (*cxpb.Webhook, error) + DeleteWebhook(context.Context, *cxpb.DeleteWebhookRequest, ...gax.CallOption) error +} + // WebhooksClient is a client for interacting with Dialogflow API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing Webhooks. type WebhooksClient struct { + // The internal transport-dependent client. + internalClient internalWebhooksClient + + // The call options for this service. + CallOptions *WebhooksCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *WebhooksClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *WebhooksClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *WebhooksClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListWebhooks returns the list of all webhooks in the specified agent. +func (c *WebhooksClient) ListWebhooks(ctx context.Context, req *cxpb.ListWebhooksRequest, opts ...gax.CallOption) *WebhookIterator { + return c.internalClient.ListWebhooks(ctx, req, opts...) +} + +// GetWebhook retrieves the specified webhook. +func (c *WebhooksClient) GetWebhook(ctx context.Context, req *cxpb.GetWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { + return c.internalClient.GetWebhook(ctx, req, opts...) +} + +// CreateWebhook creates a webhook in the specified agent. +func (c *WebhooksClient) CreateWebhook(ctx context.Context, req *cxpb.CreateWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { + return c.internalClient.CreateWebhook(ctx, req, opts...) +} + +// UpdateWebhook updates the specified webhook. +func (c *WebhooksClient) UpdateWebhook(ctx context.Context, req *cxpb.UpdateWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { + return c.internalClient.UpdateWebhook(ctx, req, opts...) +} + +// DeleteWebhook deletes the specified webhook. +func (c *WebhooksClient) DeleteWebhook(ctx context.Context, req *cxpb.DeleteWebhookRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteWebhook(ctx, req, opts...) +} + +// webhooksGRPCClient is a client for interacting with Dialogflow API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type webhooksGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing WebhooksClient + CallOptions **WebhooksCallOptions + // The gRPC API client. webhooksClient cxpb.WebhooksClient - // The call options for this service. - CallOptions *WebhooksCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewWebhooksClient creates a new webhooks client. +// NewWebhooksClient creates a new webhooks client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing Webhooks. func NewWebhooksClient(ctx context.Context, opts ...option.ClientOption) (*WebhooksClient, error) { - clientOpts := defaultWebhooksClientOptions() - + clientOpts := defaultWebhooksGRPCClientOptions() if newWebhooksClientHook != nil { hookOpts, err := newWebhooksClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,45 +232,47 @@ func NewWebhooksClient(ctx context.Context, opts ...option.ClientOption) (*Webho if err != nil { return nil, err } - c := &WebhooksClient{ + client := WebhooksClient{CallOptions: defaultWebhooksCallOptions()} + + c := &webhooksGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultWebhooksCallOptions(), - - webhooksClient: cxpb.NewWebhooksClient(connPool), + webhooksClient: cxpb.NewWebhooksClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *WebhooksClient) Connection() *grpc.ClientConn { +func (c *webhooksGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *WebhooksClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *WebhooksClient) setGoogleClientInfo(keyval ...string) { +func (c *webhooksGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListWebhooks returns the list of all webhooks in the specified agent. -func (c *WebhooksClient) ListWebhooks(ctx context.Context, req *cxpb.ListWebhooksRequest, opts ...gax.CallOption) *WebhookIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *webhooksGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *webhooksGRPCClient) ListWebhooks(ctx context.Context, req *cxpb.ListWebhooksRequest, opts ...gax.CallOption) *WebhookIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListWebhooks[0:len(c.CallOptions.ListWebhooks):len(c.CallOptions.ListWebhooks)], opts...) + opts = append((*c.CallOptions).ListWebhooks[0:len((*c.CallOptions).ListWebhooks):len((*c.CallOptions).ListWebhooks)], opts...) it := &WebhookIterator{} req = proto.Clone(req).(*cxpb.ListWebhooksRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cxpb.Webhook, string, error) { @@ -236,8 +309,7 @@ func (c *WebhooksClient) ListWebhooks(ctx context.Context, req *cxpb.ListWebhook return it } -// GetWebhook retrieves the specified webhook. -func (c *WebhooksClient) GetWebhook(ctx context.Context, req *cxpb.GetWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { +func (c *webhooksGRPCClient) GetWebhook(ctx context.Context, req *cxpb.GetWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -245,7 +317,7 @@ func (c *WebhooksClient) GetWebhook(ctx context.Context, req *cxpb.GetWebhookReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetWebhook[0:len(c.CallOptions.GetWebhook):len(c.CallOptions.GetWebhook)], opts...) + opts = append((*c.CallOptions).GetWebhook[0:len((*c.CallOptions).GetWebhook):len((*c.CallOptions).GetWebhook)], opts...) var resp *cxpb.Webhook err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -258,8 +330,7 @@ func (c *WebhooksClient) GetWebhook(ctx context.Context, req *cxpb.GetWebhookReq return resp, nil } -// CreateWebhook creates a webhook in the specified agent. -func (c *WebhooksClient) CreateWebhook(ctx context.Context, req *cxpb.CreateWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { +func (c *webhooksGRPCClient) CreateWebhook(ctx context.Context, req *cxpb.CreateWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -267,7 +338,7 @@ func (c *WebhooksClient) CreateWebhook(ctx context.Context, req *cxpb.CreateWebh } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateWebhook[0:len(c.CallOptions.CreateWebhook):len(c.CallOptions.CreateWebhook)], opts...) + opts = append((*c.CallOptions).CreateWebhook[0:len((*c.CallOptions).CreateWebhook):len((*c.CallOptions).CreateWebhook)], opts...) var resp *cxpb.Webhook err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -280,8 +351,7 @@ func (c *WebhooksClient) CreateWebhook(ctx context.Context, req *cxpb.CreateWebh return resp, nil } -// UpdateWebhook updates the specified webhook. -func (c *WebhooksClient) UpdateWebhook(ctx context.Context, req *cxpb.UpdateWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { +func (c *webhooksGRPCClient) UpdateWebhook(ctx context.Context, req *cxpb.UpdateWebhookRequest, opts ...gax.CallOption) (*cxpb.Webhook, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -289,7 +359,7 @@ func (c *WebhooksClient) UpdateWebhook(ctx context.Context, req *cxpb.UpdateWebh } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "webhook.name", url.QueryEscape(req.GetWebhook().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateWebhook[0:len(c.CallOptions.UpdateWebhook):len(c.CallOptions.UpdateWebhook)], opts...) + opts = append((*c.CallOptions).UpdateWebhook[0:len((*c.CallOptions).UpdateWebhook):len((*c.CallOptions).UpdateWebhook)], opts...) var resp *cxpb.Webhook err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -302,8 +372,7 @@ func (c *WebhooksClient) UpdateWebhook(ctx context.Context, req *cxpb.UpdateWebh return resp, nil } -// DeleteWebhook deletes the specified webhook. -func (c *WebhooksClient) DeleteWebhook(ctx context.Context, req *cxpb.DeleteWebhookRequest, opts ...gax.CallOption) error { +func (c *webhooksGRPCClient) DeleteWebhook(ctx context.Context, req *cxpb.DeleteWebhookRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -311,7 +380,7 @@ func (c *WebhooksClient) DeleteWebhook(ctx context.Context, req *cxpb.DeleteWebh } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteWebhook[0:len(c.CallOptions.DeleteWebhook):len(c.CallOptions.DeleteWebhook)], opts...) + opts = append((*c.CallOptions).DeleteWebhook[0:len((*c.CallOptions).DeleteWebhook):len((*c.CallOptions).DeleteWebhook)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.webhooksClient.DeleteWebhook(ctx, req, settings.GRPC...) diff --git a/dialogflow/cx/apiv3beta1/webhooks_client_example_test.go b/dialogflow/cx/apiv3beta1/webhooks_client_example_test.go index d54bb2b4291a..1f9f92e5c03d 100644 --- a/dialogflow/cx/apiv3beta1/webhooks_client_example_test.go +++ b/dialogflow/cx/apiv3beta1/webhooks_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewWebhooksClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleWebhooksClient_ListWebhooks() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewWebhooksClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListWebhooksRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleWebhooksClient_ListWebhooks() { } func ExampleWebhooksClient_GetWebhook() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewWebhooksClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetWebhookRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleWebhooksClient_GetWebhook() { } func ExampleWebhooksClient_CreateWebhook() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewWebhooksClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateWebhookRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleWebhooksClient_CreateWebhook() { } func ExampleWebhooksClient_UpdateWebhook() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewWebhooksClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateWebhookRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleWebhooksClient_DeleteWebhook() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteWebhookRequest{ // TODO: Fill request struct fields. diff --git a/dlp/apiv2/dlp_client.go b/dlp/apiv2/dlp_client.go index 38fd781e88c9..2069f352ff0b 100644 --- a/dlp/apiv2/dlp_client.go +++ b/dlp/apiv2/dlp_client.go @@ -75,7 +75,7 @@ type CallOptions struct { FinishDlpJob []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("dlp.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("dlp.mtls.googleapis.com:443"), @@ -346,27 +346,375 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Data Loss Prevention (DLP) API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + InspectContent(context.Context, *dlppb.InspectContentRequest, ...gax.CallOption) (*dlppb.InspectContentResponse, error) + RedactImage(context.Context, *dlppb.RedactImageRequest, ...gax.CallOption) (*dlppb.RedactImageResponse, error) + DeidentifyContent(context.Context, *dlppb.DeidentifyContentRequest, ...gax.CallOption) (*dlppb.DeidentifyContentResponse, error) + ReidentifyContent(context.Context, *dlppb.ReidentifyContentRequest, ...gax.CallOption) (*dlppb.ReidentifyContentResponse, error) + ListInfoTypes(context.Context, *dlppb.ListInfoTypesRequest, ...gax.CallOption) (*dlppb.ListInfoTypesResponse, error) + CreateInspectTemplate(context.Context, *dlppb.CreateInspectTemplateRequest, ...gax.CallOption) (*dlppb.InspectTemplate, error) + UpdateInspectTemplate(context.Context, *dlppb.UpdateInspectTemplateRequest, ...gax.CallOption) (*dlppb.InspectTemplate, error) + GetInspectTemplate(context.Context, *dlppb.GetInspectTemplateRequest, ...gax.CallOption) (*dlppb.InspectTemplate, error) + ListInspectTemplates(context.Context, *dlppb.ListInspectTemplatesRequest, ...gax.CallOption) *InspectTemplateIterator + DeleteInspectTemplate(context.Context, *dlppb.DeleteInspectTemplateRequest, ...gax.CallOption) error + CreateDeidentifyTemplate(context.Context, *dlppb.CreateDeidentifyTemplateRequest, ...gax.CallOption) (*dlppb.DeidentifyTemplate, error) + UpdateDeidentifyTemplate(context.Context, *dlppb.UpdateDeidentifyTemplateRequest, ...gax.CallOption) (*dlppb.DeidentifyTemplate, error) + GetDeidentifyTemplate(context.Context, *dlppb.GetDeidentifyTemplateRequest, ...gax.CallOption) (*dlppb.DeidentifyTemplate, error) + ListDeidentifyTemplates(context.Context, *dlppb.ListDeidentifyTemplatesRequest, ...gax.CallOption) *DeidentifyTemplateIterator + DeleteDeidentifyTemplate(context.Context, *dlppb.DeleteDeidentifyTemplateRequest, ...gax.CallOption) error + CreateJobTrigger(context.Context, *dlppb.CreateJobTriggerRequest, ...gax.CallOption) (*dlppb.JobTrigger, error) + UpdateJobTrigger(context.Context, *dlppb.UpdateJobTriggerRequest, ...gax.CallOption) (*dlppb.JobTrigger, error) + HybridInspectJobTrigger(context.Context, *dlppb.HybridInspectJobTriggerRequest, ...gax.CallOption) (*dlppb.HybridInspectResponse, error) + GetJobTrigger(context.Context, *dlppb.GetJobTriggerRequest, ...gax.CallOption) (*dlppb.JobTrigger, error) + ListJobTriggers(context.Context, *dlppb.ListJobTriggersRequest, ...gax.CallOption) *JobTriggerIterator + DeleteJobTrigger(context.Context, *dlppb.DeleteJobTriggerRequest, ...gax.CallOption) error + ActivateJobTrigger(context.Context, *dlppb.ActivateJobTriggerRequest, ...gax.CallOption) (*dlppb.DlpJob, error) + CreateDlpJob(context.Context, *dlppb.CreateDlpJobRequest, ...gax.CallOption) (*dlppb.DlpJob, error) + ListDlpJobs(context.Context, *dlppb.ListDlpJobsRequest, ...gax.CallOption) *DlpJobIterator + GetDlpJob(context.Context, *dlppb.GetDlpJobRequest, ...gax.CallOption) (*dlppb.DlpJob, error) + DeleteDlpJob(context.Context, *dlppb.DeleteDlpJobRequest, ...gax.CallOption) error + CancelDlpJob(context.Context, *dlppb.CancelDlpJobRequest, ...gax.CallOption) error + CreateStoredInfoType(context.Context, *dlppb.CreateStoredInfoTypeRequest, ...gax.CallOption) (*dlppb.StoredInfoType, error) + UpdateStoredInfoType(context.Context, *dlppb.UpdateStoredInfoTypeRequest, ...gax.CallOption) (*dlppb.StoredInfoType, error) + GetStoredInfoType(context.Context, *dlppb.GetStoredInfoTypeRequest, ...gax.CallOption) (*dlppb.StoredInfoType, error) + ListStoredInfoTypes(context.Context, *dlppb.ListStoredInfoTypesRequest, ...gax.CallOption) *StoredInfoTypeIterator + DeleteStoredInfoType(context.Context, *dlppb.DeleteStoredInfoTypeRequest, ...gax.CallOption) error + HybridInspectDlpJob(context.Context, *dlppb.HybridInspectDlpJobRequest, ...gax.CallOption) (*dlppb.HybridInspectResponse, error) + FinishDlpJob(context.Context, *dlppb.FinishDlpJobRequest, ...gax.CallOption) error +} + // Client is a client for interacting with Cloud Data Loss Prevention (DLP) API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The Cloud Data Loss Prevention (DLP) API is a service that allows clients +// to detect the presence of Personally Identifiable Information (PII) and other +// privacy-sensitive data in user-supplied, unstructured data streams, like text +// blocks or images. +// The service also includes methods for sensitive data redaction and +// scheduling of data scans on Google Cloud Platform based data sets. +// +// To learn more about concepts and find how-to guides see +// https://cloud.google.com/dlp/docs/ (at https://cloud.google.com/dlp/docs/). type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// InspectContent finds potentially sensitive info in content. +// This method has limits on input size, processing time, and output size. +// +// When no InfoTypes or CustomInfoTypes are specified in this request, the +// system will automatically choose what detectors to run. By default this may +// be all types, but may change over time as detectors are updated. +// +// For how to guides, see https://cloud.google.com/dlp/docs/inspecting-images (at https://cloud.google.com/dlp/docs/inspecting-images) +// and https://cloud.google.com/dlp/docs/inspecting-text (at https://cloud.google.com/dlp/docs/inspecting-text), +func (c *Client) InspectContent(ctx context.Context, req *dlppb.InspectContentRequest, opts ...gax.CallOption) (*dlppb.InspectContentResponse, error) { + return c.internalClient.InspectContent(ctx, req, opts...) +} + +// RedactImage redacts potentially sensitive info from an image. +// This method has limits on input size, processing time, and output size. +// See https://cloud.google.com/dlp/docs/redacting-sensitive-data-images (at https://cloud.google.com/dlp/docs/redacting-sensitive-data-images) to +// learn more. +// +// When no InfoTypes or CustomInfoTypes are specified in this request, the +// system will automatically choose what detectors to run. By default this may +// be all types, but may change over time as detectors are updated. +func (c *Client) RedactImage(ctx context.Context, req *dlppb.RedactImageRequest, opts ...gax.CallOption) (*dlppb.RedactImageResponse, error) { + return c.internalClient.RedactImage(ctx, req, opts...) +} + +// DeidentifyContent de-identifies potentially sensitive info from a ContentItem. +// This method has limits on input size and output size. +// See https://cloud.google.com/dlp/docs/deidentify-sensitive-data (at https://cloud.google.com/dlp/docs/deidentify-sensitive-data) to +// learn more. +// +// When no InfoTypes or CustomInfoTypes are specified in this request, the +// system will automatically choose what detectors to run. By default this may +// be all types, but may change over time as detectors are updated. +func (c *Client) DeidentifyContent(ctx context.Context, req *dlppb.DeidentifyContentRequest, opts ...gax.CallOption) (*dlppb.DeidentifyContentResponse, error) { + return c.internalClient.DeidentifyContent(ctx, req, opts...) +} + +// ReidentifyContent re-identifies content that has been de-identified. +// See +// https://cloud.google.com/dlp/docs/pseudonymization#re-identification_in_free_text_code_example (at https://cloud.google.com/dlp/docs/pseudonymization#re-identification_in_free_text_code_example) +// to learn more. +func (c *Client) ReidentifyContent(ctx context.Context, req *dlppb.ReidentifyContentRequest, opts ...gax.CallOption) (*dlppb.ReidentifyContentResponse, error) { + return c.internalClient.ReidentifyContent(ctx, req, opts...) +} + +// ListInfoTypes returns a list of the sensitive information types that the DLP API +// supports. See https://cloud.google.com/dlp/docs/infotypes-reference (at https://cloud.google.com/dlp/docs/infotypes-reference) to +// learn more. +func (c *Client) ListInfoTypes(ctx context.Context, req *dlppb.ListInfoTypesRequest, opts ...gax.CallOption) (*dlppb.ListInfoTypesResponse, error) { + return c.internalClient.ListInfoTypes(ctx, req, opts...) +} + +// CreateInspectTemplate creates an InspectTemplate for re-using frequently used configuration +// for inspecting content, images, and storage. +// See https://cloud.google.com/dlp/docs/creating-templates (at https://cloud.google.com/dlp/docs/creating-templates) to learn more. +func (c *Client) CreateInspectTemplate(ctx context.Context, req *dlppb.CreateInspectTemplateRequest, opts ...gax.CallOption) (*dlppb.InspectTemplate, error) { + return c.internalClient.CreateInspectTemplate(ctx, req, opts...) +} + +// UpdateInspectTemplate updates the InspectTemplate. +// See https://cloud.google.com/dlp/docs/creating-templates (at https://cloud.google.com/dlp/docs/creating-templates) to learn more. +func (c *Client) UpdateInspectTemplate(ctx context.Context, req *dlppb.UpdateInspectTemplateRequest, opts ...gax.CallOption) (*dlppb.InspectTemplate, error) { + return c.internalClient.UpdateInspectTemplate(ctx, req, opts...) +} + +// GetInspectTemplate gets an InspectTemplate. +// See https://cloud.google.com/dlp/docs/creating-templates (at https://cloud.google.com/dlp/docs/creating-templates) to learn more. +func (c *Client) GetInspectTemplate(ctx context.Context, req *dlppb.GetInspectTemplateRequest, opts ...gax.CallOption) (*dlppb.InspectTemplate, error) { + return c.internalClient.GetInspectTemplate(ctx, req, opts...) +} + +// ListInspectTemplates lists InspectTemplates. +// See https://cloud.google.com/dlp/docs/creating-templates (at https://cloud.google.com/dlp/docs/creating-templates) to learn more. +func (c *Client) ListInspectTemplates(ctx context.Context, req *dlppb.ListInspectTemplatesRequest, opts ...gax.CallOption) *InspectTemplateIterator { + return c.internalClient.ListInspectTemplates(ctx, req, opts...) +} + +// DeleteInspectTemplate deletes an InspectTemplate. +// See https://cloud.google.com/dlp/docs/creating-templates (at https://cloud.google.com/dlp/docs/creating-templates) to learn more. +func (c *Client) DeleteInspectTemplate(ctx context.Context, req *dlppb.DeleteInspectTemplateRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteInspectTemplate(ctx, req, opts...) +} + +// CreateDeidentifyTemplate creates a DeidentifyTemplate for re-using frequently used configuration +// for de-identifying content, images, and storage. +// See https://cloud.google.com/dlp/docs/creating-templates-deid (at https://cloud.google.com/dlp/docs/creating-templates-deid) to learn +// more. +func (c *Client) CreateDeidentifyTemplate(ctx context.Context, req *dlppb.CreateDeidentifyTemplateRequest, opts ...gax.CallOption) (*dlppb.DeidentifyTemplate, error) { + return c.internalClient.CreateDeidentifyTemplate(ctx, req, opts...) +} + +// UpdateDeidentifyTemplate updates the DeidentifyTemplate. +// See https://cloud.google.com/dlp/docs/creating-templates-deid (at https://cloud.google.com/dlp/docs/creating-templates-deid) to learn +// more. +func (c *Client) UpdateDeidentifyTemplate(ctx context.Context, req *dlppb.UpdateDeidentifyTemplateRequest, opts ...gax.CallOption) (*dlppb.DeidentifyTemplate, error) { + return c.internalClient.UpdateDeidentifyTemplate(ctx, req, opts...) +} + +// GetDeidentifyTemplate gets a DeidentifyTemplate. +// See https://cloud.google.com/dlp/docs/creating-templates-deid (at https://cloud.google.com/dlp/docs/creating-templates-deid) to learn +// more. +func (c *Client) GetDeidentifyTemplate(ctx context.Context, req *dlppb.GetDeidentifyTemplateRequest, opts ...gax.CallOption) (*dlppb.DeidentifyTemplate, error) { + return c.internalClient.GetDeidentifyTemplate(ctx, req, opts...) +} + +// ListDeidentifyTemplates lists DeidentifyTemplates. +// See https://cloud.google.com/dlp/docs/creating-templates-deid (at https://cloud.google.com/dlp/docs/creating-templates-deid) to learn +// more. +func (c *Client) ListDeidentifyTemplates(ctx context.Context, req *dlppb.ListDeidentifyTemplatesRequest, opts ...gax.CallOption) *DeidentifyTemplateIterator { + return c.internalClient.ListDeidentifyTemplates(ctx, req, opts...) +} + +// DeleteDeidentifyTemplate deletes a DeidentifyTemplate. +// See https://cloud.google.com/dlp/docs/creating-templates-deid (at https://cloud.google.com/dlp/docs/creating-templates-deid) to learn +// more. +func (c *Client) DeleteDeidentifyTemplate(ctx context.Context, req *dlppb.DeleteDeidentifyTemplateRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteDeidentifyTemplate(ctx, req, opts...) +} + +// CreateJobTrigger creates a job trigger to run DLP actions such as scanning storage for +// sensitive information on a set schedule. +// See https://cloud.google.com/dlp/docs/creating-job-triggers (at https://cloud.google.com/dlp/docs/creating-job-triggers) to learn more. +func (c *Client) CreateJobTrigger(ctx context.Context, req *dlppb.CreateJobTriggerRequest, opts ...gax.CallOption) (*dlppb.JobTrigger, error) { + return c.internalClient.CreateJobTrigger(ctx, req, opts...) +} + +// UpdateJobTrigger updates a job trigger. +// See https://cloud.google.com/dlp/docs/creating-job-triggers (at https://cloud.google.com/dlp/docs/creating-job-triggers) to learn more. +func (c *Client) UpdateJobTrigger(ctx context.Context, req *dlppb.UpdateJobTriggerRequest, opts ...gax.CallOption) (*dlppb.JobTrigger, error) { + return c.internalClient.UpdateJobTrigger(ctx, req, opts...) +} + +// HybridInspectJobTrigger inspect hybrid content and store findings to a trigger. The inspection +// will be processed asynchronously. To review the findings monitor the +// jobs within the trigger. +// Early access feature is in a pre-release state and might change or have +// limited support. For more information, see +// https://cloud.google.com/products#product-launch-stages (at https://cloud.google.com/products#product-launch-stages). +func (c *Client) HybridInspectJobTrigger(ctx context.Context, req *dlppb.HybridInspectJobTriggerRequest, opts ...gax.CallOption) (*dlppb.HybridInspectResponse, error) { + return c.internalClient.HybridInspectJobTrigger(ctx, req, opts...) +} + +// GetJobTrigger gets a job trigger. +// See https://cloud.google.com/dlp/docs/creating-job-triggers (at https://cloud.google.com/dlp/docs/creating-job-triggers) to learn more. +func (c *Client) GetJobTrigger(ctx context.Context, req *dlppb.GetJobTriggerRequest, opts ...gax.CallOption) (*dlppb.JobTrigger, error) { + return c.internalClient.GetJobTrigger(ctx, req, opts...) +} + +// ListJobTriggers lists job triggers. +// See https://cloud.google.com/dlp/docs/creating-job-triggers (at https://cloud.google.com/dlp/docs/creating-job-triggers) to learn more. +func (c *Client) ListJobTriggers(ctx context.Context, req *dlppb.ListJobTriggersRequest, opts ...gax.CallOption) *JobTriggerIterator { + return c.internalClient.ListJobTriggers(ctx, req, opts...) +} + +// DeleteJobTrigger deletes a job trigger. +// See https://cloud.google.com/dlp/docs/creating-job-triggers (at https://cloud.google.com/dlp/docs/creating-job-triggers) to learn more. +func (c *Client) DeleteJobTrigger(ctx context.Context, req *dlppb.DeleteJobTriggerRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteJobTrigger(ctx, req, opts...) +} + +// ActivateJobTrigger activate a job trigger. Causes the immediate execute of a trigger +// instead of waiting on the trigger event to occur. +func (c *Client) ActivateJobTrigger(ctx context.Context, req *dlppb.ActivateJobTriggerRequest, opts ...gax.CallOption) (*dlppb.DlpJob, error) { + return c.internalClient.ActivateJobTrigger(ctx, req, opts...) +} + +// CreateDlpJob creates a new job to inspect storage or calculate risk metrics. +// See https://cloud.google.com/dlp/docs/inspecting-storage (at https://cloud.google.com/dlp/docs/inspecting-storage) and +// https://cloud.google.com/dlp/docs/compute-risk-analysis (at https://cloud.google.com/dlp/docs/compute-risk-analysis) to learn more. +// +// When no InfoTypes or CustomInfoTypes are specified in inspect jobs, the +// system will automatically choose what detectors to run. By default this may +// be all types, but may change over time as detectors are updated. +func (c *Client) CreateDlpJob(ctx context.Context, req *dlppb.CreateDlpJobRequest, opts ...gax.CallOption) (*dlppb.DlpJob, error) { + return c.internalClient.CreateDlpJob(ctx, req, opts...) +} + +// ListDlpJobs lists DlpJobs that match the specified filter in the request. +// See https://cloud.google.com/dlp/docs/inspecting-storage (at https://cloud.google.com/dlp/docs/inspecting-storage) and +// https://cloud.google.com/dlp/docs/compute-risk-analysis (at https://cloud.google.com/dlp/docs/compute-risk-analysis) to learn more. +func (c *Client) ListDlpJobs(ctx context.Context, req *dlppb.ListDlpJobsRequest, opts ...gax.CallOption) *DlpJobIterator { + return c.internalClient.ListDlpJobs(ctx, req, opts...) +} + +// GetDlpJob gets the latest state of a long-running DlpJob. +// See https://cloud.google.com/dlp/docs/inspecting-storage (at https://cloud.google.com/dlp/docs/inspecting-storage) and +// https://cloud.google.com/dlp/docs/compute-risk-analysis (at https://cloud.google.com/dlp/docs/compute-risk-analysis) to learn more. +func (c *Client) GetDlpJob(ctx context.Context, req *dlppb.GetDlpJobRequest, opts ...gax.CallOption) (*dlppb.DlpJob, error) { + return c.internalClient.GetDlpJob(ctx, req, opts...) +} + +// DeleteDlpJob deletes a long-running DlpJob. This method indicates that the client is +// no longer interested in the DlpJob result. The job will be cancelled if +// possible. +// See https://cloud.google.com/dlp/docs/inspecting-storage (at https://cloud.google.com/dlp/docs/inspecting-storage) and +// https://cloud.google.com/dlp/docs/compute-risk-analysis (at https://cloud.google.com/dlp/docs/compute-risk-analysis) to learn more. +func (c *Client) DeleteDlpJob(ctx context.Context, req *dlppb.DeleteDlpJobRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteDlpJob(ctx, req, opts...) +} + +// CancelDlpJob starts asynchronous cancellation on a long-running DlpJob. The server +// makes a best effort to cancel the DlpJob, but success is not +// guaranteed. +// See https://cloud.google.com/dlp/docs/inspecting-storage (at https://cloud.google.com/dlp/docs/inspecting-storage) and +// https://cloud.google.com/dlp/docs/compute-risk-analysis (at https://cloud.google.com/dlp/docs/compute-risk-analysis) to learn more. +func (c *Client) CancelDlpJob(ctx context.Context, req *dlppb.CancelDlpJobRequest, opts ...gax.CallOption) error { + return c.internalClient.CancelDlpJob(ctx, req, opts...) +} + +// CreateStoredInfoType creates a pre-built stored infoType to be used for inspection. +// See https://cloud.google.com/dlp/docs/creating-stored-infotypes (at https://cloud.google.com/dlp/docs/creating-stored-infotypes) to +// learn more. +func (c *Client) CreateStoredInfoType(ctx context.Context, req *dlppb.CreateStoredInfoTypeRequest, opts ...gax.CallOption) (*dlppb.StoredInfoType, error) { + return c.internalClient.CreateStoredInfoType(ctx, req, opts...) +} + +// UpdateStoredInfoType updates the stored infoType by creating a new version. The existing version +// will continue to be used until the new version is ready. +// See https://cloud.google.com/dlp/docs/creating-stored-infotypes (at https://cloud.google.com/dlp/docs/creating-stored-infotypes) to +// learn more. +func (c *Client) UpdateStoredInfoType(ctx context.Context, req *dlppb.UpdateStoredInfoTypeRequest, opts ...gax.CallOption) (*dlppb.StoredInfoType, error) { + return c.internalClient.UpdateStoredInfoType(ctx, req, opts...) +} + +// GetStoredInfoType gets a stored infoType. +// See https://cloud.google.com/dlp/docs/creating-stored-infotypes (at https://cloud.google.com/dlp/docs/creating-stored-infotypes) to +// learn more. +func (c *Client) GetStoredInfoType(ctx context.Context, req *dlppb.GetStoredInfoTypeRequest, opts ...gax.CallOption) (*dlppb.StoredInfoType, error) { + return c.internalClient.GetStoredInfoType(ctx, req, opts...) +} + +// ListStoredInfoTypes lists stored infoTypes. +// See https://cloud.google.com/dlp/docs/creating-stored-infotypes (at https://cloud.google.com/dlp/docs/creating-stored-infotypes) to +// learn more. +func (c *Client) ListStoredInfoTypes(ctx context.Context, req *dlppb.ListStoredInfoTypesRequest, opts ...gax.CallOption) *StoredInfoTypeIterator { + return c.internalClient.ListStoredInfoTypes(ctx, req, opts...) +} + +// DeleteStoredInfoType deletes a stored infoType. +// See https://cloud.google.com/dlp/docs/creating-stored-infotypes (at https://cloud.google.com/dlp/docs/creating-stored-infotypes) to +// learn more. +func (c *Client) DeleteStoredInfoType(ctx context.Context, req *dlppb.DeleteStoredInfoTypeRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteStoredInfoType(ctx, req, opts...) +} + +// HybridInspectDlpJob inspect hybrid content and store findings to a job. +// To review the findings inspect the job. Inspection will occur +// asynchronously. +// Early access feature is in a pre-release state and might change or have +// limited support. For more information, see +// https://cloud.google.com/products#product-launch-stages (at https://cloud.google.com/products#product-launch-stages). +func (c *Client) HybridInspectDlpJob(ctx context.Context, req *dlppb.HybridInspectDlpJobRequest, opts ...gax.CallOption) (*dlppb.HybridInspectResponse, error) { + return c.internalClient.HybridInspectDlpJob(ctx, req, opts...) +} + +// FinishDlpJob finish a running hybrid DlpJob. Triggers the finalization steps and running +// of any enabled actions that have not yet run. +// Early access feature is in a pre-release state and might change or have +// limited support. For more information, see +// https://cloud.google.com/products#product-launch-stages (at https://cloud.google.com/products#product-launch-stages). +func (c *Client) FinishDlpJob(ctx context.Context, req *dlppb.FinishDlpJobRequest, opts ...gax.CallOption) error { + return c.internalClient.FinishDlpJob(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud Data Loss Prevention (DLP) API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client dlppb.DlpServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new dlp service client. +// NewClient creates a new dlp service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The Cloud Data Loss Prevention (DLP) API is a service that allows clients // to detect the presence of Personally Identifiable Information (PII) and other @@ -378,8 +726,7 @@ type Client struct { // To learn more about concepts and find how-to guides see // https://cloud.google.com/dlp/docs/ (at https://cloud.google.com/dlp/docs/). func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -397,50 +744,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: dlppb.NewDlpServiceClient(connPool), + client: dlppb.NewDlpServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// InspectContent finds potentially sensitive info in content. -// This method has limits on input size, processing time, and output size. -// -// When no InfoTypes or CustomInfoTypes are specified in this request, the -// system will automatically choose what detectors to run. By default this may -// be all types, but may change over time as detectors are updated. -// -// For how to guides, see https://cloud.google.com/dlp/docs/inspecting-images (at https://cloud.google.com/dlp/docs/inspecting-images) -// and https://cloud.google.com/dlp/docs/inspecting-text (at https://cloud.google.com/dlp/docs/inspecting-text), -func (c *Client) InspectContent(ctx context.Context, req *dlppb.InspectContentRequest, opts ...gax.CallOption) (*dlppb.InspectContentResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) InspectContent(ctx context.Context, req *dlppb.InspectContentRequest, opts ...gax.CallOption) (*dlppb.InspectContentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -448,7 +789,7 @@ func (c *Client) InspectContent(ctx context.Context, req *dlppb.InspectContentRe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.InspectContent[0:len(c.CallOptions.InspectContent):len(c.CallOptions.InspectContent)], opts...) + opts = append((*c.CallOptions).InspectContent[0:len((*c.CallOptions).InspectContent):len((*c.CallOptions).InspectContent)], opts...) var resp *dlppb.InspectContentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -461,15 +802,7 @@ func (c *Client) InspectContent(ctx context.Context, req *dlppb.InspectContentRe return resp, nil } -// RedactImage redacts potentially sensitive info from an image. -// This method has limits on input size, processing time, and output size. -// See https://cloud.google.com/dlp/docs/redacting-sensitive-data-images (at https://cloud.google.com/dlp/docs/redacting-sensitive-data-images) to -// learn more. -// -// When no InfoTypes or CustomInfoTypes are specified in this request, the -// system will automatically choose what detectors to run. By default this may -// be all types, but may change over time as detectors are updated. -func (c *Client) RedactImage(ctx context.Context, req *dlppb.RedactImageRequest, opts ...gax.CallOption) (*dlppb.RedactImageResponse, error) { +func (c *gRPCClient) RedactImage(ctx context.Context, req *dlppb.RedactImageRequest, opts ...gax.CallOption) (*dlppb.RedactImageResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -477,7 +810,7 @@ func (c *Client) RedactImage(ctx context.Context, req *dlppb.RedactImageRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RedactImage[0:len(c.CallOptions.RedactImage):len(c.CallOptions.RedactImage)], opts...) + opts = append((*c.CallOptions).RedactImage[0:len((*c.CallOptions).RedactImage):len((*c.CallOptions).RedactImage)], opts...) var resp *dlppb.RedactImageResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -490,15 +823,7 @@ func (c *Client) RedactImage(ctx context.Context, req *dlppb.RedactImageRequest, return resp, nil } -// DeidentifyContent de-identifies potentially sensitive info from a ContentItem. -// This method has limits on input size and output size. -// See https://cloud.google.com/dlp/docs/deidentify-sensitive-data (at https://cloud.google.com/dlp/docs/deidentify-sensitive-data) to -// learn more. -// -// When no InfoTypes or CustomInfoTypes are specified in this request, the -// system will automatically choose what detectors to run. By default this may -// be all types, but may change over time as detectors are updated. -func (c *Client) DeidentifyContent(ctx context.Context, req *dlppb.DeidentifyContentRequest, opts ...gax.CallOption) (*dlppb.DeidentifyContentResponse, error) { +func (c *gRPCClient) DeidentifyContent(ctx context.Context, req *dlppb.DeidentifyContentRequest, opts ...gax.CallOption) (*dlppb.DeidentifyContentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -506,7 +831,7 @@ func (c *Client) DeidentifyContent(ctx context.Context, req *dlppb.DeidentifyCon } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeidentifyContent[0:len(c.CallOptions.DeidentifyContent):len(c.CallOptions.DeidentifyContent)], opts...) + opts = append((*c.CallOptions).DeidentifyContent[0:len((*c.CallOptions).DeidentifyContent):len((*c.CallOptions).DeidentifyContent)], opts...) var resp *dlppb.DeidentifyContentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -519,11 +844,7 @@ func (c *Client) DeidentifyContent(ctx context.Context, req *dlppb.DeidentifyCon return resp, nil } -// ReidentifyContent re-identifies content that has been de-identified. -// See -// https://cloud.google.com/dlp/docs/pseudonymization#re-identification_in_free_text_code_example (at https://cloud.google.com/dlp/docs/pseudonymization#re-identification_in_free_text_code_example) -// to learn more. -func (c *Client) ReidentifyContent(ctx context.Context, req *dlppb.ReidentifyContentRequest, opts ...gax.CallOption) (*dlppb.ReidentifyContentResponse, error) { +func (c *gRPCClient) ReidentifyContent(ctx context.Context, req *dlppb.ReidentifyContentRequest, opts ...gax.CallOption) (*dlppb.ReidentifyContentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -531,7 +852,7 @@ func (c *Client) ReidentifyContent(ctx context.Context, req *dlppb.ReidentifyCon } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ReidentifyContent[0:len(c.CallOptions.ReidentifyContent):len(c.CallOptions.ReidentifyContent)], opts...) + opts = append((*c.CallOptions).ReidentifyContent[0:len((*c.CallOptions).ReidentifyContent):len((*c.CallOptions).ReidentifyContent)], opts...) var resp *dlppb.ReidentifyContentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -544,10 +865,7 @@ func (c *Client) ReidentifyContent(ctx context.Context, req *dlppb.ReidentifyCon return resp, nil } -// ListInfoTypes returns a list of the sensitive information types that the DLP API -// supports. See https://cloud.google.com/dlp/docs/infotypes-reference (at https://cloud.google.com/dlp/docs/infotypes-reference) to -// learn more. -func (c *Client) ListInfoTypes(ctx context.Context, req *dlppb.ListInfoTypesRequest, opts ...gax.CallOption) (*dlppb.ListInfoTypesResponse, error) { +func (c *gRPCClient) ListInfoTypes(ctx context.Context, req *dlppb.ListInfoTypesRequest, opts ...gax.CallOption) (*dlppb.ListInfoTypesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -555,7 +873,7 @@ func (c *Client) ListInfoTypes(ctx context.Context, req *dlppb.ListInfoTypesRequ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListInfoTypes[0:len(c.CallOptions.ListInfoTypes):len(c.CallOptions.ListInfoTypes)], opts...) + opts = append((*c.CallOptions).ListInfoTypes[0:len((*c.CallOptions).ListInfoTypes):len((*c.CallOptions).ListInfoTypes)], opts...) var resp *dlppb.ListInfoTypesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -568,10 +886,7 @@ func (c *Client) ListInfoTypes(ctx context.Context, req *dlppb.ListInfoTypesRequ return resp, nil } -// CreateInspectTemplate creates an InspectTemplate for re-using frequently used configuration -// for inspecting content, images, and storage. -// See https://cloud.google.com/dlp/docs/creating-templates (at https://cloud.google.com/dlp/docs/creating-templates) to learn more. -func (c *Client) CreateInspectTemplate(ctx context.Context, req *dlppb.CreateInspectTemplateRequest, opts ...gax.CallOption) (*dlppb.InspectTemplate, error) { +func (c *gRPCClient) CreateInspectTemplate(ctx context.Context, req *dlppb.CreateInspectTemplateRequest, opts ...gax.CallOption) (*dlppb.InspectTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -579,7 +894,7 @@ func (c *Client) CreateInspectTemplate(ctx context.Context, req *dlppb.CreateIns } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateInspectTemplate[0:len(c.CallOptions.CreateInspectTemplate):len(c.CallOptions.CreateInspectTemplate)], opts...) + opts = append((*c.CallOptions).CreateInspectTemplate[0:len((*c.CallOptions).CreateInspectTemplate):len((*c.CallOptions).CreateInspectTemplate)], opts...) var resp *dlppb.InspectTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -592,9 +907,7 @@ func (c *Client) CreateInspectTemplate(ctx context.Context, req *dlppb.CreateIns return resp, nil } -// UpdateInspectTemplate updates the InspectTemplate. -// See https://cloud.google.com/dlp/docs/creating-templates (at https://cloud.google.com/dlp/docs/creating-templates) to learn more. -func (c *Client) UpdateInspectTemplate(ctx context.Context, req *dlppb.UpdateInspectTemplateRequest, opts ...gax.CallOption) (*dlppb.InspectTemplate, error) { +func (c *gRPCClient) UpdateInspectTemplate(ctx context.Context, req *dlppb.UpdateInspectTemplateRequest, opts ...gax.CallOption) (*dlppb.InspectTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -602,7 +915,7 @@ func (c *Client) UpdateInspectTemplate(ctx context.Context, req *dlppb.UpdateIns } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateInspectTemplate[0:len(c.CallOptions.UpdateInspectTemplate):len(c.CallOptions.UpdateInspectTemplate)], opts...) + opts = append((*c.CallOptions).UpdateInspectTemplate[0:len((*c.CallOptions).UpdateInspectTemplate):len((*c.CallOptions).UpdateInspectTemplate)], opts...) var resp *dlppb.InspectTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -615,9 +928,7 @@ func (c *Client) UpdateInspectTemplate(ctx context.Context, req *dlppb.UpdateIns return resp, nil } -// GetInspectTemplate gets an InspectTemplate. -// See https://cloud.google.com/dlp/docs/creating-templates (at https://cloud.google.com/dlp/docs/creating-templates) to learn more. -func (c *Client) GetInspectTemplate(ctx context.Context, req *dlppb.GetInspectTemplateRequest, opts ...gax.CallOption) (*dlppb.InspectTemplate, error) { +func (c *gRPCClient) GetInspectTemplate(ctx context.Context, req *dlppb.GetInspectTemplateRequest, opts ...gax.CallOption) (*dlppb.InspectTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -625,7 +936,7 @@ func (c *Client) GetInspectTemplate(ctx context.Context, req *dlppb.GetInspectTe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetInspectTemplate[0:len(c.CallOptions.GetInspectTemplate):len(c.CallOptions.GetInspectTemplate)], opts...) + opts = append((*c.CallOptions).GetInspectTemplate[0:len((*c.CallOptions).GetInspectTemplate):len((*c.CallOptions).GetInspectTemplate)], opts...) var resp *dlppb.InspectTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -638,12 +949,10 @@ func (c *Client) GetInspectTemplate(ctx context.Context, req *dlppb.GetInspectTe return resp, nil } -// ListInspectTemplates lists InspectTemplates. -// See https://cloud.google.com/dlp/docs/creating-templates (at https://cloud.google.com/dlp/docs/creating-templates) to learn more. -func (c *Client) ListInspectTemplates(ctx context.Context, req *dlppb.ListInspectTemplatesRequest, opts ...gax.CallOption) *InspectTemplateIterator { +func (c *gRPCClient) ListInspectTemplates(ctx context.Context, req *dlppb.ListInspectTemplatesRequest, opts ...gax.CallOption) *InspectTemplateIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListInspectTemplates[0:len(c.CallOptions.ListInspectTemplates):len(c.CallOptions.ListInspectTemplates)], opts...) + opts = append((*c.CallOptions).ListInspectTemplates[0:len((*c.CallOptions).ListInspectTemplates):len((*c.CallOptions).ListInspectTemplates)], opts...) it := &InspectTemplateIterator{} req = proto.Clone(req).(*dlppb.ListInspectTemplatesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dlppb.InspectTemplate, string, error) { @@ -680,9 +989,7 @@ func (c *Client) ListInspectTemplates(ctx context.Context, req *dlppb.ListInspec return it } -// DeleteInspectTemplate deletes an InspectTemplate. -// See https://cloud.google.com/dlp/docs/creating-templates (at https://cloud.google.com/dlp/docs/creating-templates) to learn more. -func (c *Client) DeleteInspectTemplate(ctx context.Context, req *dlppb.DeleteInspectTemplateRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteInspectTemplate(ctx context.Context, req *dlppb.DeleteInspectTemplateRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -690,7 +997,7 @@ func (c *Client) DeleteInspectTemplate(ctx context.Context, req *dlppb.DeleteIns } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteInspectTemplate[0:len(c.CallOptions.DeleteInspectTemplate):len(c.CallOptions.DeleteInspectTemplate)], opts...) + opts = append((*c.CallOptions).DeleteInspectTemplate[0:len((*c.CallOptions).DeleteInspectTemplate):len((*c.CallOptions).DeleteInspectTemplate)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteInspectTemplate(ctx, req, settings.GRPC...) @@ -699,11 +1006,7 @@ func (c *Client) DeleteInspectTemplate(ctx context.Context, req *dlppb.DeleteIns return err } -// CreateDeidentifyTemplate creates a DeidentifyTemplate for re-using frequently used configuration -// for de-identifying content, images, and storage. -// See https://cloud.google.com/dlp/docs/creating-templates-deid (at https://cloud.google.com/dlp/docs/creating-templates-deid) to learn -// more. -func (c *Client) CreateDeidentifyTemplate(ctx context.Context, req *dlppb.CreateDeidentifyTemplateRequest, opts ...gax.CallOption) (*dlppb.DeidentifyTemplate, error) { +func (c *gRPCClient) CreateDeidentifyTemplate(ctx context.Context, req *dlppb.CreateDeidentifyTemplateRequest, opts ...gax.CallOption) (*dlppb.DeidentifyTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -711,7 +1014,7 @@ func (c *Client) CreateDeidentifyTemplate(ctx context.Context, req *dlppb.Create } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateDeidentifyTemplate[0:len(c.CallOptions.CreateDeidentifyTemplate):len(c.CallOptions.CreateDeidentifyTemplate)], opts...) + opts = append((*c.CallOptions).CreateDeidentifyTemplate[0:len((*c.CallOptions).CreateDeidentifyTemplate):len((*c.CallOptions).CreateDeidentifyTemplate)], opts...) var resp *dlppb.DeidentifyTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -724,10 +1027,7 @@ func (c *Client) CreateDeidentifyTemplate(ctx context.Context, req *dlppb.Create return resp, nil } -// UpdateDeidentifyTemplate updates the DeidentifyTemplate. -// See https://cloud.google.com/dlp/docs/creating-templates-deid (at https://cloud.google.com/dlp/docs/creating-templates-deid) to learn -// more. -func (c *Client) UpdateDeidentifyTemplate(ctx context.Context, req *dlppb.UpdateDeidentifyTemplateRequest, opts ...gax.CallOption) (*dlppb.DeidentifyTemplate, error) { +func (c *gRPCClient) UpdateDeidentifyTemplate(ctx context.Context, req *dlppb.UpdateDeidentifyTemplateRequest, opts ...gax.CallOption) (*dlppb.DeidentifyTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -735,7 +1035,7 @@ func (c *Client) UpdateDeidentifyTemplate(ctx context.Context, req *dlppb.Update } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateDeidentifyTemplate[0:len(c.CallOptions.UpdateDeidentifyTemplate):len(c.CallOptions.UpdateDeidentifyTemplate)], opts...) + opts = append((*c.CallOptions).UpdateDeidentifyTemplate[0:len((*c.CallOptions).UpdateDeidentifyTemplate):len((*c.CallOptions).UpdateDeidentifyTemplate)], opts...) var resp *dlppb.DeidentifyTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -748,10 +1048,7 @@ func (c *Client) UpdateDeidentifyTemplate(ctx context.Context, req *dlppb.Update return resp, nil } -// GetDeidentifyTemplate gets a DeidentifyTemplate. -// See https://cloud.google.com/dlp/docs/creating-templates-deid (at https://cloud.google.com/dlp/docs/creating-templates-deid) to learn -// more. -func (c *Client) GetDeidentifyTemplate(ctx context.Context, req *dlppb.GetDeidentifyTemplateRequest, opts ...gax.CallOption) (*dlppb.DeidentifyTemplate, error) { +func (c *gRPCClient) GetDeidentifyTemplate(ctx context.Context, req *dlppb.GetDeidentifyTemplateRequest, opts ...gax.CallOption) (*dlppb.DeidentifyTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -759,7 +1056,7 @@ func (c *Client) GetDeidentifyTemplate(ctx context.Context, req *dlppb.GetDeiden } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetDeidentifyTemplate[0:len(c.CallOptions.GetDeidentifyTemplate):len(c.CallOptions.GetDeidentifyTemplate)], opts...) + opts = append((*c.CallOptions).GetDeidentifyTemplate[0:len((*c.CallOptions).GetDeidentifyTemplate):len((*c.CallOptions).GetDeidentifyTemplate)], opts...) var resp *dlppb.DeidentifyTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -772,13 +1069,10 @@ func (c *Client) GetDeidentifyTemplate(ctx context.Context, req *dlppb.GetDeiden return resp, nil } -// ListDeidentifyTemplates lists DeidentifyTemplates. -// See https://cloud.google.com/dlp/docs/creating-templates-deid (at https://cloud.google.com/dlp/docs/creating-templates-deid) to learn -// more. -func (c *Client) ListDeidentifyTemplates(ctx context.Context, req *dlppb.ListDeidentifyTemplatesRequest, opts ...gax.CallOption) *DeidentifyTemplateIterator { +func (c *gRPCClient) ListDeidentifyTemplates(ctx context.Context, req *dlppb.ListDeidentifyTemplatesRequest, opts ...gax.CallOption) *DeidentifyTemplateIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDeidentifyTemplates[0:len(c.CallOptions.ListDeidentifyTemplates):len(c.CallOptions.ListDeidentifyTemplates)], opts...) + opts = append((*c.CallOptions).ListDeidentifyTemplates[0:len((*c.CallOptions).ListDeidentifyTemplates):len((*c.CallOptions).ListDeidentifyTemplates)], opts...) it := &DeidentifyTemplateIterator{} req = proto.Clone(req).(*dlppb.ListDeidentifyTemplatesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dlppb.DeidentifyTemplate, string, error) { @@ -815,10 +1109,7 @@ func (c *Client) ListDeidentifyTemplates(ctx context.Context, req *dlppb.ListDei return it } -// DeleteDeidentifyTemplate deletes a DeidentifyTemplate. -// See https://cloud.google.com/dlp/docs/creating-templates-deid (at https://cloud.google.com/dlp/docs/creating-templates-deid) to learn -// more. -func (c *Client) DeleteDeidentifyTemplate(ctx context.Context, req *dlppb.DeleteDeidentifyTemplateRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteDeidentifyTemplate(ctx context.Context, req *dlppb.DeleteDeidentifyTemplateRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -826,7 +1117,7 @@ func (c *Client) DeleteDeidentifyTemplate(ctx context.Context, req *dlppb.Delete } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteDeidentifyTemplate[0:len(c.CallOptions.DeleteDeidentifyTemplate):len(c.CallOptions.DeleteDeidentifyTemplate)], opts...) + opts = append((*c.CallOptions).DeleteDeidentifyTemplate[0:len((*c.CallOptions).DeleteDeidentifyTemplate):len((*c.CallOptions).DeleteDeidentifyTemplate)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteDeidentifyTemplate(ctx, req, settings.GRPC...) @@ -835,10 +1126,7 @@ func (c *Client) DeleteDeidentifyTemplate(ctx context.Context, req *dlppb.Delete return err } -// CreateJobTrigger creates a job trigger to run DLP actions such as scanning storage for -// sensitive information on a set schedule. -// See https://cloud.google.com/dlp/docs/creating-job-triggers (at https://cloud.google.com/dlp/docs/creating-job-triggers) to learn more. -func (c *Client) CreateJobTrigger(ctx context.Context, req *dlppb.CreateJobTriggerRequest, opts ...gax.CallOption) (*dlppb.JobTrigger, error) { +func (c *gRPCClient) CreateJobTrigger(ctx context.Context, req *dlppb.CreateJobTriggerRequest, opts ...gax.CallOption) (*dlppb.JobTrigger, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -846,7 +1134,7 @@ func (c *Client) CreateJobTrigger(ctx context.Context, req *dlppb.CreateJobTrigg } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateJobTrigger[0:len(c.CallOptions.CreateJobTrigger):len(c.CallOptions.CreateJobTrigger)], opts...) + opts = append((*c.CallOptions).CreateJobTrigger[0:len((*c.CallOptions).CreateJobTrigger):len((*c.CallOptions).CreateJobTrigger)], opts...) var resp *dlppb.JobTrigger err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -859,9 +1147,7 @@ func (c *Client) CreateJobTrigger(ctx context.Context, req *dlppb.CreateJobTrigg return resp, nil } -// UpdateJobTrigger updates a job trigger. -// See https://cloud.google.com/dlp/docs/creating-job-triggers (at https://cloud.google.com/dlp/docs/creating-job-triggers) to learn more. -func (c *Client) UpdateJobTrigger(ctx context.Context, req *dlppb.UpdateJobTriggerRequest, opts ...gax.CallOption) (*dlppb.JobTrigger, error) { +func (c *gRPCClient) UpdateJobTrigger(ctx context.Context, req *dlppb.UpdateJobTriggerRequest, opts ...gax.CallOption) (*dlppb.JobTrigger, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -869,7 +1155,7 @@ func (c *Client) UpdateJobTrigger(ctx context.Context, req *dlppb.UpdateJobTrigg } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateJobTrigger[0:len(c.CallOptions.UpdateJobTrigger):len(c.CallOptions.UpdateJobTrigger)], opts...) + opts = append((*c.CallOptions).UpdateJobTrigger[0:len((*c.CallOptions).UpdateJobTrigger):len((*c.CallOptions).UpdateJobTrigger)], opts...) var resp *dlppb.JobTrigger err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -882,13 +1168,7 @@ func (c *Client) UpdateJobTrigger(ctx context.Context, req *dlppb.UpdateJobTrigg return resp, nil } -// HybridInspectJobTrigger inspect hybrid content and store findings to a trigger. The inspection -// will be processed asynchronously. To review the findings monitor the -// jobs within the trigger. -// Early access feature is in a pre-release state and might change or have -// limited support. For more information, see -// https://cloud.google.com/products#product-launch-stages (at https://cloud.google.com/products#product-launch-stages). -func (c *Client) HybridInspectJobTrigger(ctx context.Context, req *dlppb.HybridInspectJobTriggerRequest, opts ...gax.CallOption) (*dlppb.HybridInspectResponse, error) { +func (c *gRPCClient) HybridInspectJobTrigger(ctx context.Context, req *dlppb.HybridInspectJobTriggerRequest, opts ...gax.CallOption) (*dlppb.HybridInspectResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -896,7 +1176,7 @@ func (c *Client) HybridInspectJobTrigger(ctx context.Context, req *dlppb.HybridI } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.HybridInspectJobTrigger[0:len(c.CallOptions.HybridInspectJobTrigger):len(c.CallOptions.HybridInspectJobTrigger)], opts...) + opts = append((*c.CallOptions).HybridInspectJobTrigger[0:len((*c.CallOptions).HybridInspectJobTrigger):len((*c.CallOptions).HybridInspectJobTrigger)], opts...) var resp *dlppb.HybridInspectResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -909,9 +1189,7 @@ func (c *Client) HybridInspectJobTrigger(ctx context.Context, req *dlppb.HybridI return resp, nil } -// GetJobTrigger gets a job trigger. -// See https://cloud.google.com/dlp/docs/creating-job-triggers (at https://cloud.google.com/dlp/docs/creating-job-triggers) to learn more. -func (c *Client) GetJobTrigger(ctx context.Context, req *dlppb.GetJobTriggerRequest, opts ...gax.CallOption) (*dlppb.JobTrigger, error) { +func (c *gRPCClient) GetJobTrigger(ctx context.Context, req *dlppb.GetJobTriggerRequest, opts ...gax.CallOption) (*dlppb.JobTrigger, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -919,7 +1197,7 @@ func (c *Client) GetJobTrigger(ctx context.Context, req *dlppb.GetJobTriggerRequ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetJobTrigger[0:len(c.CallOptions.GetJobTrigger):len(c.CallOptions.GetJobTrigger)], opts...) + opts = append((*c.CallOptions).GetJobTrigger[0:len((*c.CallOptions).GetJobTrigger):len((*c.CallOptions).GetJobTrigger)], opts...) var resp *dlppb.JobTrigger err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -932,12 +1210,10 @@ func (c *Client) GetJobTrigger(ctx context.Context, req *dlppb.GetJobTriggerRequ return resp, nil } -// ListJobTriggers lists job triggers. -// See https://cloud.google.com/dlp/docs/creating-job-triggers (at https://cloud.google.com/dlp/docs/creating-job-triggers) to learn more. -func (c *Client) ListJobTriggers(ctx context.Context, req *dlppb.ListJobTriggersRequest, opts ...gax.CallOption) *JobTriggerIterator { +func (c *gRPCClient) ListJobTriggers(ctx context.Context, req *dlppb.ListJobTriggersRequest, opts ...gax.CallOption) *JobTriggerIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListJobTriggers[0:len(c.CallOptions.ListJobTriggers):len(c.CallOptions.ListJobTriggers)], opts...) + opts = append((*c.CallOptions).ListJobTriggers[0:len((*c.CallOptions).ListJobTriggers):len((*c.CallOptions).ListJobTriggers)], opts...) it := &JobTriggerIterator{} req = proto.Clone(req).(*dlppb.ListJobTriggersRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dlppb.JobTrigger, string, error) { @@ -974,9 +1250,7 @@ func (c *Client) ListJobTriggers(ctx context.Context, req *dlppb.ListJobTriggers return it } -// DeleteJobTrigger deletes a job trigger. -// See https://cloud.google.com/dlp/docs/creating-job-triggers (at https://cloud.google.com/dlp/docs/creating-job-triggers) to learn more. -func (c *Client) DeleteJobTrigger(ctx context.Context, req *dlppb.DeleteJobTriggerRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteJobTrigger(ctx context.Context, req *dlppb.DeleteJobTriggerRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -984,7 +1258,7 @@ func (c *Client) DeleteJobTrigger(ctx context.Context, req *dlppb.DeleteJobTrigg } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteJobTrigger[0:len(c.CallOptions.DeleteJobTrigger):len(c.CallOptions.DeleteJobTrigger)], opts...) + opts = append((*c.CallOptions).DeleteJobTrigger[0:len((*c.CallOptions).DeleteJobTrigger):len((*c.CallOptions).DeleteJobTrigger)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteJobTrigger(ctx, req, settings.GRPC...) @@ -993,9 +1267,7 @@ func (c *Client) DeleteJobTrigger(ctx context.Context, req *dlppb.DeleteJobTrigg return err } -// ActivateJobTrigger activate a job trigger. Causes the immediate execute of a trigger -// instead of waiting on the trigger event to occur. -func (c *Client) ActivateJobTrigger(ctx context.Context, req *dlppb.ActivateJobTriggerRequest, opts ...gax.CallOption) (*dlppb.DlpJob, error) { +func (c *gRPCClient) ActivateJobTrigger(ctx context.Context, req *dlppb.ActivateJobTriggerRequest, opts ...gax.CallOption) (*dlppb.DlpJob, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -1003,7 +1275,7 @@ func (c *Client) ActivateJobTrigger(ctx context.Context, req *dlppb.ActivateJobT } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ActivateJobTrigger[0:len(c.CallOptions.ActivateJobTrigger):len(c.CallOptions.ActivateJobTrigger)], opts...) + opts = append((*c.CallOptions).ActivateJobTrigger[0:len((*c.CallOptions).ActivateJobTrigger):len((*c.CallOptions).ActivateJobTrigger)], opts...) var resp *dlppb.DlpJob err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1016,14 +1288,7 @@ func (c *Client) ActivateJobTrigger(ctx context.Context, req *dlppb.ActivateJobT return resp, nil } -// CreateDlpJob creates a new job to inspect storage or calculate risk metrics. -// See https://cloud.google.com/dlp/docs/inspecting-storage (at https://cloud.google.com/dlp/docs/inspecting-storage) and -// https://cloud.google.com/dlp/docs/compute-risk-analysis (at https://cloud.google.com/dlp/docs/compute-risk-analysis) to learn more. -// -// When no InfoTypes or CustomInfoTypes are specified in inspect jobs, the -// system will automatically choose what detectors to run. By default this may -// be all types, but may change over time as detectors are updated. -func (c *Client) CreateDlpJob(ctx context.Context, req *dlppb.CreateDlpJobRequest, opts ...gax.CallOption) (*dlppb.DlpJob, error) { +func (c *gRPCClient) CreateDlpJob(ctx context.Context, req *dlppb.CreateDlpJobRequest, opts ...gax.CallOption) (*dlppb.DlpJob, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -1031,7 +1296,7 @@ func (c *Client) CreateDlpJob(ctx context.Context, req *dlppb.CreateDlpJobReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateDlpJob[0:len(c.CallOptions.CreateDlpJob):len(c.CallOptions.CreateDlpJob)], opts...) + opts = append((*c.CallOptions).CreateDlpJob[0:len((*c.CallOptions).CreateDlpJob):len((*c.CallOptions).CreateDlpJob)], opts...) var resp *dlppb.DlpJob err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1044,13 +1309,10 @@ func (c *Client) CreateDlpJob(ctx context.Context, req *dlppb.CreateDlpJobReques return resp, nil } -// ListDlpJobs lists DlpJobs that match the specified filter in the request. -// See https://cloud.google.com/dlp/docs/inspecting-storage (at https://cloud.google.com/dlp/docs/inspecting-storage) and -// https://cloud.google.com/dlp/docs/compute-risk-analysis (at https://cloud.google.com/dlp/docs/compute-risk-analysis) to learn more. -func (c *Client) ListDlpJobs(ctx context.Context, req *dlppb.ListDlpJobsRequest, opts ...gax.CallOption) *DlpJobIterator { +func (c *gRPCClient) ListDlpJobs(ctx context.Context, req *dlppb.ListDlpJobsRequest, opts ...gax.CallOption) *DlpJobIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDlpJobs[0:len(c.CallOptions.ListDlpJobs):len(c.CallOptions.ListDlpJobs)], opts...) + opts = append((*c.CallOptions).ListDlpJobs[0:len((*c.CallOptions).ListDlpJobs):len((*c.CallOptions).ListDlpJobs)], opts...) it := &DlpJobIterator{} req = proto.Clone(req).(*dlppb.ListDlpJobsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dlppb.DlpJob, string, error) { @@ -1087,10 +1349,7 @@ func (c *Client) ListDlpJobs(ctx context.Context, req *dlppb.ListDlpJobsRequest, return it } -// GetDlpJob gets the latest state of a long-running DlpJob. -// See https://cloud.google.com/dlp/docs/inspecting-storage (at https://cloud.google.com/dlp/docs/inspecting-storage) and -// https://cloud.google.com/dlp/docs/compute-risk-analysis (at https://cloud.google.com/dlp/docs/compute-risk-analysis) to learn more. -func (c *Client) GetDlpJob(ctx context.Context, req *dlppb.GetDlpJobRequest, opts ...gax.CallOption) (*dlppb.DlpJob, error) { +func (c *gRPCClient) GetDlpJob(ctx context.Context, req *dlppb.GetDlpJobRequest, opts ...gax.CallOption) (*dlppb.DlpJob, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -1098,7 +1357,7 @@ func (c *Client) GetDlpJob(ctx context.Context, req *dlppb.GetDlpJobRequest, opt } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetDlpJob[0:len(c.CallOptions.GetDlpJob):len(c.CallOptions.GetDlpJob)], opts...) + opts = append((*c.CallOptions).GetDlpJob[0:len((*c.CallOptions).GetDlpJob):len((*c.CallOptions).GetDlpJob)], opts...) var resp *dlppb.DlpJob err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1111,12 +1370,7 @@ func (c *Client) GetDlpJob(ctx context.Context, req *dlppb.GetDlpJobRequest, opt return resp, nil } -// DeleteDlpJob deletes a long-running DlpJob. This method indicates that the client is -// no longer interested in the DlpJob result. The job will be cancelled if -// possible. -// See https://cloud.google.com/dlp/docs/inspecting-storage (at https://cloud.google.com/dlp/docs/inspecting-storage) and -// https://cloud.google.com/dlp/docs/compute-risk-analysis (at https://cloud.google.com/dlp/docs/compute-risk-analysis) to learn more. -func (c *Client) DeleteDlpJob(ctx context.Context, req *dlppb.DeleteDlpJobRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteDlpJob(ctx context.Context, req *dlppb.DeleteDlpJobRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -1124,7 +1378,7 @@ func (c *Client) DeleteDlpJob(ctx context.Context, req *dlppb.DeleteDlpJobReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteDlpJob[0:len(c.CallOptions.DeleteDlpJob):len(c.CallOptions.DeleteDlpJob)], opts...) + opts = append((*c.CallOptions).DeleteDlpJob[0:len((*c.CallOptions).DeleteDlpJob):len((*c.CallOptions).DeleteDlpJob)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteDlpJob(ctx, req, settings.GRPC...) @@ -1133,12 +1387,7 @@ func (c *Client) DeleteDlpJob(ctx context.Context, req *dlppb.DeleteDlpJobReques return err } -// CancelDlpJob starts asynchronous cancellation on a long-running DlpJob. The server -// makes a best effort to cancel the DlpJob, but success is not -// guaranteed. -// See https://cloud.google.com/dlp/docs/inspecting-storage (at https://cloud.google.com/dlp/docs/inspecting-storage) and -// https://cloud.google.com/dlp/docs/compute-risk-analysis (at https://cloud.google.com/dlp/docs/compute-risk-analysis) to learn more. -func (c *Client) CancelDlpJob(ctx context.Context, req *dlppb.CancelDlpJobRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) CancelDlpJob(ctx context.Context, req *dlppb.CancelDlpJobRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -1146,7 +1395,7 @@ func (c *Client) CancelDlpJob(ctx context.Context, req *dlppb.CancelDlpJobReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CancelDlpJob[0:len(c.CallOptions.CancelDlpJob):len(c.CallOptions.CancelDlpJob)], opts...) + opts = append((*c.CallOptions).CancelDlpJob[0:len((*c.CallOptions).CancelDlpJob):len((*c.CallOptions).CancelDlpJob)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.CancelDlpJob(ctx, req, settings.GRPC...) @@ -1155,10 +1404,7 @@ func (c *Client) CancelDlpJob(ctx context.Context, req *dlppb.CancelDlpJobReques return err } -// CreateStoredInfoType creates a pre-built stored infoType to be used for inspection. -// See https://cloud.google.com/dlp/docs/creating-stored-infotypes (at https://cloud.google.com/dlp/docs/creating-stored-infotypes) to -// learn more. -func (c *Client) CreateStoredInfoType(ctx context.Context, req *dlppb.CreateStoredInfoTypeRequest, opts ...gax.CallOption) (*dlppb.StoredInfoType, error) { +func (c *gRPCClient) CreateStoredInfoType(ctx context.Context, req *dlppb.CreateStoredInfoTypeRequest, opts ...gax.CallOption) (*dlppb.StoredInfoType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -1166,7 +1412,7 @@ func (c *Client) CreateStoredInfoType(ctx context.Context, req *dlppb.CreateStor } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateStoredInfoType[0:len(c.CallOptions.CreateStoredInfoType):len(c.CallOptions.CreateStoredInfoType)], opts...) + opts = append((*c.CallOptions).CreateStoredInfoType[0:len((*c.CallOptions).CreateStoredInfoType):len((*c.CallOptions).CreateStoredInfoType)], opts...) var resp *dlppb.StoredInfoType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1179,11 +1425,7 @@ func (c *Client) CreateStoredInfoType(ctx context.Context, req *dlppb.CreateStor return resp, nil } -// UpdateStoredInfoType updates the stored infoType by creating a new version. The existing version -// will continue to be used until the new version is ready. -// See https://cloud.google.com/dlp/docs/creating-stored-infotypes (at https://cloud.google.com/dlp/docs/creating-stored-infotypes) to -// learn more. -func (c *Client) UpdateStoredInfoType(ctx context.Context, req *dlppb.UpdateStoredInfoTypeRequest, opts ...gax.CallOption) (*dlppb.StoredInfoType, error) { +func (c *gRPCClient) UpdateStoredInfoType(ctx context.Context, req *dlppb.UpdateStoredInfoTypeRequest, opts ...gax.CallOption) (*dlppb.StoredInfoType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -1191,7 +1433,7 @@ func (c *Client) UpdateStoredInfoType(ctx context.Context, req *dlppb.UpdateStor } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateStoredInfoType[0:len(c.CallOptions.UpdateStoredInfoType):len(c.CallOptions.UpdateStoredInfoType)], opts...) + opts = append((*c.CallOptions).UpdateStoredInfoType[0:len((*c.CallOptions).UpdateStoredInfoType):len((*c.CallOptions).UpdateStoredInfoType)], opts...) var resp *dlppb.StoredInfoType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1204,10 +1446,7 @@ func (c *Client) UpdateStoredInfoType(ctx context.Context, req *dlppb.UpdateStor return resp, nil } -// GetStoredInfoType gets a stored infoType. -// See https://cloud.google.com/dlp/docs/creating-stored-infotypes (at https://cloud.google.com/dlp/docs/creating-stored-infotypes) to -// learn more. -func (c *Client) GetStoredInfoType(ctx context.Context, req *dlppb.GetStoredInfoTypeRequest, opts ...gax.CallOption) (*dlppb.StoredInfoType, error) { +func (c *gRPCClient) GetStoredInfoType(ctx context.Context, req *dlppb.GetStoredInfoTypeRequest, opts ...gax.CallOption) (*dlppb.StoredInfoType, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -1215,7 +1454,7 @@ func (c *Client) GetStoredInfoType(ctx context.Context, req *dlppb.GetStoredInfo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetStoredInfoType[0:len(c.CallOptions.GetStoredInfoType):len(c.CallOptions.GetStoredInfoType)], opts...) + opts = append((*c.CallOptions).GetStoredInfoType[0:len((*c.CallOptions).GetStoredInfoType):len((*c.CallOptions).GetStoredInfoType)], opts...) var resp *dlppb.StoredInfoType err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1228,13 +1467,10 @@ func (c *Client) GetStoredInfoType(ctx context.Context, req *dlppb.GetStoredInfo return resp, nil } -// ListStoredInfoTypes lists stored infoTypes. -// See https://cloud.google.com/dlp/docs/creating-stored-infotypes (at https://cloud.google.com/dlp/docs/creating-stored-infotypes) to -// learn more. -func (c *Client) ListStoredInfoTypes(ctx context.Context, req *dlppb.ListStoredInfoTypesRequest, opts ...gax.CallOption) *StoredInfoTypeIterator { +func (c *gRPCClient) ListStoredInfoTypes(ctx context.Context, req *dlppb.ListStoredInfoTypesRequest, opts ...gax.CallOption) *StoredInfoTypeIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListStoredInfoTypes[0:len(c.CallOptions.ListStoredInfoTypes):len(c.CallOptions.ListStoredInfoTypes)], opts...) + opts = append((*c.CallOptions).ListStoredInfoTypes[0:len((*c.CallOptions).ListStoredInfoTypes):len((*c.CallOptions).ListStoredInfoTypes)], opts...) it := &StoredInfoTypeIterator{} req = proto.Clone(req).(*dlppb.ListStoredInfoTypesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dlppb.StoredInfoType, string, error) { @@ -1271,10 +1507,7 @@ func (c *Client) ListStoredInfoTypes(ctx context.Context, req *dlppb.ListStoredI return it } -// DeleteStoredInfoType deletes a stored infoType. -// See https://cloud.google.com/dlp/docs/creating-stored-infotypes (at https://cloud.google.com/dlp/docs/creating-stored-infotypes) to -// learn more. -func (c *Client) DeleteStoredInfoType(ctx context.Context, req *dlppb.DeleteStoredInfoTypeRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteStoredInfoType(ctx context.Context, req *dlppb.DeleteStoredInfoTypeRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -1282,7 +1515,7 @@ func (c *Client) DeleteStoredInfoType(ctx context.Context, req *dlppb.DeleteStor } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteStoredInfoType[0:len(c.CallOptions.DeleteStoredInfoType):len(c.CallOptions.DeleteStoredInfoType)], opts...) + opts = append((*c.CallOptions).DeleteStoredInfoType[0:len((*c.CallOptions).DeleteStoredInfoType):len((*c.CallOptions).DeleteStoredInfoType)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteStoredInfoType(ctx, req, settings.GRPC...) @@ -1291,13 +1524,7 @@ func (c *Client) DeleteStoredInfoType(ctx context.Context, req *dlppb.DeleteStor return err } -// HybridInspectDlpJob inspect hybrid content and store findings to a job. -// To review the findings inspect the job. Inspection will occur -// asynchronously. -// Early access feature is in a pre-release state and might change or have -// limited support. For more information, see -// https://cloud.google.com/products#product-launch-stages (at https://cloud.google.com/products#product-launch-stages). -func (c *Client) HybridInspectDlpJob(ctx context.Context, req *dlppb.HybridInspectDlpJobRequest, opts ...gax.CallOption) (*dlppb.HybridInspectResponse, error) { +func (c *gRPCClient) HybridInspectDlpJob(ctx context.Context, req *dlppb.HybridInspectDlpJobRequest, opts ...gax.CallOption) (*dlppb.HybridInspectResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -1305,7 +1532,7 @@ func (c *Client) HybridInspectDlpJob(ctx context.Context, req *dlppb.HybridInspe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.HybridInspectDlpJob[0:len(c.CallOptions.HybridInspectDlpJob):len(c.CallOptions.HybridInspectDlpJob)], opts...) + opts = append((*c.CallOptions).HybridInspectDlpJob[0:len((*c.CallOptions).HybridInspectDlpJob):len((*c.CallOptions).HybridInspectDlpJob)], opts...) var resp *dlppb.HybridInspectResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1318,12 +1545,7 @@ func (c *Client) HybridInspectDlpJob(ctx context.Context, req *dlppb.HybridInspe return resp, nil } -// FinishDlpJob finish a running hybrid DlpJob. Triggers the finalization steps and running -// of any enabled actions that have not yet run. -// Early access feature is in a pre-release state and might change or have -// limited support. For more information, see -// https://cloud.google.com/products#product-launch-stages (at https://cloud.google.com/products#product-launch-stages). -func (c *Client) FinishDlpJob(ctx context.Context, req *dlppb.FinishDlpJobRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) FinishDlpJob(ctx context.Context, req *dlppb.FinishDlpJobRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 300000*time.Millisecond) defer cancel() @@ -1331,7 +1553,7 @@ func (c *Client) FinishDlpJob(ctx context.Context, req *dlppb.FinishDlpJobReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.FinishDlpJob[0:len(c.CallOptions.FinishDlpJob):len(c.CallOptions.FinishDlpJob)], opts...) + opts = append((*c.CallOptions).FinishDlpJob[0:len((*c.CallOptions).FinishDlpJob):len((*c.CallOptions).FinishDlpJob)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.FinishDlpJob(ctx, req, settings.GRPC...) diff --git a/dlp/apiv2/dlp_client_example_test.go b/dlp/apiv2/dlp_client_example_test.go index 3965f208621f..e26f1b00af89 100644 --- a/dlp/apiv2/dlp_client_example_test.go +++ b/dlp/apiv2/dlp_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_InspectContent() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.InspectContentRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleClient_InspectContent() { } func ExampleClient_RedactImage() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.RedactImageRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleClient_RedactImage() { } func ExampleClient_DeidentifyContent() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.DeidentifyContentRequest{ // TODO: Fill request struct fields. @@ -95,13 +94,12 @@ func ExampleClient_DeidentifyContent() { } func ExampleClient_ReidentifyContent() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.ReidentifyContentRequest{ // TODO: Fill request struct fields. @@ -115,13 +113,12 @@ func ExampleClient_ReidentifyContent() { } func ExampleClient_ListInfoTypes() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.ListInfoTypesRequest{ // TODO: Fill request struct fields. @@ -135,13 +132,12 @@ func ExampleClient_ListInfoTypes() { } func ExampleClient_CreateInspectTemplate() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.CreateInspectTemplateRequest{ // TODO: Fill request struct fields. @@ -155,13 +151,12 @@ func ExampleClient_CreateInspectTemplate() { } func ExampleClient_UpdateInspectTemplate() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.UpdateInspectTemplateRequest{ // TODO: Fill request struct fields. @@ -175,13 +170,12 @@ func ExampleClient_UpdateInspectTemplate() { } func ExampleClient_GetInspectTemplate() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.GetInspectTemplateRequest{ // TODO: Fill request struct fields. @@ -195,14 +189,12 @@ func ExampleClient_GetInspectTemplate() { } func ExampleClient_ListInspectTemplates() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.ListInspectTemplatesRequest{ // TODO: Fill request struct fields. @@ -227,6 +219,7 @@ func ExampleClient_DeleteInspectTemplate() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.DeleteInspectTemplateRequest{ // TODO: Fill request struct fields. @@ -238,13 +231,12 @@ func ExampleClient_DeleteInspectTemplate() { } func ExampleClient_CreateDeidentifyTemplate() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.CreateDeidentifyTemplateRequest{ // TODO: Fill request struct fields. @@ -258,13 +250,12 @@ func ExampleClient_CreateDeidentifyTemplate() { } func ExampleClient_UpdateDeidentifyTemplate() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.UpdateDeidentifyTemplateRequest{ // TODO: Fill request struct fields. @@ -278,13 +269,12 @@ func ExampleClient_UpdateDeidentifyTemplate() { } func ExampleClient_GetDeidentifyTemplate() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.GetDeidentifyTemplateRequest{ // TODO: Fill request struct fields. @@ -298,14 +288,12 @@ func ExampleClient_GetDeidentifyTemplate() { } func ExampleClient_ListDeidentifyTemplates() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.ListDeidentifyTemplatesRequest{ // TODO: Fill request struct fields. @@ -330,6 +318,7 @@ func ExampleClient_DeleteDeidentifyTemplate() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.DeleteDeidentifyTemplateRequest{ // TODO: Fill request struct fields. @@ -341,13 +330,12 @@ func ExampleClient_DeleteDeidentifyTemplate() { } func ExampleClient_CreateJobTrigger() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.CreateJobTriggerRequest{ // TODO: Fill request struct fields. @@ -361,13 +349,12 @@ func ExampleClient_CreateJobTrigger() { } func ExampleClient_UpdateJobTrigger() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.UpdateJobTriggerRequest{ // TODO: Fill request struct fields. @@ -381,13 +368,12 @@ func ExampleClient_UpdateJobTrigger() { } func ExampleClient_HybridInspectJobTrigger() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.HybridInspectJobTriggerRequest{ // TODO: Fill request struct fields. @@ -401,13 +387,12 @@ func ExampleClient_HybridInspectJobTrigger() { } func ExampleClient_GetJobTrigger() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.GetJobTriggerRequest{ // TODO: Fill request struct fields. @@ -421,14 +406,12 @@ func ExampleClient_GetJobTrigger() { } func ExampleClient_ListJobTriggers() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.ListJobTriggersRequest{ // TODO: Fill request struct fields. @@ -453,6 +436,7 @@ func ExampleClient_DeleteJobTrigger() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.DeleteJobTriggerRequest{ // TODO: Fill request struct fields. @@ -464,13 +448,12 @@ func ExampleClient_DeleteJobTrigger() { } func ExampleClient_ActivateJobTrigger() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.ActivateJobTriggerRequest{ // TODO: Fill request struct fields. @@ -484,13 +467,12 @@ func ExampleClient_ActivateJobTrigger() { } func ExampleClient_CreateDlpJob() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.CreateDlpJobRequest{ // TODO: Fill request struct fields. @@ -504,14 +486,12 @@ func ExampleClient_CreateDlpJob() { } func ExampleClient_ListDlpJobs() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.ListDlpJobsRequest{ // TODO: Fill request struct fields. @@ -531,13 +511,12 @@ func ExampleClient_ListDlpJobs() { } func ExampleClient_GetDlpJob() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.GetDlpJobRequest{ // TODO: Fill request struct fields. @@ -556,6 +535,7 @@ func ExampleClient_DeleteDlpJob() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.DeleteDlpJobRequest{ // TODO: Fill request struct fields. @@ -572,6 +552,7 @@ func ExampleClient_CancelDlpJob() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.CancelDlpJobRequest{ // TODO: Fill request struct fields. @@ -583,13 +564,12 @@ func ExampleClient_CancelDlpJob() { } func ExampleClient_CreateStoredInfoType() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.CreateStoredInfoTypeRequest{ // TODO: Fill request struct fields. @@ -603,13 +583,12 @@ func ExampleClient_CreateStoredInfoType() { } func ExampleClient_UpdateStoredInfoType() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.UpdateStoredInfoTypeRequest{ // TODO: Fill request struct fields. @@ -623,13 +602,12 @@ func ExampleClient_UpdateStoredInfoType() { } func ExampleClient_GetStoredInfoType() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.GetStoredInfoTypeRequest{ // TODO: Fill request struct fields. @@ -643,14 +621,12 @@ func ExampleClient_GetStoredInfoType() { } func ExampleClient_ListStoredInfoTypes() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.ListStoredInfoTypesRequest{ // TODO: Fill request struct fields. @@ -675,6 +651,7 @@ func ExampleClient_DeleteStoredInfoType() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.DeleteStoredInfoTypeRequest{ // TODO: Fill request struct fields. @@ -686,13 +663,12 @@ func ExampleClient_DeleteStoredInfoType() { } func ExampleClient_HybridInspectDlpJob() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.HybridInspectDlpJobRequest{ // TODO: Fill request struct fields. @@ -711,6 +687,7 @@ func ExampleClient_FinishDlpJob() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.FinishDlpJobRequest{ // TODO: Fill request struct fields. diff --git a/dlp/apiv2/doc.go b/dlp/apiv2/doc.go index 3aba6ff39bff..a813a589cda3 100644 --- a/dlp/apiv2/doc.go +++ b/dlp/apiv2/doc.go @@ -30,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package dlp // import "cloud.google.com/go/dlp/apiv2" import ( @@ -50,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/documentai/apiv1/doc.go b/documentai/apiv1/doc.go index 001269234a09..379fdb6a5034 100644 --- a/documentai/apiv1/doc.go +++ b/documentai/apiv1/doc.go @@ -21,6 +21,8 @@ // semi-structured documents using state-of-the-art Google AI such as natural // language, computer vision, translation, and AutoML. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -30,7 +32,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package documentai // import "cloud.google.com/go/documentai/apiv1" import ( @@ -50,7 +52,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/documentai/apiv1/document_processor_client.go b/documentai/apiv1/document_processor_client.go index d62634b2ac20..a225594646c9 100644 --- a/documentai/apiv1/document_processor_client.go +++ b/documentai/apiv1/document_processor_client.go @@ -45,7 +45,7 @@ type DocumentProcessorCallOptions struct { ReviewDocument []gax.CallOption } -func defaultDocumentProcessorClientOptions() []option.ClientOption { +func defaultDocumentProcessorGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("documentai.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("documentai.mtls.googleapis.com:443"), @@ -98,40 +98,123 @@ func defaultDocumentProcessorCallOptions() *DocumentProcessorCallOptions { } } +// internalDocumentProcessorClient is an interface that defines the methods availaible from Cloud Document AI API. +type internalDocumentProcessorClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ProcessDocument(context.Context, *documentaipb.ProcessRequest, ...gax.CallOption) (*documentaipb.ProcessResponse, error) + BatchProcessDocuments(context.Context, *documentaipb.BatchProcessRequest, ...gax.CallOption) (*BatchProcessDocumentsOperation, error) + BatchProcessDocumentsOperation(name string) *BatchProcessDocumentsOperation + ReviewDocument(context.Context, *documentaipb.ReviewDocumentRequest, ...gax.CallOption) (*ReviewDocumentOperation, error) + ReviewDocumentOperation(name string) *ReviewDocumentOperation +} + // DocumentProcessorClient is a client for interacting with Cloud Document AI API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service to call Cloud DocumentAI to process documents according to the +// processor’s definition. Processors are built using state-of-the-art Google +// AI such as natural language, computer vision, and translation to extract +// structured information from unstructured or semi-structured documents. type DocumentProcessorClient struct { + // The internal transport-dependent client. + internalClient internalDocumentProcessorClient + + // The call options for this service. + CallOptions *DocumentProcessorCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *DocumentProcessorClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *DocumentProcessorClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *DocumentProcessorClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ProcessDocument processes a single document. +func (c *DocumentProcessorClient) ProcessDocument(ctx context.Context, req *documentaipb.ProcessRequest, opts ...gax.CallOption) (*documentaipb.ProcessResponse, error) { + return c.internalClient.ProcessDocument(ctx, req, opts...) +} + +// BatchProcessDocuments lRO endpoint to batch process many documents. The output is written +// to Cloud Storage as JSON in the [Document] format. +func (c *DocumentProcessorClient) BatchProcessDocuments(ctx context.Context, req *documentaipb.BatchProcessRequest, opts ...gax.CallOption) (*BatchProcessDocumentsOperation, error) { + return c.internalClient.BatchProcessDocuments(ctx, req, opts...) +} + +// BatchProcessDocumentsOperation returns a new BatchProcessDocumentsOperation from a given name. +// The name must be that of a previously created BatchProcessDocumentsOperation, possibly from a different process. +func (c *DocumentProcessorClient) BatchProcessDocumentsOperation(name string) *BatchProcessDocumentsOperation { + return c.internalClient.BatchProcessDocumentsOperation(name) +} + +// ReviewDocument send a document for Human Review. The input document should be processed by +// the specified processor. +func (c *DocumentProcessorClient) ReviewDocument(ctx context.Context, req *documentaipb.ReviewDocumentRequest, opts ...gax.CallOption) (*ReviewDocumentOperation, error) { + return c.internalClient.ReviewDocument(ctx, req, opts...) +} + +// ReviewDocumentOperation returns a new ReviewDocumentOperation from a given name. +// The name must be that of a previously created ReviewDocumentOperation, possibly from a different process. +func (c *DocumentProcessorClient) ReviewDocumentOperation(name string) *ReviewDocumentOperation { + return c.internalClient.ReviewDocumentOperation(name) +} + +// documentProcessorGRPCClient is a client for interacting with Cloud Document AI API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type documentProcessorGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing DocumentProcessorClient + CallOptions **DocumentProcessorCallOptions + // The gRPC API client. documentProcessorClient documentaipb.DocumentProcessorServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *DocumentProcessorCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewDocumentProcessorClient creates a new document processor service client. +// NewDocumentProcessorClient creates a new document processor service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service to call Cloud DocumentAI to process documents according to the // processor’s definition. Processors are built using state-of-the-art Google // AI such as natural language, computer vision, and translation to extract // structured information from unstructured or semi-structured documents. func NewDocumentProcessorClient(ctx context.Context, opts ...option.ClientOption) (*DocumentProcessorClient, error) { - clientOpts := defaultDocumentProcessorClientOptions() - + clientOpts := defaultDocumentProcessorGRPCClientOptions() if newDocumentProcessorClientHook != nil { hookOpts, err := newDocumentProcessorClientHook(ctx, clientHookParams{}) if err != nil { @@ -149,16 +232,19 @@ func NewDocumentProcessorClient(ctx context.Context, opts ...option.ClientOption if err != nil { return nil, err } - c := &DocumentProcessorClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultDocumentProcessorCallOptions(), + client := DocumentProcessorClient{CallOptions: defaultDocumentProcessorCallOptions()} + c := &documentProcessorGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, documentProcessorClient: documentaipb.NewDocumentProcessorServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -168,33 +254,33 @@ func NewDocumentProcessorClient(ctx context.Context, opts ...option.ClientOption // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *DocumentProcessorClient) Connection() *grpc.ClientConn { +func (c *documentProcessorGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *DocumentProcessorClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *DocumentProcessorClient) setGoogleClientInfo(keyval ...string) { +func (c *documentProcessorGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ProcessDocument processes a single document. -func (c *DocumentProcessorClient) ProcessDocument(ctx context.Context, req *documentaipb.ProcessRequest, opts ...gax.CallOption) (*documentaipb.ProcessResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *documentProcessorGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *documentProcessorGRPCClient) ProcessDocument(ctx context.Context, req *documentaipb.ProcessRequest, opts ...gax.CallOption) (*documentaipb.ProcessResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -202,7 +288,7 @@ func (c *DocumentProcessorClient) ProcessDocument(ctx context.Context, req *docu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ProcessDocument[0:len(c.CallOptions.ProcessDocument):len(c.CallOptions.ProcessDocument)], opts...) + opts = append((*c.CallOptions).ProcessDocument[0:len((*c.CallOptions).ProcessDocument):len((*c.CallOptions).ProcessDocument)], opts...) var resp *documentaipb.ProcessResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -215,9 +301,7 @@ func (c *DocumentProcessorClient) ProcessDocument(ctx context.Context, req *docu return resp, nil } -// BatchProcessDocuments lRO endpoint to batch process many documents. The output is written -// to Cloud Storage as JSON in the [Document] format. -func (c *DocumentProcessorClient) BatchProcessDocuments(ctx context.Context, req *documentaipb.BatchProcessRequest, opts ...gax.CallOption) (*BatchProcessDocumentsOperation, error) { +func (c *documentProcessorGRPCClient) BatchProcessDocuments(ctx context.Context, req *documentaipb.BatchProcessRequest, opts ...gax.CallOption) (*BatchProcessDocumentsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -225,7 +309,7 @@ func (c *DocumentProcessorClient) BatchProcessDocuments(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchProcessDocuments[0:len(c.CallOptions.BatchProcessDocuments):len(c.CallOptions.BatchProcessDocuments)], opts...) + opts = append((*c.CallOptions).BatchProcessDocuments[0:len((*c.CallOptions).BatchProcessDocuments):len((*c.CallOptions).BatchProcessDocuments)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -236,13 +320,11 @@ func (c *DocumentProcessorClient) BatchProcessDocuments(ctx context.Context, req return nil, err } return &BatchProcessDocumentsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ReviewDocument send a document for Human Review. The input document should be processed by -// the specified processor. -func (c *DocumentProcessorClient) ReviewDocument(ctx context.Context, req *documentaipb.ReviewDocumentRequest, opts ...gax.CallOption) (*ReviewDocumentOperation, error) { +func (c *documentProcessorGRPCClient) ReviewDocument(ctx context.Context, req *documentaipb.ReviewDocumentRequest, opts ...gax.CallOption) (*ReviewDocumentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -250,7 +332,7 @@ func (c *DocumentProcessorClient) ReviewDocument(ctx context.Context, req *docum } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "human_review_config", url.QueryEscape(req.GetHumanReviewConfig()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ReviewDocument[0:len(c.CallOptions.ReviewDocument):len(c.CallOptions.ReviewDocument)], opts...) + opts = append((*c.CallOptions).ReviewDocument[0:len((*c.CallOptions).ReviewDocument):len((*c.CallOptions).ReviewDocument)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -261,7 +343,7 @@ func (c *DocumentProcessorClient) ReviewDocument(ctx context.Context, req *docum return nil, err } return &ReviewDocumentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -272,9 +354,9 @@ type BatchProcessDocumentsOperation struct { // BatchProcessDocumentsOperation returns a new BatchProcessDocumentsOperation from a given name. // The name must be that of a previously created BatchProcessDocumentsOperation, possibly from a different process. -func (c *DocumentProcessorClient) BatchProcessDocumentsOperation(name string) *BatchProcessDocumentsOperation { +func (c *documentProcessorGRPCClient) BatchProcessDocumentsOperation(name string) *BatchProcessDocumentsOperation { return &BatchProcessDocumentsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -341,9 +423,9 @@ type ReviewDocumentOperation struct { // ReviewDocumentOperation returns a new ReviewDocumentOperation from a given name. // The name must be that of a previously created ReviewDocumentOperation, possibly from a different process. -func (c *DocumentProcessorClient) ReviewDocumentOperation(name string) *ReviewDocumentOperation { +func (c *documentProcessorGRPCClient) ReviewDocumentOperation(name string) *ReviewDocumentOperation { return &ReviewDocumentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/documentai/apiv1/document_processor_client_example_test.go b/documentai/apiv1/document_processor_client_example_test.go index 54aa165f0329..dbe14526f674 100644 --- a/documentai/apiv1/document_processor_client_example_test.go +++ b/documentai/apiv1/document_processor_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewDocumentProcessorClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleDocumentProcessorClient_ProcessDocument() { - // import documentaipb "google.golang.org/genproto/googleapis/cloud/documentai/v1" - ctx := context.Background() c, err := documentai.NewDocumentProcessorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &documentaipb.ProcessRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleDocumentProcessorClient_ProcessDocument() { } func ExampleDocumentProcessorClient_BatchProcessDocuments() { - // import documentaipb "google.golang.org/genproto/googleapis/cloud/documentai/v1" - ctx := context.Background() c, err := documentai.NewDocumentProcessorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &documentaipb.BatchProcessRequest{ // TODO: Fill request struct fields. @@ -79,13 +79,12 @@ func ExampleDocumentProcessorClient_BatchProcessDocuments() { } func ExampleDocumentProcessorClient_ReviewDocument() { - // import documentaipb "google.golang.org/genproto/googleapis/cloud/documentai/v1" - ctx := context.Background() c, err := documentai.NewDocumentProcessorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &documentaipb.ReviewDocumentRequest{ // TODO: Fill request struct fields. diff --git a/documentai/apiv1beta3/doc.go b/documentai/apiv1beta3/doc.go index feb76d5bdb11..27f29c65a65a 100644 --- a/documentai/apiv1beta3/doc.go +++ b/documentai/apiv1beta3/doc.go @@ -21,6 +21,8 @@ // semi-structured documents using state-of-the-art Google AI such as natural // language, computer vision, translation, and AutoML. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -30,7 +32,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package documentai // import "cloud.google.com/go/documentai/apiv1beta3" import ( @@ -50,7 +52,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/documentai/apiv1beta3/document_processor_client.go b/documentai/apiv1beta3/document_processor_client.go index 2a595b7ec947..a7f81454fee6 100644 --- a/documentai/apiv1beta3/document_processor_client.go +++ b/documentai/apiv1beta3/document_processor_client.go @@ -45,7 +45,7 @@ type DocumentProcessorCallOptions struct { ReviewDocument []gax.CallOption } -func defaultDocumentProcessorClientOptions() []option.ClientOption { +func defaultDocumentProcessorGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("documentai.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("documentai.mtls.googleapis.com:443"), @@ -98,40 +98,123 @@ func defaultDocumentProcessorCallOptions() *DocumentProcessorCallOptions { } } +// internalDocumentProcessorClient is an interface that defines the methods availaible from Cloud Document AI API. +type internalDocumentProcessorClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ProcessDocument(context.Context, *documentaipb.ProcessRequest, ...gax.CallOption) (*documentaipb.ProcessResponse, error) + BatchProcessDocuments(context.Context, *documentaipb.BatchProcessRequest, ...gax.CallOption) (*BatchProcessDocumentsOperation, error) + BatchProcessDocumentsOperation(name string) *BatchProcessDocumentsOperation + ReviewDocument(context.Context, *documentaipb.ReviewDocumentRequest, ...gax.CallOption) (*ReviewDocumentOperation, error) + ReviewDocumentOperation(name string) *ReviewDocumentOperation +} + // DocumentProcessorClient is a client for interacting with Cloud Document AI API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service to call Cloud DocumentAI to process documents according to the +// processor’s definition. Processors are built using state-of-the-art Google +// AI such as natural language, computer vision, and translation to extract +// structured information from unstructured or semi-structured documents. type DocumentProcessorClient struct { + // The internal transport-dependent client. + internalClient internalDocumentProcessorClient + + // The call options for this service. + CallOptions *DocumentProcessorCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *DocumentProcessorClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *DocumentProcessorClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *DocumentProcessorClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ProcessDocument processes a single document. +func (c *DocumentProcessorClient) ProcessDocument(ctx context.Context, req *documentaipb.ProcessRequest, opts ...gax.CallOption) (*documentaipb.ProcessResponse, error) { + return c.internalClient.ProcessDocument(ctx, req, opts...) +} + +// BatchProcessDocuments lRO endpoint to batch process many documents. The output is written +// to Cloud Storage as JSON in the [Document] format. +func (c *DocumentProcessorClient) BatchProcessDocuments(ctx context.Context, req *documentaipb.BatchProcessRequest, opts ...gax.CallOption) (*BatchProcessDocumentsOperation, error) { + return c.internalClient.BatchProcessDocuments(ctx, req, opts...) +} + +// BatchProcessDocumentsOperation returns a new BatchProcessDocumentsOperation from a given name. +// The name must be that of a previously created BatchProcessDocumentsOperation, possibly from a different process. +func (c *DocumentProcessorClient) BatchProcessDocumentsOperation(name string) *BatchProcessDocumentsOperation { + return c.internalClient.BatchProcessDocumentsOperation(name) +} + +// ReviewDocument send a document for Human Review. The input document should be processed by +// the specified processor. +func (c *DocumentProcessorClient) ReviewDocument(ctx context.Context, req *documentaipb.ReviewDocumentRequest, opts ...gax.CallOption) (*ReviewDocumentOperation, error) { + return c.internalClient.ReviewDocument(ctx, req, opts...) +} + +// ReviewDocumentOperation returns a new ReviewDocumentOperation from a given name. +// The name must be that of a previously created ReviewDocumentOperation, possibly from a different process. +func (c *DocumentProcessorClient) ReviewDocumentOperation(name string) *ReviewDocumentOperation { + return c.internalClient.ReviewDocumentOperation(name) +} + +// documentProcessorGRPCClient is a client for interacting with Cloud Document AI API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type documentProcessorGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing DocumentProcessorClient + CallOptions **DocumentProcessorCallOptions + // The gRPC API client. documentProcessorClient documentaipb.DocumentProcessorServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *DocumentProcessorCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewDocumentProcessorClient creates a new document processor service client. +// NewDocumentProcessorClient creates a new document processor service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service to call Cloud DocumentAI to process documents according to the // processor’s definition. Processors are built using state-of-the-art Google // AI such as natural language, computer vision, and translation to extract // structured information from unstructured or semi-structured documents. func NewDocumentProcessorClient(ctx context.Context, opts ...option.ClientOption) (*DocumentProcessorClient, error) { - clientOpts := defaultDocumentProcessorClientOptions() - + clientOpts := defaultDocumentProcessorGRPCClientOptions() if newDocumentProcessorClientHook != nil { hookOpts, err := newDocumentProcessorClientHook(ctx, clientHookParams{}) if err != nil { @@ -149,16 +232,19 @@ func NewDocumentProcessorClient(ctx context.Context, opts ...option.ClientOption if err != nil { return nil, err } - c := &DocumentProcessorClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultDocumentProcessorCallOptions(), + client := DocumentProcessorClient{CallOptions: defaultDocumentProcessorCallOptions()} + c := &documentProcessorGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, documentProcessorClient: documentaipb.NewDocumentProcessorServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -168,33 +254,33 @@ func NewDocumentProcessorClient(ctx context.Context, opts ...option.ClientOption // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *DocumentProcessorClient) Connection() *grpc.ClientConn { +func (c *documentProcessorGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *DocumentProcessorClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *DocumentProcessorClient) setGoogleClientInfo(keyval ...string) { +func (c *documentProcessorGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ProcessDocument processes a single document. -func (c *DocumentProcessorClient) ProcessDocument(ctx context.Context, req *documentaipb.ProcessRequest, opts ...gax.CallOption) (*documentaipb.ProcessResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *documentProcessorGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *documentProcessorGRPCClient) ProcessDocument(ctx context.Context, req *documentaipb.ProcessRequest, opts ...gax.CallOption) (*documentaipb.ProcessResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -202,7 +288,7 @@ func (c *DocumentProcessorClient) ProcessDocument(ctx context.Context, req *docu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ProcessDocument[0:len(c.CallOptions.ProcessDocument):len(c.CallOptions.ProcessDocument)], opts...) + opts = append((*c.CallOptions).ProcessDocument[0:len((*c.CallOptions).ProcessDocument):len((*c.CallOptions).ProcessDocument)], opts...) var resp *documentaipb.ProcessResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -215,9 +301,7 @@ func (c *DocumentProcessorClient) ProcessDocument(ctx context.Context, req *docu return resp, nil } -// BatchProcessDocuments lRO endpoint to batch process many documents. The output is written -// to Cloud Storage as JSON in the [Document] format. -func (c *DocumentProcessorClient) BatchProcessDocuments(ctx context.Context, req *documentaipb.BatchProcessRequest, opts ...gax.CallOption) (*BatchProcessDocumentsOperation, error) { +func (c *documentProcessorGRPCClient) BatchProcessDocuments(ctx context.Context, req *documentaipb.BatchProcessRequest, opts ...gax.CallOption) (*BatchProcessDocumentsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -225,7 +309,7 @@ func (c *DocumentProcessorClient) BatchProcessDocuments(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchProcessDocuments[0:len(c.CallOptions.BatchProcessDocuments):len(c.CallOptions.BatchProcessDocuments)], opts...) + opts = append((*c.CallOptions).BatchProcessDocuments[0:len((*c.CallOptions).BatchProcessDocuments):len((*c.CallOptions).BatchProcessDocuments)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -236,13 +320,11 @@ func (c *DocumentProcessorClient) BatchProcessDocuments(ctx context.Context, req return nil, err } return &BatchProcessDocumentsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ReviewDocument send a document for Human Review. The input document should be processed by -// the specified processor. -func (c *DocumentProcessorClient) ReviewDocument(ctx context.Context, req *documentaipb.ReviewDocumentRequest, opts ...gax.CallOption) (*ReviewDocumentOperation, error) { +func (c *documentProcessorGRPCClient) ReviewDocument(ctx context.Context, req *documentaipb.ReviewDocumentRequest, opts ...gax.CallOption) (*ReviewDocumentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -250,7 +332,7 @@ func (c *DocumentProcessorClient) ReviewDocument(ctx context.Context, req *docum } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "human_review_config", url.QueryEscape(req.GetHumanReviewConfig()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ReviewDocument[0:len(c.CallOptions.ReviewDocument):len(c.CallOptions.ReviewDocument)], opts...) + opts = append((*c.CallOptions).ReviewDocument[0:len((*c.CallOptions).ReviewDocument):len((*c.CallOptions).ReviewDocument)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -261,7 +343,7 @@ func (c *DocumentProcessorClient) ReviewDocument(ctx context.Context, req *docum return nil, err } return &ReviewDocumentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -272,9 +354,9 @@ type BatchProcessDocumentsOperation struct { // BatchProcessDocumentsOperation returns a new BatchProcessDocumentsOperation from a given name. // The name must be that of a previously created BatchProcessDocumentsOperation, possibly from a different process. -func (c *DocumentProcessorClient) BatchProcessDocumentsOperation(name string) *BatchProcessDocumentsOperation { +func (c *documentProcessorGRPCClient) BatchProcessDocumentsOperation(name string) *BatchProcessDocumentsOperation { return &BatchProcessDocumentsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -341,9 +423,9 @@ type ReviewDocumentOperation struct { // ReviewDocumentOperation returns a new ReviewDocumentOperation from a given name. // The name must be that of a previously created ReviewDocumentOperation, possibly from a different process. -func (c *DocumentProcessorClient) ReviewDocumentOperation(name string) *ReviewDocumentOperation { +func (c *documentProcessorGRPCClient) ReviewDocumentOperation(name string) *ReviewDocumentOperation { return &ReviewDocumentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/documentai/apiv1beta3/document_processor_client_example_test.go b/documentai/apiv1beta3/document_processor_client_example_test.go index ccddcfc32c64..381bc2e1a913 100644 --- a/documentai/apiv1beta3/document_processor_client_example_test.go +++ b/documentai/apiv1beta3/document_processor_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewDocumentProcessorClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleDocumentProcessorClient_ProcessDocument() { - // import documentaipb "google.golang.org/genproto/googleapis/cloud/documentai/v1beta3" - ctx := context.Background() c, err := documentai.NewDocumentProcessorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &documentaipb.ProcessRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleDocumentProcessorClient_ProcessDocument() { } func ExampleDocumentProcessorClient_BatchProcessDocuments() { - // import documentaipb "google.golang.org/genproto/googleapis/cloud/documentai/v1beta3" - ctx := context.Background() c, err := documentai.NewDocumentProcessorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &documentaipb.BatchProcessRequest{ // TODO: Fill request struct fields. @@ -79,13 +79,12 @@ func ExampleDocumentProcessorClient_BatchProcessDocuments() { } func ExampleDocumentProcessorClient_ReviewDocument() { - // import documentaipb "google.golang.org/genproto/googleapis/cloud/documentai/v1beta3" - ctx := context.Background() c, err := documentai.NewDocumentProcessorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &documentaipb.ReviewDocumentRequest{ // TODO: Fill request struct fields. diff --git a/domains/apiv1beta1/doc.go b/domains/apiv1beta1/doc.go index a2c6670971b4..3c916fa88353 100644 --- a/domains/apiv1beta1/doc.go +++ b/domains/apiv1beta1/doc.go @@ -19,6 +19,8 @@ // // Enables management and configuration of domain names. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -28,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package domains // import "cloud.google.com/go/domains/apiv1beta1" import ( @@ -48,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/domains/apiv1beta1/domains_client.go b/domains/apiv1beta1/domains_client.go index d86a9fb25653..9bf37c07d4ed 100644 --- a/domains/apiv1beta1/domains_client.go +++ b/domains/apiv1beta1/domains_client.go @@ -56,7 +56,7 @@ type CallOptions struct { ResetAuthorizationCode []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("domains.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("domains.mtls.googleapis.com:443"), @@ -86,37 +86,263 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Domains API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + SearchDomains(context.Context, *domainspb.SearchDomainsRequest, ...gax.CallOption) (*domainspb.SearchDomainsResponse, error) + RetrieveRegisterParameters(context.Context, *domainspb.RetrieveRegisterParametersRequest, ...gax.CallOption) (*domainspb.RetrieveRegisterParametersResponse, error) + RegisterDomain(context.Context, *domainspb.RegisterDomainRequest, ...gax.CallOption) (*RegisterDomainOperation, error) + RegisterDomainOperation(name string) *RegisterDomainOperation + ListRegistrations(context.Context, *domainspb.ListRegistrationsRequest, ...gax.CallOption) *RegistrationIterator + GetRegistration(context.Context, *domainspb.GetRegistrationRequest, ...gax.CallOption) (*domainspb.Registration, error) + UpdateRegistration(context.Context, *domainspb.UpdateRegistrationRequest, ...gax.CallOption) (*UpdateRegistrationOperation, error) + UpdateRegistrationOperation(name string) *UpdateRegistrationOperation + ConfigureManagementSettings(context.Context, *domainspb.ConfigureManagementSettingsRequest, ...gax.CallOption) (*ConfigureManagementSettingsOperation, error) + ConfigureManagementSettingsOperation(name string) *ConfigureManagementSettingsOperation + ConfigureDnsSettings(context.Context, *domainspb.ConfigureDnsSettingsRequest, ...gax.CallOption) (*ConfigureDnsSettingsOperation, error) + ConfigureDnsSettingsOperation(name string) *ConfigureDnsSettingsOperation + ConfigureContactSettings(context.Context, *domainspb.ConfigureContactSettingsRequest, ...gax.CallOption) (*ConfigureContactSettingsOperation, error) + ConfigureContactSettingsOperation(name string) *ConfigureContactSettingsOperation + ExportRegistration(context.Context, *domainspb.ExportRegistrationRequest, ...gax.CallOption) (*ExportRegistrationOperation, error) + ExportRegistrationOperation(name string) *ExportRegistrationOperation + DeleteRegistration(context.Context, *domainspb.DeleteRegistrationRequest, ...gax.CallOption) (*DeleteRegistrationOperation, error) + DeleteRegistrationOperation(name string) *DeleteRegistrationOperation + RetrieveAuthorizationCode(context.Context, *domainspb.RetrieveAuthorizationCodeRequest, ...gax.CallOption) (*domainspb.AuthorizationCode, error) + ResetAuthorizationCode(context.Context, *domainspb.ResetAuthorizationCodeRequest, ...gax.CallOption) (*domainspb.AuthorizationCode, error) +} + // Client is a client for interacting with Cloud Domains API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The Cloud Domains API enables management and configuration of domain names. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// SearchDomains searches for available domain names similar to the provided query. +// +// Availability results from this method are approximate; call +// RetrieveRegisterParameters on a domain before registering to confirm +// availability. +func (c *Client) SearchDomains(ctx context.Context, req *domainspb.SearchDomainsRequest, opts ...gax.CallOption) (*domainspb.SearchDomainsResponse, error) { + return c.internalClient.SearchDomains(ctx, req, opts...) +} + +// RetrieveRegisterParameters gets parameters needed to register a new domain name, including price and +// up-to-date availability. Use the returned values to call RegisterDomain. +func (c *Client) RetrieveRegisterParameters(ctx context.Context, req *domainspb.RetrieveRegisterParametersRequest, opts ...gax.CallOption) (*domainspb.RetrieveRegisterParametersResponse, error) { + return c.internalClient.RetrieveRegisterParameters(ctx, req, opts...) +} + +// RegisterDomain registers a new domain name and creates a corresponding Registration +// resource. +// +// Call RetrieveRegisterParameters first to check availability of the domain +// name and determine parameters like price that are needed to build a call to +// this method. +// +// A successful call creates a Registration resource in state +// REGISTRATION_PENDING, which resolves to ACTIVE within 1-2 +// minutes, indicating that the domain was successfully registered. If the +// resource ends up in state REGISTRATION_FAILED, it indicates that the +// domain was not registered successfully, and you can safely delete the +// resource and retry registration. +func (c *Client) RegisterDomain(ctx context.Context, req *domainspb.RegisterDomainRequest, opts ...gax.CallOption) (*RegisterDomainOperation, error) { + return c.internalClient.RegisterDomain(ctx, req, opts...) +} + +// RegisterDomainOperation returns a new RegisterDomainOperation from a given name. +// The name must be that of a previously created RegisterDomainOperation, possibly from a different process. +func (c *Client) RegisterDomainOperation(name string) *RegisterDomainOperation { + return c.internalClient.RegisterDomainOperation(name) +} + +// ListRegistrations lists the Registration resources in a project. +func (c *Client) ListRegistrations(ctx context.Context, req *domainspb.ListRegistrationsRequest, opts ...gax.CallOption) *RegistrationIterator { + return c.internalClient.ListRegistrations(ctx, req, opts...) +} + +// GetRegistration gets the details of a Registration resource. +func (c *Client) GetRegistration(ctx context.Context, req *domainspb.GetRegistrationRequest, opts ...gax.CallOption) (*domainspb.Registration, error) { + return c.internalClient.GetRegistration(ctx, req, opts...) +} + +// UpdateRegistration updates select fields of a Registration resource, notably labels. To +// update other fields, use the appropriate custom update method: +// +// To update management settings, see ConfigureManagementSettings +// +// To update DNS configuration, see ConfigureDnsSettings +// +// To update contact information, see ConfigureContactSettings +func (c *Client) UpdateRegistration(ctx context.Context, req *domainspb.UpdateRegistrationRequest, opts ...gax.CallOption) (*UpdateRegistrationOperation, error) { + return c.internalClient.UpdateRegistration(ctx, req, opts...) +} + +// UpdateRegistrationOperation returns a new UpdateRegistrationOperation from a given name. +// The name must be that of a previously created UpdateRegistrationOperation, possibly from a different process. +func (c *Client) UpdateRegistrationOperation(name string) *UpdateRegistrationOperation { + return c.internalClient.UpdateRegistrationOperation(name) +} + +// ConfigureManagementSettings updates a Registration's management settings. +func (c *Client) ConfigureManagementSettings(ctx context.Context, req *domainspb.ConfigureManagementSettingsRequest, opts ...gax.CallOption) (*ConfigureManagementSettingsOperation, error) { + return c.internalClient.ConfigureManagementSettings(ctx, req, opts...) +} + +// ConfigureManagementSettingsOperation returns a new ConfigureManagementSettingsOperation from a given name. +// The name must be that of a previously created ConfigureManagementSettingsOperation, possibly from a different process. +func (c *Client) ConfigureManagementSettingsOperation(name string) *ConfigureManagementSettingsOperation { + return c.internalClient.ConfigureManagementSettingsOperation(name) +} + +// ConfigureDnsSettings updates a Registration's DNS settings. +func (c *Client) ConfigureDnsSettings(ctx context.Context, req *domainspb.ConfigureDnsSettingsRequest, opts ...gax.CallOption) (*ConfigureDnsSettingsOperation, error) { + return c.internalClient.ConfigureDnsSettings(ctx, req, opts...) +} + +// ConfigureDnsSettingsOperation returns a new ConfigureDnsSettingsOperation from a given name. +// The name must be that of a previously created ConfigureDnsSettingsOperation, possibly from a different process. +func (c *Client) ConfigureDnsSettingsOperation(name string) *ConfigureDnsSettingsOperation { + return c.internalClient.ConfigureDnsSettingsOperation(name) +} + +// ConfigureContactSettings updates a Registration's contact settings. Some changes require +// confirmation by the domain’s registrant contact . +func (c *Client) ConfigureContactSettings(ctx context.Context, req *domainspb.ConfigureContactSettingsRequest, opts ...gax.CallOption) (*ConfigureContactSettingsOperation, error) { + return c.internalClient.ConfigureContactSettings(ctx, req, opts...) +} + +// ConfigureContactSettingsOperation returns a new ConfigureContactSettingsOperation from a given name. +// The name must be that of a previously created ConfigureContactSettingsOperation, possibly from a different process. +func (c *Client) ConfigureContactSettingsOperation(name string) *ConfigureContactSettingsOperation { + return c.internalClient.ConfigureContactSettingsOperation(name) +} + +// ExportRegistration exports a Registration that you no longer want to use with +// Cloud Domains. You can continue to use the domain in +// Google Domains (at https://domains.google/) until it expires. +// +// If the export is successful: +// +// The resource’s state becomes EXPORTED, meaning that it is no longer +// managed by Cloud Domains +// +// Because individual users can own domains in Google Domains, the calling +// user becomes the domain’s sole owner. Permissions for the domain are +// subsequently managed in Google Domains. +// +// Without further action, the domain does not renew automatically. +// The new owner can set up billing in Google Domains to renew the domain +// if needed. +func (c *Client) ExportRegistration(ctx context.Context, req *domainspb.ExportRegistrationRequest, opts ...gax.CallOption) (*ExportRegistrationOperation, error) { + return c.internalClient.ExportRegistration(ctx, req, opts...) +} + +// ExportRegistrationOperation returns a new ExportRegistrationOperation from a given name. +// The name must be that of a previously created ExportRegistrationOperation, possibly from a different process. +func (c *Client) ExportRegistrationOperation(name string) *ExportRegistrationOperation { + return c.internalClient.ExportRegistrationOperation(name) +} + +// DeleteRegistration deletes a Registration resource. +// +// This method only works on resources in one of the following states: +// +// state is EXPORTED with expire_time in the past +// +// state is REGISTRATION_FAILED +func (c *Client) DeleteRegistration(ctx context.Context, req *domainspb.DeleteRegistrationRequest, opts ...gax.CallOption) (*DeleteRegistrationOperation, error) { + return c.internalClient.DeleteRegistration(ctx, req, opts...) +} + +// DeleteRegistrationOperation returns a new DeleteRegistrationOperation from a given name. +// The name must be that of a previously created DeleteRegistrationOperation, possibly from a different process. +func (c *Client) DeleteRegistrationOperation(name string) *DeleteRegistrationOperation { + return c.internalClient.DeleteRegistrationOperation(name) +} + +// RetrieveAuthorizationCode gets the authorization code of the Registration for the purpose of +// transferring the domain to another registrar. +// +// You can call this method only after 60 days have elapsed since the initial +// domain registration. +func (c *Client) RetrieveAuthorizationCode(ctx context.Context, req *domainspb.RetrieveAuthorizationCodeRequest, opts ...gax.CallOption) (*domainspb.AuthorizationCode, error) { + return c.internalClient.RetrieveAuthorizationCode(ctx, req, opts...) +} + +// ResetAuthorizationCode resets the authorization code of the Registration to a new random string. +// +// You can call this method only after 60 days have elapsed since the initial +// domain registration. +func (c *Client) ResetAuthorizationCode(ctx context.Context, req *domainspb.ResetAuthorizationCodeRequest, opts ...gax.CallOption) (*domainspb.AuthorizationCode, error) { + return c.internalClient.ResetAuthorizationCode(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud Domains API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client domainspb.DomainsClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new domains client. +// NewClient creates a new domains client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The Cloud Domains API enables management and configuration of domain names. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -134,16 +360,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: domainspb.NewDomainsClient(connPool), + client: domainspb.NewDomainsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -153,40 +382,36 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// SearchDomains searches for available domain names similar to the provided query. -// -// Availability results from this method are approximate; call -// RetrieveRegisterParameters on a domain before registering to confirm -// availability. -func (c *Client) SearchDomains(ctx context.Context, req *domainspb.SearchDomainsRequest, opts ...gax.CallOption) (*domainspb.SearchDomainsResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) SearchDomains(ctx context.Context, req *domainspb.SearchDomainsRequest, opts ...gax.CallOption) (*domainspb.SearchDomainsResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "location", url.QueryEscape(req.GetLocation()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SearchDomains[0:len(c.CallOptions.SearchDomains):len(c.CallOptions.SearchDomains)], opts...) + opts = append((*c.CallOptions).SearchDomains[0:len((*c.CallOptions).SearchDomains):len((*c.CallOptions).SearchDomains)], opts...) var resp *domainspb.SearchDomainsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -199,12 +424,10 @@ func (c *Client) SearchDomains(ctx context.Context, req *domainspb.SearchDomains return resp, nil } -// RetrieveRegisterParameters gets parameters needed to register a new domain name, including price and -// up-to-date availability. Use the returned values to call RegisterDomain. -func (c *Client) RetrieveRegisterParameters(ctx context.Context, req *domainspb.RetrieveRegisterParametersRequest, opts ...gax.CallOption) (*domainspb.RetrieveRegisterParametersResponse, error) { +func (c *gRPCClient) RetrieveRegisterParameters(ctx context.Context, req *domainspb.RetrieveRegisterParametersRequest, opts ...gax.CallOption) (*domainspb.RetrieveRegisterParametersResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "location", url.QueryEscape(req.GetLocation()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RetrieveRegisterParameters[0:len(c.CallOptions.RetrieveRegisterParameters):len(c.CallOptions.RetrieveRegisterParameters)], opts...) + opts = append((*c.CallOptions).RetrieveRegisterParameters[0:len((*c.CallOptions).RetrieveRegisterParameters):len((*c.CallOptions).RetrieveRegisterParameters)], opts...) var resp *domainspb.RetrieveRegisterParametersResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -217,23 +440,10 @@ func (c *Client) RetrieveRegisterParameters(ctx context.Context, req *domainspb. return resp, nil } -// RegisterDomain registers a new domain name and creates a corresponding Registration -// resource. -// -// Call RetrieveRegisterParameters first to check availability of the domain -// name and determine parameters like price that are needed to build a call to -// this method. -// -// A successful call creates a Registration resource in state -// REGISTRATION_PENDING, which resolves to ACTIVE within 1-2 -// minutes, indicating that the domain was successfully registered. If the -// resource ends up in state REGISTRATION_FAILED, it indicates that the -// domain was not registered successfully, and you can safely delete the -// resource and retry registration. -func (c *Client) RegisterDomain(ctx context.Context, req *domainspb.RegisterDomainRequest, opts ...gax.CallOption) (*RegisterDomainOperation, error) { +func (c *gRPCClient) RegisterDomain(ctx context.Context, req *domainspb.RegisterDomainRequest, opts ...gax.CallOption) (*RegisterDomainOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RegisterDomain[0:len(c.CallOptions.RegisterDomain):len(c.CallOptions.RegisterDomain)], opts...) + opts = append((*c.CallOptions).RegisterDomain[0:len((*c.CallOptions).RegisterDomain):len((*c.CallOptions).RegisterDomain)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -244,15 +454,14 @@ func (c *Client) RegisterDomain(ctx context.Context, req *domainspb.RegisterDoma return nil, err } return &RegisterDomainOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListRegistrations lists the Registration resources in a project. -func (c *Client) ListRegistrations(ctx context.Context, req *domainspb.ListRegistrationsRequest, opts ...gax.CallOption) *RegistrationIterator { +func (c *gRPCClient) ListRegistrations(ctx context.Context, req *domainspb.ListRegistrationsRequest, opts ...gax.CallOption) *RegistrationIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListRegistrations[0:len(c.CallOptions.ListRegistrations):len(c.CallOptions.ListRegistrations)], opts...) + opts = append((*c.CallOptions).ListRegistrations[0:len((*c.CallOptions).ListRegistrations):len((*c.CallOptions).ListRegistrations)], opts...) it := &RegistrationIterator{} req = proto.Clone(req).(*domainspb.ListRegistrationsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*domainspb.Registration, string, error) { @@ -289,11 +498,10 @@ func (c *Client) ListRegistrations(ctx context.Context, req *domainspb.ListRegis return it } -// GetRegistration gets the details of a Registration resource. -func (c *Client) GetRegistration(ctx context.Context, req *domainspb.GetRegistrationRequest, opts ...gax.CallOption) (*domainspb.Registration, error) { +func (c *gRPCClient) GetRegistration(ctx context.Context, req *domainspb.GetRegistrationRequest, opts ...gax.CallOption) (*domainspb.Registration, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetRegistration[0:len(c.CallOptions.GetRegistration):len(c.CallOptions.GetRegistration)], opts...) + opts = append((*c.CallOptions).GetRegistration[0:len((*c.CallOptions).GetRegistration):len((*c.CallOptions).GetRegistration)], opts...) var resp *domainspb.Registration err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -306,18 +514,10 @@ func (c *Client) GetRegistration(ctx context.Context, req *domainspb.GetRegistra return resp, nil } -// UpdateRegistration updates select fields of a Registration resource, notably labels. To -// update other fields, use the appropriate custom update method: -// -// To update management settings, see ConfigureManagementSettings -// -// To update DNS configuration, see ConfigureDnsSettings -// -// To update contact information, see ConfigureContactSettings -func (c *Client) UpdateRegistration(ctx context.Context, req *domainspb.UpdateRegistrationRequest, opts ...gax.CallOption) (*UpdateRegistrationOperation, error) { +func (c *gRPCClient) UpdateRegistration(ctx context.Context, req *domainspb.UpdateRegistrationRequest, opts ...gax.CallOption) (*UpdateRegistrationOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "registration.name", url.QueryEscape(req.GetRegistration().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateRegistration[0:len(c.CallOptions.UpdateRegistration):len(c.CallOptions.UpdateRegistration)], opts...) + opts = append((*c.CallOptions).UpdateRegistration[0:len((*c.CallOptions).UpdateRegistration):len((*c.CallOptions).UpdateRegistration)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -328,15 +528,14 @@ func (c *Client) UpdateRegistration(ctx context.Context, req *domainspb.UpdateRe return nil, err } return &UpdateRegistrationOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ConfigureManagementSettings updates a Registration's management settings. -func (c *Client) ConfigureManagementSettings(ctx context.Context, req *domainspb.ConfigureManagementSettingsRequest, opts ...gax.CallOption) (*ConfigureManagementSettingsOperation, error) { +func (c *gRPCClient) ConfigureManagementSettings(ctx context.Context, req *domainspb.ConfigureManagementSettingsRequest, opts ...gax.CallOption) (*ConfigureManagementSettingsOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "registration", url.QueryEscape(req.GetRegistration()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ConfigureManagementSettings[0:len(c.CallOptions.ConfigureManagementSettings):len(c.CallOptions.ConfigureManagementSettings)], opts...) + opts = append((*c.CallOptions).ConfigureManagementSettings[0:len((*c.CallOptions).ConfigureManagementSettings):len((*c.CallOptions).ConfigureManagementSettings)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -347,15 +546,14 @@ func (c *Client) ConfigureManagementSettings(ctx context.Context, req *domainspb return nil, err } return &ConfigureManagementSettingsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ConfigureDnsSettings updates a Registration's DNS settings. -func (c *Client) ConfigureDnsSettings(ctx context.Context, req *domainspb.ConfigureDnsSettingsRequest, opts ...gax.CallOption) (*ConfigureDnsSettingsOperation, error) { +func (c *gRPCClient) ConfigureDnsSettings(ctx context.Context, req *domainspb.ConfigureDnsSettingsRequest, opts ...gax.CallOption) (*ConfigureDnsSettingsOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "registration", url.QueryEscape(req.GetRegistration()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ConfigureDnsSettings[0:len(c.CallOptions.ConfigureDnsSettings):len(c.CallOptions.ConfigureDnsSettings)], opts...) + opts = append((*c.CallOptions).ConfigureDnsSettings[0:len((*c.CallOptions).ConfigureDnsSettings):len((*c.CallOptions).ConfigureDnsSettings)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -366,16 +564,14 @@ func (c *Client) ConfigureDnsSettings(ctx context.Context, req *domainspb.Config return nil, err } return &ConfigureDnsSettingsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ConfigureContactSettings updates a Registration's contact settings. Some changes require -// confirmation by the domain’s registrant contact . -func (c *Client) ConfigureContactSettings(ctx context.Context, req *domainspb.ConfigureContactSettingsRequest, opts ...gax.CallOption) (*ConfigureContactSettingsOperation, error) { +func (c *gRPCClient) ConfigureContactSettings(ctx context.Context, req *domainspb.ConfigureContactSettingsRequest, opts ...gax.CallOption) (*ConfigureContactSettingsOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "registration", url.QueryEscape(req.GetRegistration()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ConfigureContactSettings[0:len(c.CallOptions.ConfigureContactSettings):len(c.CallOptions.ConfigureContactSettings)], opts...) + opts = append((*c.CallOptions).ConfigureContactSettings[0:len((*c.CallOptions).ConfigureContactSettings):len((*c.CallOptions).ConfigureContactSettings)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -386,30 +582,14 @@ func (c *Client) ConfigureContactSettings(ctx context.Context, req *domainspb.Co return nil, err } return &ConfigureContactSettingsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ExportRegistration exports a Registration that you no longer want to use with -// Cloud Domains. You can continue to use the domain in -// Google Domains (at https://domains.google/) until it expires. -// -// If the export is successful: -// -// The resource’s state becomes EXPORTED, meaning that it is no longer -// managed by Cloud Domains -// -// Because individual users can own domains in Google Domains, the calling -// user becomes the domain’s sole owner. Permissions for the domain are -// subsequently managed in Google Domains. -// -// Without further action, the domain does not renew automatically. -// The new owner can set up billing in Google Domains to renew the domain -// if needed. -func (c *Client) ExportRegistration(ctx context.Context, req *domainspb.ExportRegistrationRequest, opts ...gax.CallOption) (*ExportRegistrationOperation, error) { +func (c *gRPCClient) ExportRegistration(ctx context.Context, req *domainspb.ExportRegistrationRequest, opts ...gax.CallOption) (*ExportRegistrationOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportRegistration[0:len(c.CallOptions.ExportRegistration):len(c.CallOptions.ExportRegistration)], opts...) + opts = append((*c.CallOptions).ExportRegistration[0:len((*c.CallOptions).ExportRegistration):len((*c.CallOptions).ExportRegistration)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -420,21 +600,14 @@ func (c *Client) ExportRegistration(ctx context.Context, req *domainspb.ExportRe return nil, err } return &ExportRegistrationOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteRegistration deletes a Registration resource. -// -// This method only works on resources in one of the following states: -// -// state is EXPORTED with expire_time in the past -// -// state is REGISTRATION_FAILED -func (c *Client) DeleteRegistration(ctx context.Context, req *domainspb.DeleteRegistrationRequest, opts ...gax.CallOption) (*DeleteRegistrationOperation, error) { +func (c *gRPCClient) DeleteRegistration(ctx context.Context, req *domainspb.DeleteRegistrationRequest, opts ...gax.CallOption) (*DeleteRegistrationOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteRegistration[0:len(c.CallOptions.DeleteRegistration):len(c.CallOptions.DeleteRegistration)], opts...) + opts = append((*c.CallOptions).DeleteRegistration[0:len((*c.CallOptions).DeleteRegistration):len((*c.CallOptions).DeleteRegistration)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -445,19 +618,14 @@ func (c *Client) DeleteRegistration(ctx context.Context, req *domainspb.DeleteRe return nil, err } return &DeleteRegistrationOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// RetrieveAuthorizationCode gets the authorization code of the Registration for the purpose of -// transferring the domain to another registrar. -// -// You can call this method only after 60 days have elapsed since the initial -// domain registration. -func (c *Client) RetrieveAuthorizationCode(ctx context.Context, req *domainspb.RetrieveAuthorizationCodeRequest, opts ...gax.CallOption) (*domainspb.AuthorizationCode, error) { +func (c *gRPCClient) RetrieveAuthorizationCode(ctx context.Context, req *domainspb.RetrieveAuthorizationCodeRequest, opts ...gax.CallOption) (*domainspb.AuthorizationCode, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "registration", url.QueryEscape(req.GetRegistration()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RetrieveAuthorizationCode[0:len(c.CallOptions.RetrieveAuthorizationCode):len(c.CallOptions.RetrieveAuthorizationCode)], opts...) + opts = append((*c.CallOptions).RetrieveAuthorizationCode[0:len((*c.CallOptions).RetrieveAuthorizationCode):len((*c.CallOptions).RetrieveAuthorizationCode)], opts...) var resp *domainspb.AuthorizationCode err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -470,14 +638,10 @@ func (c *Client) RetrieveAuthorizationCode(ctx context.Context, req *domainspb.R return resp, nil } -// ResetAuthorizationCode resets the authorization code of the Registration to a new random string. -// -// You can call this method only after 60 days have elapsed since the initial -// domain registration. -func (c *Client) ResetAuthorizationCode(ctx context.Context, req *domainspb.ResetAuthorizationCodeRequest, opts ...gax.CallOption) (*domainspb.AuthorizationCode, error) { +func (c *gRPCClient) ResetAuthorizationCode(ctx context.Context, req *domainspb.ResetAuthorizationCodeRequest, opts ...gax.CallOption) (*domainspb.AuthorizationCode, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "registration", url.QueryEscape(req.GetRegistration()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ResetAuthorizationCode[0:len(c.CallOptions.ResetAuthorizationCode):len(c.CallOptions.ResetAuthorizationCode)], opts...) + opts = append((*c.CallOptions).ResetAuthorizationCode[0:len((*c.CallOptions).ResetAuthorizationCode):len((*c.CallOptions).ResetAuthorizationCode)], opts...) var resp *domainspb.AuthorizationCode err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -497,9 +661,9 @@ type ConfigureContactSettingsOperation struct { // ConfigureContactSettingsOperation returns a new ConfigureContactSettingsOperation from a given name. // The name must be that of a previously created ConfigureContactSettingsOperation, possibly from a different process. -func (c *Client) ConfigureContactSettingsOperation(name string) *ConfigureContactSettingsOperation { +func (c *gRPCClient) ConfigureContactSettingsOperation(name string) *ConfigureContactSettingsOperation { return &ConfigureContactSettingsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -566,9 +730,9 @@ type ConfigureDnsSettingsOperation struct { // ConfigureDnsSettingsOperation returns a new ConfigureDnsSettingsOperation from a given name. // The name must be that of a previously created ConfigureDnsSettingsOperation, possibly from a different process. -func (c *Client) ConfigureDnsSettingsOperation(name string) *ConfigureDnsSettingsOperation { +func (c *gRPCClient) ConfigureDnsSettingsOperation(name string) *ConfigureDnsSettingsOperation { return &ConfigureDnsSettingsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -635,9 +799,9 @@ type ConfigureManagementSettingsOperation struct { // ConfigureManagementSettingsOperation returns a new ConfigureManagementSettingsOperation from a given name. // The name must be that of a previously created ConfigureManagementSettingsOperation, possibly from a different process. -func (c *Client) ConfigureManagementSettingsOperation(name string) *ConfigureManagementSettingsOperation { +func (c *gRPCClient) ConfigureManagementSettingsOperation(name string) *ConfigureManagementSettingsOperation { return &ConfigureManagementSettingsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -704,9 +868,9 @@ type DeleteRegistrationOperation struct { // DeleteRegistrationOperation returns a new DeleteRegistrationOperation from a given name. // The name must be that of a previously created DeleteRegistrationOperation, possibly from a different process. -func (c *Client) DeleteRegistrationOperation(name string) *DeleteRegistrationOperation { +func (c *gRPCClient) DeleteRegistrationOperation(name string) *DeleteRegistrationOperation { return &DeleteRegistrationOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -762,9 +926,9 @@ type ExportRegistrationOperation struct { // ExportRegistrationOperation returns a new ExportRegistrationOperation from a given name. // The name must be that of a previously created ExportRegistrationOperation, possibly from a different process. -func (c *Client) ExportRegistrationOperation(name string) *ExportRegistrationOperation { +func (c *gRPCClient) ExportRegistrationOperation(name string) *ExportRegistrationOperation { return &ExportRegistrationOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -831,9 +995,9 @@ type RegisterDomainOperation struct { // RegisterDomainOperation returns a new RegisterDomainOperation from a given name. // The name must be that of a previously created RegisterDomainOperation, possibly from a different process. -func (c *Client) RegisterDomainOperation(name string) *RegisterDomainOperation { +func (c *gRPCClient) RegisterDomainOperation(name string) *RegisterDomainOperation { return &RegisterDomainOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -900,9 +1064,9 @@ type UpdateRegistrationOperation struct { // UpdateRegistrationOperation returns a new UpdateRegistrationOperation from a given name. // The name must be that of a previously created UpdateRegistrationOperation, possibly from a different process. -func (c *Client) UpdateRegistrationOperation(name string) *UpdateRegistrationOperation { +func (c *gRPCClient) UpdateRegistrationOperation(name string) *UpdateRegistrationOperation { return &UpdateRegistrationOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/domains/apiv1beta1/domains_client_example_test.go b/domains/apiv1beta1/domains_client_example_test.go index 5067d17684ba..d4a4b9dbe3e9 100644 --- a/domains/apiv1beta1/domains_client_example_test.go +++ b/domains/apiv1beta1/domains_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_SearchDomains() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.SearchDomainsRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleClient_SearchDomains() { } func ExampleClient_RetrieveRegisterParameters() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.RetrieveRegisterParametersRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleClient_RetrieveRegisterParameters() { } func ExampleClient_RegisterDomain() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.RegisterDomainRequest{ // TODO: Fill request struct fields. @@ -100,14 +99,12 @@ func ExampleClient_RegisterDomain() { } func ExampleClient_ListRegistrations() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.ListRegistrationsRequest{ // TODO: Fill request struct fields. @@ -127,13 +124,12 @@ func ExampleClient_ListRegistrations() { } func ExampleClient_GetRegistration() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.GetRegistrationRequest{ // TODO: Fill request struct fields. @@ -147,13 +143,12 @@ func ExampleClient_GetRegistration() { } func ExampleClient_UpdateRegistration() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.UpdateRegistrationRequest{ // TODO: Fill request struct fields. @@ -172,13 +167,12 @@ func ExampleClient_UpdateRegistration() { } func ExampleClient_ConfigureManagementSettings() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.ConfigureManagementSettingsRequest{ // TODO: Fill request struct fields. @@ -197,13 +191,12 @@ func ExampleClient_ConfigureManagementSettings() { } func ExampleClient_ConfigureDnsSettings() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.ConfigureDnsSettingsRequest{ // TODO: Fill request struct fields. @@ -222,13 +215,12 @@ func ExampleClient_ConfigureDnsSettings() { } func ExampleClient_ConfigureContactSettings() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.ConfigureContactSettingsRequest{ // TODO: Fill request struct fields. @@ -247,13 +239,12 @@ func ExampleClient_ConfigureContactSettings() { } func ExampleClient_ExportRegistration() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.ExportRegistrationRequest{ // TODO: Fill request struct fields. @@ -272,13 +263,12 @@ func ExampleClient_ExportRegistration() { } func ExampleClient_DeleteRegistration() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.DeleteRegistrationRequest{ // TODO: Fill request struct fields. @@ -295,13 +285,12 @@ func ExampleClient_DeleteRegistration() { } func ExampleClient_RetrieveAuthorizationCode() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.RetrieveAuthorizationCodeRequest{ // TODO: Fill request struct fields. @@ -315,13 +304,12 @@ func ExampleClient_RetrieveAuthorizationCode() { } func ExampleClient_ResetAuthorizationCode() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.ResetAuthorizationCodeRequest{ // TODO: Fill request struct fields. diff --git a/errorreporting/apiv1beta1/doc.go b/errorreporting/apiv1beta1/doc.go index 8eadfff92d3a..d0c89fc22a27 100644 --- a/errorreporting/apiv1beta1/doc.go +++ b/errorreporting/apiv1beta1/doc.go @@ -21,6 +21,8 @@ // reports new errors, and provides access to error groups and their // associated errors. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -30,7 +32,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package errorreporting // import "cloud.google.com/go/errorreporting/apiv1beta1" import ( @@ -50,7 +52,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/errorreporting/apiv1beta1/error_group_client.go b/errorreporting/apiv1beta1/error_group_client.go index bd3f3ad7576e..747a985e4d86 100644 --- a/errorreporting/apiv1beta1/error_group_client.go +++ b/errorreporting/apiv1beta1/error_group_client.go @@ -41,7 +41,7 @@ type ErrorGroupCallOptions struct { UpdateGroup []gax.CallOption } -func defaultErrorGroupClientOptions() []option.ClientOption { +func defaultErrorGroupGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("clouderrorreporting.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("clouderrorreporting.mtls.googleapis.com:443"), @@ -82,32 +82,86 @@ func defaultErrorGroupCallOptions() *ErrorGroupCallOptions { } } +// internalErrorGroupClient is an interface that defines the methods availaible from Error Reporting API. +type internalErrorGroupClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + GetGroup(context.Context, *clouderrorreportingpb.GetGroupRequest, ...gax.CallOption) (*clouderrorreportingpb.ErrorGroup, error) + UpdateGroup(context.Context, *clouderrorreportingpb.UpdateGroupRequest, ...gax.CallOption) (*clouderrorreportingpb.ErrorGroup, error) +} + // ErrorGroupClient is a client for interacting with Error Reporting API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for retrieving and updating individual error groups. type ErrorGroupClient struct { + // The internal transport-dependent client. + internalClient internalErrorGroupClient + + // The call options for this service. + CallOptions *ErrorGroupCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ErrorGroupClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ErrorGroupClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ErrorGroupClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// GetGroup get the specified group. +func (c *ErrorGroupClient) GetGroup(ctx context.Context, req *clouderrorreportingpb.GetGroupRequest, opts ...gax.CallOption) (*clouderrorreportingpb.ErrorGroup, error) { + return c.internalClient.GetGroup(ctx, req, opts...) +} + +// UpdateGroup replace the data for the specified group. +// Fails if the group does not exist. +func (c *ErrorGroupClient) UpdateGroup(ctx context.Context, req *clouderrorreportingpb.UpdateGroupRequest, opts ...gax.CallOption) (*clouderrorreportingpb.ErrorGroup, error) { + return c.internalClient.UpdateGroup(ctx, req, opts...) +} + +// errorGroupGRPCClient is a client for interacting with Error Reporting API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type errorGroupGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ErrorGroupClient + CallOptions **ErrorGroupCallOptions + // The gRPC API client. errorGroupClient clouderrorreportingpb.ErrorGroupServiceClient - // The call options for this service. - CallOptions *ErrorGroupCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewErrorGroupClient creates a new error group service client. +// NewErrorGroupClient creates a new error group service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for retrieving and updating individual error groups. func NewErrorGroupClient(ctx context.Context, opts ...option.ClientOption) (*ErrorGroupClient, error) { - clientOpts := defaultErrorGroupClientOptions() - + clientOpts := defaultErrorGroupGRPCClientOptions() if newErrorGroupClientHook != nil { hookOpts, err := newErrorGroupClientHook(ctx, clientHookParams{}) if err != nil { @@ -125,42 +179,44 @@ func NewErrorGroupClient(ctx context.Context, opts ...option.ClientOption) (*Err if err != nil { return nil, err } - c := &ErrorGroupClient{ + client := ErrorGroupClient{CallOptions: defaultErrorGroupCallOptions()} + + c := &errorGroupGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultErrorGroupCallOptions(), - errorGroupClient: clouderrorreportingpb.NewErrorGroupServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ErrorGroupClient) Connection() *grpc.ClientConn { +func (c *errorGroupGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ErrorGroupClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ErrorGroupClient) setGoogleClientInfo(keyval ...string) { +func (c *errorGroupGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// GetGroup get the specified group. -func (c *ErrorGroupClient) GetGroup(ctx context.Context, req *clouderrorreportingpb.GetGroupRequest, opts ...gax.CallOption) (*clouderrorreportingpb.ErrorGroup, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *errorGroupGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *errorGroupGRPCClient) GetGroup(ctx context.Context, req *clouderrorreportingpb.GetGroupRequest, opts ...gax.CallOption) (*clouderrorreportingpb.ErrorGroup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -168,7 +224,7 @@ func (c *ErrorGroupClient) GetGroup(ctx context.Context, req *clouderrorreportin } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "group_name", url.QueryEscape(req.GetGroupName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetGroup[0:len(c.CallOptions.GetGroup):len(c.CallOptions.GetGroup)], opts...) + opts = append((*c.CallOptions).GetGroup[0:len((*c.CallOptions).GetGroup):len((*c.CallOptions).GetGroup)], opts...) var resp *clouderrorreportingpb.ErrorGroup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -181,9 +237,7 @@ func (c *ErrorGroupClient) GetGroup(ctx context.Context, req *clouderrorreportin return resp, nil } -// UpdateGroup replace the data for the specified group. -// Fails if the group does not exist. -func (c *ErrorGroupClient) UpdateGroup(ctx context.Context, req *clouderrorreportingpb.UpdateGroupRequest, opts ...gax.CallOption) (*clouderrorreportingpb.ErrorGroup, error) { +func (c *errorGroupGRPCClient) UpdateGroup(ctx context.Context, req *clouderrorreportingpb.UpdateGroupRequest, opts ...gax.CallOption) (*clouderrorreportingpb.ErrorGroup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -191,7 +245,7 @@ func (c *ErrorGroupClient) UpdateGroup(ctx context.Context, req *clouderrorrepor } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "group.name", url.QueryEscape(req.GetGroup().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateGroup[0:len(c.CallOptions.UpdateGroup):len(c.CallOptions.UpdateGroup)], opts...) + opts = append((*c.CallOptions).UpdateGroup[0:len((*c.CallOptions).UpdateGroup):len((*c.CallOptions).UpdateGroup)], opts...) var resp *clouderrorreportingpb.ErrorGroup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/errorreporting/apiv1beta1/error_group_client_example_test.go b/errorreporting/apiv1beta1/error_group_client_example_test.go index 5de23a7b21a5..14366d206533 100644 --- a/errorreporting/apiv1beta1/error_group_client_example_test.go +++ b/errorreporting/apiv1beta1/error_group_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewErrorGroupClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleErrorGroupClient_GetGroup() { - // import clouderrorreportingpb "google.golang.org/genproto/googleapis/devtools/clouderrorreporting/v1beta1" - ctx := context.Background() c, err := errorreporting.NewErrorGroupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouderrorreportingpb.GetGroupRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleErrorGroupClient_GetGroup() { } func ExampleErrorGroupClient_UpdateGroup() { - // import clouderrorreportingpb "google.golang.org/genproto/googleapis/devtools/clouderrorreporting/v1beta1" - ctx := context.Background() c, err := errorreporting.NewErrorGroupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouderrorreportingpb.UpdateGroupRequest{ // TODO: Fill request struct fields. diff --git a/errorreporting/apiv1beta1/error_stats_client.go b/errorreporting/apiv1beta1/error_stats_client.go index fed597ea9615..ca6bcd779dea 100644 --- a/errorreporting/apiv1beta1/error_stats_client.go +++ b/errorreporting/apiv1beta1/error_stats_client.go @@ -44,7 +44,7 @@ type ErrorStatsCallOptions struct { DeleteEvents []gax.CallOption } -func defaultErrorStatsClientOptions() []option.ClientOption { +func defaultErrorStatsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("clouderrorreporting.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("clouderrorreporting.mtls.googleapis.com:443"), @@ -97,33 +97,93 @@ func defaultErrorStatsCallOptions() *ErrorStatsCallOptions { } } +// internalErrorStatsClient is an interface that defines the methods availaible from Error Reporting API. +type internalErrorStatsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListGroupStats(context.Context, *clouderrorreportingpb.ListGroupStatsRequest, ...gax.CallOption) *ErrorGroupStatsIterator + ListEvents(context.Context, *clouderrorreportingpb.ListEventsRequest, ...gax.CallOption) *ErrorEventIterator + DeleteEvents(context.Context, *clouderrorreportingpb.DeleteEventsRequest, ...gax.CallOption) (*clouderrorreportingpb.DeleteEventsResponse, error) +} + // ErrorStatsClient is a client for interacting with Error Reporting API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// An API for retrieving and managing error statistics as well as data for +// individual events. type ErrorStatsClient struct { + // The internal transport-dependent client. + internalClient internalErrorStatsClient + + // The call options for this service. + CallOptions *ErrorStatsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ErrorStatsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ErrorStatsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ErrorStatsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListGroupStats lists the specified groups. +func (c *ErrorStatsClient) ListGroupStats(ctx context.Context, req *clouderrorreportingpb.ListGroupStatsRequest, opts ...gax.CallOption) *ErrorGroupStatsIterator { + return c.internalClient.ListGroupStats(ctx, req, opts...) +} + +// ListEvents lists the specified events. +func (c *ErrorStatsClient) ListEvents(ctx context.Context, req *clouderrorreportingpb.ListEventsRequest, opts ...gax.CallOption) *ErrorEventIterator { + return c.internalClient.ListEvents(ctx, req, opts...) +} + +// DeleteEvents deletes all error events of a given project. +func (c *ErrorStatsClient) DeleteEvents(ctx context.Context, req *clouderrorreportingpb.DeleteEventsRequest, opts ...gax.CallOption) (*clouderrorreportingpb.DeleteEventsResponse, error) { + return c.internalClient.DeleteEvents(ctx, req, opts...) +} + +// errorStatsGRPCClient is a client for interacting with Error Reporting API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type errorStatsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ErrorStatsClient + CallOptions **ErrorStatsCallOptions + // The gRPC API client. errorStatsClient clouderrorreportingpb.ErrorStatsServiceClient - // The call options for this service. - CallOptions *ErrorStatsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewErrorStatsClient creates a new error stats service client. +// NewErrorStatsClient creates a new error stats service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // An API for retrieving and managing error statistics as well as data for // individual events. func NewErrorStatsClient(ctx context.Context, opts ...option.ClientOption) (*ErrorStatsClient, error) { - clientOpts := defaultErrorStatsClientOptions() - + clientOpts := defaultErrorStatsGRPCClientOptions() if newErrorStatsClientHook != nil { hookOpts, err := newErrorStatsClientHook(ctx, clientHookParams{}) if err != nil { @@ -141,45 +201,47 @@ func NewErrorStatsClient(ctx context.Context, opts ...option.ClientOption) (*Err if err != nil { return nil, err } - c := &ErrorStatsClient{ + client := ErrorStatsClient{CallOptions: defaultErrorStatsCallOptions()} + + c := &errorStatsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultErrorStatsCallOptions(), - errorStatsClient: clouderrorreportingpb.NewErrorStatsServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ErrorStatsClient) Connection() *grpc.ClientConn { +func (c *errorStatsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ErrorStatsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ErrorStatsClient) setGoogleClientInfo(keyval ...string) { +func (c *errorStatsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListGroupStats lists the specified groups. -func (c *ErrorStatsClient) ListGroupStats(ctx context.Context, req *clouderrorreportingpb.ListGroupStatsRequest, opts ...gax.CallOption) *ErrorGroupStatsIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *errorStatsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *errorStatsGRPCClient) ListGroupStats(ctx context.Context, req *clouderrorreportingpb.ListGroupStatsRequest, opts ...gax.CallOption) *ErrorGroupStatsIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_name", url.QueryEscape(req.GetProjectName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListGroupStats[0:len(c.CallOptions.ListGroupStats):len(c.CallOptions.ListGroupStats)], opts...) + opts = append((*c.CallOptions).ListGroupStats[0:len((*c.CallOptions).ListGroupStats):len((*c.CallOptions).ListGroupStats)], opts...) it := &ErrorGroupStatsIterator{} req = proto.Clone(req).(*clouderrorreportingpb.ListGroupStatsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*clouderrorreportingpb.ErrorGroupStats, string, error) { @@ -216,11 +278,10 @@ func (c *ErrorStatsClient) ListGroupStats(ctx context.Context, req *clouderrorre return it } -// ListEvents lists the specified events. -func (c *ErrorStatsClient) ListEvents(ctx context.Context, req *clouderrorreportingpb.ListEventsRequest, opts ...gax.CallOption) *ErrorEventIterator { +func (c *errorStatsGRPCClient) ListEvents(ctx context.Context, req *clouderrorreportingpb.ListEventsRequest, opts ...gax.CallOption) *ErrorEventIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_name", url.QueryEscape(req.GetProjectName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListEvents[0:len(c.CallOptions.ListEvents):len(c.CallOptions.ListEvents)], opts...) + opts = append((*c.CallOptions).ListEvents[0:len((*c.CallOptions).ListEvents):len((*c.CallOptions).ListEvents)], opts...) it := &ErrorEventIterator{} req = proto.Clone(req).(*clouderrorreportingpb.ListEventsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*clouderrorreportingpb.ErrorEvent, string, error) { @@ -257,8 +318,7 @@ func (c *ErrorStatsClient) ListEvents(ctx context.Context, req *clouderrorreport return it } -// DeleteEvents deletes all error events of a given project. -func (c *ErrorStatsClient) DeleteEvents(ctx context.Context, req *clouderrorreportingpb.DeleteEventsRequest, opts ...gax.CallOption) (*clouderrorreportingpb.DeleteEventsResponse, error) { +func (c *errorStatsGRPCClient) DeleteEvents(ctx context.Context, req *clouderrorreportingpb.DeleteEventsRequest, opts ...gax.CallOption) (*clouderrorreportingpb.DeleteEventsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -266,7 +326,7 @@ func (c *ErrorStatsClient) DeleteEvents(ctx context.Context, req *clouderrorrepo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_name", url.QueryEscape(req.GetProjectName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteEvents[0:len(c.CallOptions.DeleteEvents):len(c.CallOptions.DeleteEvents)], opts...) + opts = append((*c.CallOptions).DeleteEvents[0:len((*c.CallOptions).DeleteEvents):len((*c.CallOptions).DeleteEvents)], opts...) var resp *clouderrorreportingpb.DeleteEventsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/errorreporting/apiv1beta1/error_stats_client_example_test.go b/errorreporting/apiv1beta1/error_stats_client_example_test.go index 91c1d5862b60..649822d79ee2 100644 --- a/errorreporting/apiv1beta1/error_stats_client_example_test.go +++ b/errorreporting/apiv1beta1/error_stats_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewErrorStatsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleErrorStatsClient_ListGroupStats() { - // import clouderrorreportingpb "google.golang.org/genproto/googleapis/devtools/clouderrorreporting/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := errorreporting.NewErrorStatsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouderrorreportingpb.ListGroupStatsRequest{ // TODO: Fill request struct fields. @@ -62,14 +62,12 @@ func ExampleErrorStatsClient_ListGroupStats() { } func ExampleErrorStatsClient_ListEvents() { - // import clouderrorreportingpb "google.golang.org/genproto/googleapis/devtools/clouderrorreporting/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := errorreporting.NewErrorStatsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouderrorreportingpb.ListEventsRequest{ // TODO: Fill request struct fields. @@ -89,13 +87,12 @@ func ExampleErrorStatsClient_ListEvents() { } func ExampleErrorStatsClient_DeleteEvents() { - // import clouderrorreportingpb "google.golang.org/genproto/googleapis/devtools/clouderrorreporting/v1beta1" - ctx := context.Background() c, err := errorreporting.NewErrorStatsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouderrorreportingpb.DeleteEventsRequest{ // TODO: Fill request struct fields. diff --git a/errorreporting/apiv1beta1/report_errors_client.go b/errorreporting/apiv1beta1/report_errors_client.go index 6c3c155400ac..dceb9eef727a 100644 --- a/errorreporting/apiv1beta1/report_errors_client.go +++ b/errorreporting/apiv1beta1/report_errors_client.go @@ -39,7 +39,7 @@ type ReportErrorsCallOptions struct { ReportErrorEvent []gax.CallOption } -func defaultReportErrorsClientOptions() []option.ClientOption { +func defaultReportErrorsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("clouderrorreporting.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("clouderrorreporting.mtls.googleapis.com:443"), @@ -57,32 +57,94 @@ func defaultReportErrorsCallOptions() *ReportErrorsCallOptions { } } +// internalReportErrorsClient is an interface that defines the methods availaible from Error Reporting API. +type internalReportErrorsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ReportErrorEvent(context.Context, *clouderrorreportingpb.ReportErrorEventRequest, ...gax.CallOption) (*clouderrorreportingpb.ReportErrorEventResponse, error) +} + // ReportErrorsClient is a client for interacting with Error Reporting API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// An API for reporting error events. type ReportErrorsClient struct { + // The internal transport-dependent client. + internalClient internalReportErrorsClient + + // The call options for this service. + CallOptions *ReportErrorsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ReportErrorsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ReportErrorsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ReportErrorsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ReportErrorEvent report an individual error event and record the event to a log. +// +// This endpoint accepts either an OAuth token, +// or an API key (at https://support.google.com/cloud/answer/6158862) +// for authentication. To use an API key, append it to the URL as the value of +// a key parameter. For example: +// +// POST https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456 +// +// Note: Error Reporting (at /error-reporting) is a global service built +// on Cloud Logging and doesn’t analyze logs stored +// in regional log buckets or logs routed to other Google Cloud projects. +// +// For more information, see +// Using Error Reporting with regionalized +// logs (at /error-reporting/docs/regionalization). +func (c *ReportErrorsClient) ReportErrorEvent(ctx context.Context, req *clouderrorreportingpb.ReportErrorEventRequest, opts ...gax.CallOption) (*clouderrorreportingpb.ReportErrorEventResponse, error) { + return c.internalClient.ReportErrorEvent(ctx, req, opts...) +} + +// reportErrorsGRPCClient is a client for interacting with Error Reporting API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type reportErrorsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ReportErrorsClient + CallOptions **ReportErrorsCallOptions + // The gRPC API client. reportErrorsClient clouderrorreportingpb.ReportErrorsServiceClient - // The call options for this service. - CallOptions *ReportErrorsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewReportErrorsClient creates a new report errors service client. +// NewReportErrorsClient creates a new report errors service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // An API for reporting error events. func NewReportErrorsClient(ctx context.Context, opts ...option.ClientOption) (*ReportErrorsClient, error) { - clientOpts := defaultReportErrorsClientOptions() - + clientOpts := defaultReportErrorsGRPCClientOptions() if newReportErrorsClientHook != nil { hookOpts, err := newReportErrorsClientHook(ctx, clientHookParams{}) if err != nil { @@ -100,57 +162,44 @@ func NewReportErrorsClient(ctx context.Context, opts ...option.ClientOption) (*R if err != nil { return nil, err } - c := &ReportErrorsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultReportErrorsCallOptions(), + client := ReportErrorsClient{CallOptions: defaultReportErrorsCallOptions()} + c := &reportErrorsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, reportErrorsClient: clouderrorreportingpb.NewReportErrorsServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ReportErrorsClient) Connection() *grpc.ClientConn { +func (c *reportErrorsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ReportErrorsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ReportErrorsClient) setGoogleClientInfo(keyval ...string) { +func (c *reportErrorsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ReportErrorEvent report an individual error event and record the event to a log. -// -// This endpoint accepts either an OAuth token, -// or an API key (at https://support.google.com/cloud/answer/6158862) -// for authentication. To use an API key, append it to the URL as the value of -// a key parameter. For example: -// -// POST https://clouderrorreporting.googleapis.com/v1beta1/{projectName}/events:report?key=123ABC456 -// -// Note: Error Reporting (at /error-reporting) is a global service built -// on Cloud Logging and doesn’t analyze logs stored -// in regional log buckets or logs routed to other Google Cloud projects. -// -// For more information, see -// Using Error Reporting with regionalized -// logs (at /error-reporting/docs/regionalization). -func (c *ReportErrorsClient) ReportErrorEvent(ctx context.Context, req *clouderrorreportingpb.ReportErrorEventRequest, opts ...gax.CallOption) (*clouderrorreportingpb.ReportErrorEventResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *reportErrorsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *reportErrorsGRPCClient) ReportErrorEvent(ctx context.Context, req *clouderrorreportingpb.ReportErrorEventRequest, opts ...gax.CallOption) (*clouderrorreportingpb.ReportErrorEventResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -158,7 +207,7 @@ func (c *ReportErrorsClient) ReportErrorEvent(ctx context.Context, req *clouderr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_name", url.QueryEscape(req.GetProjectName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ReportErrorEvent[0:len(c.CallOptions.ReportErrorEvent):len(c.CallOptions.ReportErrorEvent)], opts...) + opts = append((*c.CallOptions).ReportErrorEvent[0:len((*c.CallOptions).ReportErrorEvent):len((*c.CallOptions).ReportErrorEvent)], opts...) var resp *clouderrorreportingpb.ReportErrorEventResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/errorreporting/apiv1beta1/report_errors_client_example_test.go b/errorreporting/apiv1beta1/report_errors_client_example_test.go index 53126bdc731f..69d1ebf43e22 100644 --- a/errorreporting/apiv1beta1/report_errors_client_example_test.go +++ b/errorreporting/apiv1beta1/report_errors_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewReportErrorsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleReportErrorsClient_ReportErrorEvent() { - // import clouderrorreportingpb "google.golang.org/genproto/googleapis/devtools/clouderrorreporting/v1beta1" - ctx := context.Background() c, err := errorreporting.NewReportErrorsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouderrorreportingpb.ReportErrorEventRequest{ // TODO: Fill request struct fields. diff --git a/firestore/apiv1/admin/doc.go b/firestore/apiv1/admin/doc.go index 55797de21d51..f1af8f38b2f9 100644 --- a/firestore/apiv1/admin/doc.go +++ b/firestore/apiv1/admin/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package apiv1 // import "cloud.google.com/go/firestore/apiv1/admin" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/firestore/apiv1/admin/firestore_admin_client.go b/firestore/apiv1/admin/firestore_admin_client.go index 82b503c6acc7..b0a2ca69038b 100644 --- a/firestore/apiv1/admin/firestore_admin_client.go +++ b/firestore/apiv1/admin/firestore_admin_client.go @@ -53,7 +53,7 @@ type FirestoreAdminCallOptions struct { ImportDocuments []gax.CallOption } -func defaultFirestoreAdminClientOptions() []option.ClientOption { +func defaultFirestoreAdminGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("firestore.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("firestore.mtls.googleapis.com:443"), @@ -139,38 +139,197 @@ func defaultFirestoreAdminCallOptions() *FirestoreAdminCallOptions { } } +// internalFirestoreAdminClient is an interface that defines the methods availaible from Google Cloud Firestore Admin API. +type internalFirestoreAdminClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateIndex(context.Context, *adminpb.CreateIndexRequest, ...gax.CallOption) (*CreateIndexOperation, error) + CreateIndexOperation(name string) *CreateIndexOperation + ListIndexes(context.Context, *adminpb.ListIndexesRequest, ...gax.CallOption) *IndexIterator + GetIndex(context.Context, *adminpb.GetIndexRequest, ...gax.CallOption) (*adminpb.Index, error) + DeleteIndex(context.Context, *adminpb.DeleteIndexRequest, ...gax.CallOption) error + GetField(context.Context, *adminpb.GetFieldRequest, ...gax.CallOption) (*adminpb.Field, error) + UpdateField(context.Context, *adminpb.UpdateFieldRequest, ...gax.CallOption) (*UpdateFieldOperation, error) + UpdateFieldOperation(name string) *UpdateFieldOperation + ListFields(context.Context, *adminpb.ListFieldsRequest, ...gax.CallOption) *FieldIterator + ExportDocuments(context.Context, *adminpb.ExportDocumentsRequest, ...gax.CallOption) (*ExportDocumentsOperation, error) + ExportDocumentsOperation(name string) *ExportDocumentsOperation + ImportDocuments(context.Context, *adminpb.ImportDocumentsRequest, ...gax.CallOption) (*ImportDocumentsOperation, error) + ImportDocumentsOperation(name string) *ImportDocumentsOperation +} + // FirestoreAdminClient is a client for interacting with Google Cloud Firestore Admin API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Operations are created by service FirestoreAdmin, but are accessed via +// service google.longrunning.Operations. type FirestoreAdminClient struct { + // The internal transport-dependent client. + internalClient internalFirestoreAdminClient + + // The call options for this service. + CallOptions *FirestoreAdminCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *FirestoreAdminClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *FirestoreAdminClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *FirestoreAdminClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateIndex creates a composite index. This returns a google.longrunning.Operation +// which may be used to track the status of the creation. The metadata for +// the operation will be the type IndexOperationMetadata. +func (c *FirestoreAdminClient) CreateIndex(ctx context.Context, req *adminpb.CreateIndexRequest, opts ...gax.CallOption) (*CreateIndexOperation, error) { + return c.internalClient.CreateIndex(ctx, req, opts...) +} + +// CreateIndexOperation returns a new CreateIndexOperation from a given name. +// The name must be that of a previously created CreateIndexOperation, possibly from a different process. +func (c *FirestoreAdminClient) CreateIndexOperation(name string) *CreateIndexOperation { + return c.internalClient.CreateIndexOperation(name) +} + +// ListIndexes lists composite indexes. +func (c *FirestoreAdminClient) ListIndexes(ctx context.Context, req *adminpb.ListIndexesRequest, opts ...gax.CallOption) *IndexIterator { + return c.internalClient.ListIndexes(ctx, req, opts...) +} + +// GetIndex gets a composite index. +func (c *FirestoreAdminClient) GetIndex(ctx context.Context, req *adminpb.GetIndexRequest, opts ...gax.CallOption) (*adminpb.Index, error) { + return c.internalClient.GetIndex(ctx, req, opts...) +} + +// DeleteIndex deletes a composite index. +func (c *FirestoreAdminClient) DeleteIndex(ctx context.Context, req *adminpb.DeleteIndexRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteIndex(ctx, req, opts...) +} + +// GetField gets the metadata and configuration for a Field. +func (c *FirestoreAdminClient) GetField(ctx context.Context, req *adminpb.GetFieldRequest, opts ...gax.CallOption) (*adminpb.Field, error) { + return c.internalClient.GetField(ctx, req, opts...) +} + +// UpdateField updates a field configuration. Currently, field updates apply only to +// single field index configuration. However, calls to +// FirestoreAdmin.UpdateField should provide a field mask to avoid +// changing any configuration that the caller isn’t aware of. The field mask +// should be specified as: { paths: "index_config" }. +// +// This call returns a google.longrunning.Operation which may be used to +// track the status of the field update. The metadata for +// the operation will be the type FieldOperationMetadata. +// +// To configure the default field settings for the database, use +// the special Field with resource name: +// projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/*. +func (c *FirestoreAdminClient) UpdateField(ctx context.Context, req *adminpb.UpdateFieldRequest, opts ...gax.CallOption) (*UpdateFieldOperation, error) { + return c.internalClient.UpdateField(ctx, req, opts...) +} + +// UpdateFieldOperation returns a new UpdateFieldOperation from a given name. +// The name must be that of a previously created UpdateFieldOperation, possibly from a different process. +func (c *FirestoreAdminClient) UpdateFieldOperation(name string) *UpdateFieldOperation { + return c.internalClient.UpdateFieldOperation(name) +} + +// ListFields lists the field configuration and metadata for this database. +// +// Currently, FirestoreAdmin.ListFields only supports listing fields +// that have been explicitly overridden. To issue this query, call +// FirestoreAdmin.ListFields with the filter set to +// indexConfig.usesAncestorConfig:false. +func (c *FirestoreAdminClient) ListFields(ctx context.Context, req *adminpb.ListFieldsRequest, opts ...gax.CallOption) *FieldIterator { + return c.internalClient.ListFields(ctx, req, opts...) +} + +// ExportDocuments exports a copy of all or a subset of documents from Google Cloud Firestore +// to another storage system, such as Google Cloud Storage. Recent updates to +// documents may not be reflected in the export. The export occurs in the +// background and its progress can be monitored and managed via the +// Operation resource that is created. The output of an export may only be +// used once the associated operation is done. If an export operation is +// cancelled before completion it may leave partial data behind in Google +// Cloud Storage. +func (c *FirestoreAdminClient) ExportDocuments(ctx context.Context, req *adminpb.ExportDocumentsRequest, opts ...gax.CallOption) (*ExportDocumentsOperation, error) { + return c.internalClient.ExportDocuments(ctx, req, opts...) +} + +// ExportDocumentsOperation returns a new ExportDocumentsOperation from a given name. +// The name must be that of a previously created ExportDocumentsOperation, possibly from a different process. +func (c *FirestoreAdminClient) ExportDocumentsOperation(name string) *ExportDocumentsOperation { + return c.internalClient.ExportDocumentsOperation(name) +} + +// ImportDocuments imports documents into Google Cloud Firestore. Existing documents with the +// same name are overwritten. The import occurs in the background and its +// progress can be monitored and managed via the Operation resource that is +// created. If an ImportDocuments operation is cancelled, it is possible +// that a subset of the data has already been imported to Cloud Firestore. +func (c *FirestoreAdminClient) ImportDocuments(ctx context.Context, req *adminpb.ImportDocumentsRequest, opts ...gax.CallOption) (*ImportDocumentsOperation, error) { + return c.internalClient.ImportDocuments(ctx, req, opts...) +} + +// ImportDocumentsOperation returns a new ImportDocumentsOperation from a given name. +// The name must be that of a previously created ImportDocumentsOperation, possibly from a different process. +func (c *FirestoreAdminClient) ImportDocumentsOperation(name string) *ImportDocumentsOperation { + return c.internalClient.ImportDocumentsOperation(name) +} + +// firestoreAdminGRPCClient is a client for interacting with Google Cloud Firestore Admin API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type firestoreAdminGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing FirestoreAdminClient + CallOptions **FirestoreAdminCallOptions + // The gRPC API client. firestoreAdminClient adminpb.FirestoreAdminClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *FirestoreAdminCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewFirestoreAdminClient creates a new firestore admin client. +// NewFirestoreAdminClient creates a new firestore admin client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Operations are created by service FirestoreAdmin, but are accessed via // service google.longrunning.Operations. func NewFirestoreAdminClient(ctx context.Context, opts ...option.ClientOption) (*FirestoreAdminClient, error) { - clientOpts := defaultFirestoreAdminClientOptions() - + clientOpts := defaultFirestoreAdminGRPCClientOptions() if newFirestoreAdminClientHook != nil { hookOpts, err := newFirestoreAdminClientHook(ctx, clientHookParams{}) if err != nil { @@ -188,16 +347,19 @@ func NewFirestoreAdminClient(ctx context.Context, opts ...option.ClientOption) ( if err != nil { return nil, err } - c := &FirestoreAdminClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultFirestoreAdminCallOptions(), + client := FirestoreAdminClient{CallOptions: defaultFirestoreAdminCallOptions()} + c := &firestoreAdminGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, firestoreAdminClient: adminpb.NewFirestoreAdminClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -207,35 +369,33 @@ func NewFirestoreAdminClient(ctx context.Context, opts ...option.ClientOption) ( // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *FirestoreAdminClient) Connection() *grpc.ClientConn { +func (c *firestoreAdminGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *FirestoreAdminClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *FirestoreAdminClient) setGoogleClientInfo(keyval ...string) { +func (c *firestoreAdminGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateIndex creates a composite index. This returns a google.longrunning.Operation -// which may be used to track the status of the creation. The metadata for -// the operation will be the type IndexOperationMetadata. -func (c *FirestoreAdminClient) CreateIndex(ctx context.Context, req *adminpb.CreateIndexRequest, opts ...gax.CallOption) (*CreateIndexOperation, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *firestoreAdminGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *firestoreAdminGRPCClient) CreateIndex(ctx context.Context, req *adminpb.CreateIndexRequest, opts ...gax.CallOption) (*CreateIndexOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -243,7 +403,7 @@ func (c *FirestoreAdminClient) CreateIndex(ctx context.Context, req *adminpb.Cre } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateIndex[0:len(c.CallOptions.CreateIndex):len(c.CallOptions.CreateIndex)], opts...) + opts = append((*c.CallOptions).CreateIndex[0:len((*c.CallOptions).CreateIndex):len((*c.CallOptions).CreateIndex)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -254,15 +414,14 @@ func (c *FirestoreAdminClient) CreateIndex(ctx context.Context, req *adminpb.Cre return nil, err } return &CreateIndexOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListIndexes lists composite indexes. -func (c *FirestoreAdminClient) ListIndexes(ctx context.Context, req *adminpb.ListIndexesRequest, opts ...gax.CallOption) *IndexIterator { +func (c *firestoreAdminGRPCClient) ListIndexes(ctx context.Context, req *adminpb.ListIndexesRequest, opts ...gax.CallOption) *IndexIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListIndexes[0:len(c.CallOptions.ListIndexes):len(c.CallOptions.ListIndexes)], opts...) + opts = append((*c.CallOptions).ListIndexes[0:len((*c.CallOptions).ListIndexes):len((*c.CallOptions).ListIndexes)], opts...) it := &IndexIterator{} req = proto.Clone(req).(*adminpb.ListIndexesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*adminpb.Index, string, error) { @@ -299,8 +458,7 @@ func (c *FirestoreAdminClient) ListIndexes(ctx context.Context, req *adminpb.Lis return it } -// GetIndex gets a composite index. -func (c *FirestoreAdminClient) GetIndex(ctx context.Context, req *adminpb.GetIndexRequest, opts ...gax.CallOption) (*adminpb.Index, error) { +func (c *firestoreAdminGRPCClient) GetIndex(ctx context.Context, req *adminpb.GetIndexRequest, opts ...gax.CallOption) (*adminpb.Index, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -308,7 +466,7 @@ func (c *FirestoreAdminClient) GetIndex(ctx context.Context, req *adminpb.GetInd } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIndex[0:len(c.CallOptions.GetIndex):len(c.CallOptions.GetIndex)], opts...) + opts = append((*c.CallOptions).GetIndex[0:len((*c.CallOptions).GetIndex):len((*c.CallOptions).GetIndex)], opts...) var resp *adminpb.Index err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -321,8 +479,7 @@ func (c *FirestoreAdminClient) GetIndex(ctx context.Context, req *adminpb.GetInd return resp, nil } -// DeleteIndex deletes a composite index. -func (c *FirestoreAdminClient) DeleteIndex(ctx context.Context, req *adminpb.DeleteIndexRequest, opts ...gax.CallOption) error { +func (c *firestoreAdminGRPCClient) DeleteIndex(ctx context.Context, req *adminpb.DeleteIndexRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -330,7 +487,7 @@ func (c *FirestoreAdminClient) DeleteIndex(ctx context.Context, req *adminpb.Del } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteIndex[0:len(c.CallOptions.DeleteIndex):len(c.CallOptions.DeleteIndex)], opts...) + opts = append((*c.CallOptions).DeleteIndex[0:len((*c.CallOptions).DeleteIndex):len((*c.CallOptions).DeleteIndex)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.firestoreAdminClient.DeleteIndex(ctx, req, settings.GRPC...) @@ -339,8 +496,7 @@ func (c *FirestoreAdminClient) DeleteIndex(ctx context.Context, req *adminpb.Del return err } -// GetField gets the metadata and configuration for a Field. -func (c *FirestoreAdminClient) GetField(ctx context.Context, req *adminpb.GetFieldRequest, opts ...gax.CallOption) (*adminpb.Field, error) { +func (c *firestoreAdminGRPCClient) GetField(ctx context.Context, req *adminpb.GetFieldRequest, opts ...gax.CallOption) (*adminpb.Field, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -348,7 +504,7 @@ func (c *FirestoreAdminClient) GetField(ctx context.Context, req *adminpb.GetFie } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetField[0:len(c.CallOptions.GetField):len(c.CallOptions.GetField)], opts...) + opts = append((*c.CallOptions).GetField[0:len((*c.CallOptions).GetField):len((*c.CallOptions).GetField)], opts...) var resp *adminpb.Field err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -361,20 +517,7 @@ func (c *FirestoreAdminClient) GetField(ctx context.Context, req *adminpb.GetFie return resp, nil } -// UpdateField updates a field configuration. Currently, field updates apply only to -// single field index configuration. However, calls to -// FirestoreAdmin.UpdateField should provide a field mask to avoid -// changing any configuration that the caller isn’t aware of. The field mask -// should be specified as: { paths: "index_config" }. -// -// This call returns a google.longrunning.Operation which may be used to -// track the status of the field update. The metadata for -// the operation will be the type FieldOperationMetadata. -// -// To configure the default field settings for the database, use -// the special Field with resource name: -// projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/*. -func (c *FirestoreAdminClient) UpdateField(ctx context.Context, req *adminpb.UpdateFieldRequest, opts ...gax.CallOption) (*UpdateFieldOperation, error) { +func (c *firestoreAdminGRPCClient) UpdateField(ctx context.Context, req *adminpb.UpdateFieldRequest, opts ...gax.CallOption) (*UpdateFieldOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -382,7 +525,7 @@ func (c *FirestoreAdminClient) UpdateField(ctx context.Context, req *adminpb.Upd } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "field.name", url.QueryEscape(req.GetField().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateField[0:len(c.CallOptions.UpdateField):len(c.CallOptions.UpdateField)], opts...) + opts = append((*c.CallOptions).UpdateField[0:len((*c.CallOptions).UpdateField):len((*c.CallOptions).UpdateField)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -393,20 +536,14 @@ func (c *FirestoreAdminClient) UpdateField(ctx context.Context, req *adminpb.Upd return nil, err } return &UpdateFieldOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListFields lists the field configuration and metadata for this database. -// -// Currently, FirestoreAdmin.ListFields only supports listing fields -// that have been explicitly overridden. To issue this query, call -// FirestoreAdmin.ListFields with the filter set to -// indexConfig.usesAncestorConfig:false. -func (c *FirestoreAdminClient) ListFields(ctx context.Context, req *adminpb.ListFieldsRequest, opts ...gax.CallOption) *FieldIterator { +func (c *firestoreAdminGRPCClient) ListFields(ctx context.Context, req *adminpb.ListFieldsRequest, opts ...gax.CallOption) *FieldIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListFields[0:len(c.CallOptions.ListFields):len(c.CallOptions.ListFields)], opts...) + opts = append((*c.CallOptions).ListFields[0:len((*c.CallOptions).ListFields):len((*c.CallOptions).ListFields)], opts...) it := &FieldIterator{} req = proto.Clone(req).(*adminpb.ListFieldsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*adminpb.Field, string, error) { @@ -443,15 +580,7 @@ func (c *FirestoreAdminClient) ListFields(ctx context.Context, req *adminpb.List return it } -// ExportDocuments exports a copy of all or a subset of documents from Google Cloud Firestore -// to another storage system, such as Google Cloud Storage. Recent updates to -// documents may not be reflected in the export. The export occurs in the -// background and its progress can be monitored and managed via the -// Operation resource that is created. The output of an export may only be -// used once the associated operation is done. If an export operation is -// cancelled before completion it may leave partial data behind in Google -// Cloud Storage. -func (c *FirestoreAdminClient) ExportDocuments(ctx context.Context, req *adminpb.ExportDocumentsRequest, opts ...gax.CallOption) (*ExportDocumentsOperation, error) { +func (c *firestoreAdminGRPCClient) ExportDocuments(ctx context.Context, req *adminpb.ExportDocumentsRequest, opts ...gax.CallOption) (*ExportDocumentsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -459,7 +588,7 @@ func (c *FirestoreAdminClient) ExportDocuments(ctx context.Context, req *adminpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportDocuments[0:len(c.CallOptions.ExportDocuments):len(c.CallOptions.ExportDocuments)], opts...) + opts = append((*c.CallOptions).ExportDocuments[0:len((*c.CallOptions).ExportDocuments):len((*c.CallOptions).ExportDocuments)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -470,16 +599,11 @@ func (c *FirestoreAdminClient) ExportDocuments(ctx context.Context, req *adminpb return nil, err } return &ExportDocumentsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ImportDocuments imports documents into Google Cloud Firestore. Existing documents with the -// same name are overwritten. The import occurs in the background and its -// progress can be monitored and managed via the Operation resource that is -// created. If an ImportDocuments operation is cancelled, it is possible -// that a subset of the data has already been imported to Cloud Firestore. -func (c *FirestoreAdminClient) ImportDocuments(ctx context.Context, req *adminpb.ImportDocumentsRequest, opts ...gax.CallOption) (*ImportDocumentsOperation, error) { +func (c *firestoreAdminGRPCClient) ImportDocuments(ctx context.Context, req *adminpb.ImportDocumentsRequest, opts ...gax.CallOption) (*ImportDocumentsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -487,7 +611,7 @@ func (c *FirestoreAdminClient) ImportDocuments(ctx context.Context, req *adminpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportDocuments[0:len(c.CallOptions.ImportDocuments):len(c.CallOptions.ImportDocuments)], opts...) + opts = append((*c.CallOptions).ImportDocuments[0:len((*c.CallOptions).ImportDocuments):len((*c.CallOptions).ImportDocuments)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -498,7 +622,7 @@ func (c *FirestoreAdminClient) ImportDocuments(ctx context.Context, req *adminpb return nil, err } return &ImportDocumentsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -509,9 +633,9 @@ type CreateIndexOperation struct { // CreateIndexOperation returns a new CreateIndexOperation from a given name. // The name must be that of a previously created CreateIndexOperation, possibly from a different process. -func (c *FirestoreAdminClient) CreateIndexOperation(name string) *CreateIndexOperation { +func (c *firestoreAdminGRPCClient) CreateIndexOperation(name string) *CreateIndexOperation { return &CreateIndexOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -578,9 +702,9 @@ type ExportDocumentsOperation struct { // ExportDocumentsOperation returns a new ExportDocumentsOperation from a given name. // The name must be that of a previously created ExportDocumentsOperation, possibly from a different process. -func (c *FirestoreAdminClient) ExportDocumentsOperation(name string) *ExportDocumentsOperation { +func (c *firestoreAdminGRPCClient) ExportDocumentsOperation(name string) *ExportDocumentsOperation { return &ExportDocumentsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -647,9 +771,9 @@ type ImportDocumentsOperation struct { // ImportDocumentsOperation returns a new ImportDocumentsOperation from a given name. // The name must be that of a previously created ImportDocumentsOperation, possibly from a different process. -func (c *FirestoreAdminClient) ImportDocumentsOperation(name string) *ImportDocumentsOperation { +func (c *firestoreAdminGRPCClient) ImportDocumentsOperation(name string) *ImportDocumentsOperation { return &ImportDocumentsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -705,9 +829,9 @@ type UpdateFieldOperation struct { // UpdateFieldOperation returns a new UpdateFieldOperation from a given name. // The name must be that of a previously created UpdateFieldOperation, possibly from a different process. -func (c *FirestoreAdminClient) UpdateFieldOperation(name string) *UpdateFieldOperation { +func (c *firestoreAdminGRPCClient) UpdateFieldOperation(name string) *UpdateFieldOperation { return &UpdateFieldOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/firestore/apiv1/admin/firestore_admin_client_example_test.go b/firestore/apiv1/admin/firestore_admin_client_example_test.go index acf65516d567..0f42a45b7d8a 100644 --- a/firestore/apiv1/admin/firestore_admin_client_example_test.go +++ b/firestore/apiv1/admin/firestore_admin_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewFirestoreAdminClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleFirestoreAdminClient_CreateIndex() { - // import adminpb "google.golang.org/genproto/googleapis/firestore/admin/v1" - ctx := context.Background() c, err := apiv1.NewFirestoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.CreateIndexRequest{ // TODO: Fill request struct fields. @@ -60,14 +61,12 @@ func ExampleFirestoreAdminClient_CreateIndex() { } func ExampleFirestoreAdminClient_ListIndexes() { - // import adminpb "google.golang.org/genproto/googleapis/firestore/admin/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := apiv1.NewFirestoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListIndexesRequest{ // TODO: Fill request struct fields. @@ -87,13 +86,12 @@ func ExampleFirestoreAdminClient_ListIndexes() { } func ExampleFirestoreAdminClient_GetIndex() { - // import adminpb "google.golang.org/genproto/googleapis/firestore/admin/v1" - ctx := context.Background() c, err := apiv1.NewFirestoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetIndexRequest{ // TODO: Fill request struct fields. @@ -112,6 +110,7 @@ func ExampleFirestoreAdminClient_DeleteIndex() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteIndexRequest{ // TODO: Fill request struct fields. @@ -123,13 +122,12 @@ func ExampleFirestoreAdminClient_DeleteIndex() { } func ExampleFirestoreAdminClient_GetField() { - // import adminpb "google.golang.org/genproto/googleapis/firestore/admin/v1" - ctx := context.Background() c, err := apiv1.NewFirestoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetFieldRequest{ // TODO: Fill request struct fields. @@ -143,13 +141,12 @@ func ExampleFirestoreAdminClient_GetField() { } func ExampleFirestoreAdminClient_UpdateField() { - // import adminpb "google.golang.org/genproto/googleapis/firestore/admin/v1" - ctx := context.Background() c, err := apiv1.NewFirestoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateFieldRequest{ // TODO: Fill request struct fields. @@ -168,14 +165,12 @@ func ExampleFirestoreAdminClient_UpdateField() { } func ExampleFirestoreAdminClient_ListFields() { - // import adminpb "google.golang.org/genproto/googleapis/firestore/admin/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := apiv1.NewFirestoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListFieldsRequest{ // TODO: Fill request struct fields. @@ -195,13 +190,12 @@ func ExampleFirestoreAdminClient_ListFields() { } func ExampleFirestoreAdminClient_ExportDocuments() { - // import adminpb "google.golang.org/genproto/googleapis/firestore/admin/v1" - ctx := context.Background() c, err := apiv1.NewFirestoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ExportDocumentsRequest{ // TODO: Fill request struct fields. @@ -220,13 +214,12 @@ func ExampleFirestoreAdminClient_ExportDocuments() { } func ExampleFirestoreAdminClient_ImportDocuments() { - // import adminpb "google.golang.org/genproto/googleapis/firestore/admin/v1" - ctx := context.Background() c, err := apiv1.NewFirestoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ImportDocumentsRequest{ // TODO: Fill request struct fields. diff --git a/firestore/apiv1/doc.go b/firestore/apiv1/doc.go index 98fe53584672..111038ac6e58 100644 --- a/firestore/apiv1/doc.go +++ b/firestore/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package firestore // import "cloud.google.com/go/firestore/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/firestore/apiv1/firestore_client.go b/firestore/apiv1/firestore_client.go index 2a950039fd5b..f6084b6aa806 100644 --- a/firestore/apiv1/firestore_client.go +++ b/firestore/apiv1/firestore_client.go @@ -56,7 +56,7 @@ type CallOptions struct { CreateDocument []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("firestore.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("firestore.mtls.googleapis.com:443"), @@ -263,27 +263,179 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Firestore API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + GetDocument(context.Context, *firestorepb.GetDocumentRequest, ...gax.CallOption) (*firestorepb.Document, error) + ListDocuments(context.Context, *firestorepb.ListDocumentsRequest, ...gax.CallOption) *DocumentIterator + UpdateDocument(context.Context, *firestorepb.UpdateDocumentRequest, ...gax.CallOption) (*firestorepb.Document, error) + DeleteDocument(context.Context, *firestorepb.DeleteDocumentRequest, ...gax.CallOption) error + BatchGetDocuments(context.Context, *firestorepb.BatchGetDocumentsRequest, ...gax.CallOption) (firestorepb.Firestore_BatchGetDocumentsClient, error) + BeginTransaction(context.Context, *firestorepb.BeginTransactionRequest, ...gax.CallOption) (*firestorepb.BeginTransactionResponse, error) + Commit(context.Context, *firestorepb.CommitRequest, ...gax.CallOption) (*firestorepb.CommitResponse, error) + Rollback(context.Context, *firestorepb.RollbackRequest, ...gax.CallOption) error + RunQuery(context.Context, *firestorepb.RunQueryRequest, ...gax.CallOption) (firestorepb.Firestore_RunQueryClient, error) + PartitionQuery(context.Context, *firestorepb.PartitionQueryRequest, ...gax.CallOption) *CursorIterator + Write(context.Context, ...gax.CallOption) (firestorepb.Firestore_WriteClient, error) + Listen(context.Context, ...gax.CallOption) (firestorepb.Firestore_ListenClient, error) + ListCollectionIds(context.Context, *firestorepb.ListCollectionIdsRequest, ...gax.CallOption) *StringIterator + BatchWrite(context.Context, *firestorepb.BatchWriteRequest, ...gax.CallOption) (*firestorepb.BatchWriteResponse, error) + CreateDocument(context.Context, *firestorepb.CreateDocumentRequest, ...gax.CallOption) (*firestorepb.Document, error) +} + // Client is a client for interacting with Cloud Firestore API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The Cloud Firestore service. +// +// Cloud Firestore is a fast, fully managed, serverless, cloud-native NoSQL +// document database that simplifies storing, syncing, and querying data for +// your mobile, web, and IoT apps at global scale. Its client libraries provide +// live synchronization and offline support, while its security features and +// integrations with Firebase and Google Cloud Platform (GCP) accelerate +// building truly serverless apps. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// GetDocument gets a single document. +func (c *Client) GetDocument(ctx context.Context, req *firestorepb.GetDocumentRequest, opts ...gax.CallOption) (*firestorepb.Document, error) { + return c.internalClient.GetDocument(ctx, req, opts...) +} + +// ListDocuments lists documents. +func (c *Client) ListDocuments(ctx context.Context, req *firestorepb.ListDocumentsRequest, opts ...gax.CallOption) *DocumentIterator { + return c.internalClient.ListDocuments(ctx, req, opts...) +} + +// UpdateDocument updates or inserts a document. +func (c *Client) UpdateDocument(ctx context.Context, req *firestorepb.UpdateDocumentRequest, opts ...gax.CallOption) (*firestorepb.Document, error) { + return c.internalClient.UpdateDocument(ctx, req, opts...) +} + +// DeleteDocument deletes a document. +func (c *Client) DeleteDocument(ctx context.Context, req *firestorepb.DeleteDocumentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteDocument(ctx, req, opts...) +} + +// BatchGetDocuments gets multiple documents. +// +// Documents returned by this method are not guaranteed to be returned in the +// same order that they were requested. +func (c *Client) BatchGetDocuments(ctx context.Context, req *firestorepb.BatchGetDocumentsRequest, opts ...gax.CallOption) (firestorepb.Firestore_BatchGetDocumentsClient, error) { + return c.internalClient.BatchGetDocuments(ctx, req, opts...) +} + +// BeginTransaction starts a new transaction. +func (c *Client) BeginTransaction(ctx context.Context, req *firestorepb.BeginTransactionRequest, opts ...gax.CallOption) (*firestorepb.BeginTransactionResponse, error) { + return c.internalClient.BeginTransaction(ctx, req, opts...) +} + +// Commit commits a transaction, while optionally updating documents. +func (c *Client) Commit(ctx context.Context, req *firestorepb.CommitRequest, opts ...gax.CallOption) (*firestorepb.CommitResponse, error) { + return c.internalClient.Commit(ctx, req, opts...) +} + +// Rollback rolls back a transaction. +func (c *Client) Rollback(ctx context.Context, req *firestorepb.RollbackRequest, opts ...gax.CallOption) error { + return c.internalClient.Rollback(ctx, req, opts...) +} + +// RunQuery runs a query. +func (c *Client) RunQuery(ctx context.Context, req *firestorepb.RunQueryRequest, opts ...gax.CallOption) (firestorepb.Firestore_RunQueryClient, error) { + return c.internalClient.RunQuery(ctx, req, opts...) +} + +// PartitionQuery partitions a query by returning partition cursors that can be used to run +// the query in parallel. The returned partition cursors are split points that +// can be used by RunQuery as starting/end points for the query results. +func (c *Client) PartitionQuery(ctx context.Context, req *firestorepb.PartitionQueryRequest, opts ...gax.CallOption) *CursorIterator { + return c.internalClient.PartitionQuery(ctx, req, opts...) +} + +// Write streams batches of document updates and deletes, in order. +func (c *Client) Write(ctx context.Context, opts ...gax.CallOption) (firestorepb.Firestore_WriteClient, error) { + return c.internalClient.Write(ctx, opts...) +} + +// Listen listens to changes. +func (c *Client) Listen(ctx context.Context, opts ...gax.CallOption) (firestorepb.Firestore_ListenClient, error) { + return c.internalClient.Listen(ctx, opts...) +} + +// ListCollectionIds lists all the collection IDs underneath a document. +func (c *Client) ListCollectionIds(ctx context.Context, req *firestorepb.ListCollectionIdsRequest, opts ...gax.CallOption) *StringIterator { + return c.internalClient.ListCollectionIds(ctx, req, opts...) +} + +// BatchWrite applies a batch of write operations. +// +// The BatchWrite method does not apply the write operations atomically +// and can apply them out of order. Method does not allow more than one write +// per document. Each write succeeds or fails independently. See the +// BatchWriteResponse for the success status of each write. +// +// If you require an atomically applied set of writes, use +// Commit instead. +func (c *Client) BatchWrite(ctx context.Context, req *firestorepb.BatchWriteRequest, opts ...gax.CallOption) (*firestorepb.BatchWriteResponse, error) { + return c.internalClient.BatchWrite(ctx, req, opts...) +} + +// CreateDocument creates a new document. +func (c *Client) CreateDocument(ctx context.Context, req *firestorepb.CreateDocumentRequest, opts ...gax.CallOption) (*firestorepb.Document, error) { + return c.internalClient.CreateDocument(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud Firestore API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client firestorepb.FirestoreClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new firestore client. +// NewClient creates a new firestore client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The Cloud Firestore service. // @@ -294,8 +446,7 @@ type Client struct { // integrations with Firebase and Google Cloud Platform (GCP) accelerate // building truly serverless apps. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -313,42 +464,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: firestorepb.NewFirestoreClient(connPool), + client: firestorepb.NewFirestoreClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// GetDocument gets a single document. -func (c *Client) GetDocument(ctx context.Context, req *firestorepb.GetDocumentRequest, opts ...gax.CallOption) (*firestorepb.Document, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) GetDocument(ctx context.Context, req *firestorepb.GetDocumentRequest, opts ...gax.CallOption) (*firestorepb.Document, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -356,7 +509,7 @@ func (c *Client) GetDocument(ctx context.Context, req *firestorepb.GetDocumentRe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetDocument[0:len(c.CallOptions.GetDocument):len(c.CallOptions.GetDocument)], opts...) + opts = append((*c.CallOptions).GetDocument[0:len((*c.CallOptions).GetDocument):len((*c.CallOptions).GetDocument)], opts...) var resp *firestorepb.Document err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -369,11 +522,10 @@ func (c *Client) GetDocument(ctx context.Context, req *firestorepb.GetDocumentRe return resp, nil } -// ListDocuments lists documents. -func (c *Client) ListDocuments(ctx context.Context, req *firestorepb.ListDocumentsRequest, opts ...gax.CallOption) *DocumentIterator { +func (c *gRPCClient) ListDocuments(ctx context.Context, req *firestorepb.ListDocumentsRequest, opts ...gax.CallOption) *DocumentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "parent", url.QueryEscape(req.GetParent()), "collection_id", url.QueryEscape(req.GetCollectionId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDocuments[0:len(c.CallOptions.ListDocuments):len(c.CallOptions.ListDocuments)], opts...) + opts = append((*c.CallOptions).ListDocuments[0:len((*c.CallOptions).ListDocuments):len((*c.CallOptions).ListDocuments)], opts...) it := &DocumentIterator{} req = proto.Clone(req).(*firestorepb.ListDocumentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*firestorepb.Document, string, error) { @@ -410,8 +562,7 @@ func (c *Client) ListDocuments(ctx context.Context, req *firestorepb.ListDocumen return it } -// UpdateDocument updates or inserts a document. -func (c *Client) UpdateDocument(ctx context.Context, req *firestorepb.UpdateDocumentRequest, opts ...gax.CallOption) (*firestorepb.Document, error) { +func (c *gRPCClient) UpdateDocument(ctx context.Context, req *firestorepb.UpdateDocumentRequest, opts ...gax.CallOption) (*firestorepb.Document, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -419,7 +570,7 @@ func (c *Client) UpdateDocument(ctx context.Context, req *firestorepb.UpdateDocu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "document.name", url.QueryEscape(req.GetDocument().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateDocument[0:len(c.CallOptions.UpdateDocument):len(c.CallOptions.UpdateDocument)], opts...) + opts = append((*c.CallOptions).UpdateDocument[0:len((*c.CallOptions).UpdateDocument):len((*c.CallOptions).UpdateDocument)], opts...) var resp *firestorepb.Document err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -432,8 +583,7 @@ func (c *Client) UpdateDocument(ctx context.Context, req *firestorepb.UpdateDocu return resp, nil } -// DeleteDocument deletes a document. -func (c *Client) DeleteDocument(ctx context.Context, req *firestorepb.DeleteDocumentRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteDocument(ctx context.Context, req *firestorepb.DeleteDocumentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -441,7 +591,7 @@ func (c *Client) DeleteDocument(ctx context.Context, req *firestorepb.DeleteDocu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteDocument[0:len(c.CallOptions.DeleteDocument):len(c.CallOptions.DeleteDocument)], opts...) + opts = append((*c.CallOptions).DeleteDocument[0:len((*c.CallOptions).DeleteDocument):len((*c.CallOptions).DeleteDocument)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteDocument(ctx, req, settings.GRPC...) @@ -450,14 +600,9 @@ func (c *Client) DeleteDocument(ctx context.Context, req *firestorepb.DeleteDocu return err } -// BatchGetDocuments gets multiple documents. -// -// Documents returned by this method are not guaranteed to be returned in the -// same order that they were requested. -func (c *Client) BatchGetDocuments(ctx context.Context, req *firestorepb.BatchGetDocumentsRequest, opts ...gax.CallOption) (firestorepb.Firestore_BatchGetDocumentsClient, error) { +func (c *gRPCClient) BatchGetDocuments(ctx context.Context, req *firestorepb.BatchGetDocumentsRequest, opts ...gax.CallOption) (firestorepb.Firestore_BatchGetDocumentsClient, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchGetDocuments[0:len(c.CallOptions.BatchGetDocuments):len(c.CallOptions.BatchGetDocuments)], opts...) var resp firestorepb.Firestore_BatchGetDocumentsClient err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -470,8 +615,7 @@ func (c *Client) BatchGetDocuments(ctx context.Context, req *firestorepb.BatchGe return resp, nil } -// BeginTransaction starts a new transaction. -func (c *Client) BeginTransaction(ctx context.Context, req *firestorepb.BeginTransactionRequest, opts ...gax.CallOption) (*firestorepb.BeginTransactionResponse, error) { +func (c *gRPCClient) BeginTransaction(ctx context.Context, req *firestorepb.BeginTransactionRequest, opts ...gax.CallOption) (*firestorepb.BeginTransactionResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -479,7 +623,7 @@ func (c *Client) BeginTransaction(ctx context.Context, req *firestorepb.BeginTra } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BeginTransaction[0:len(c.CallOptions.BeginTransaction):len(c.CallOptions.BeginTransaction)], opts...) + opts = append((*c.CallOptions).BeginTransaction[0:len((*c.CallOptions).BeginTransaction):len((*c.CallOptions).BeginTransaction)], opts...) var resp *firestorepb.BeginTransactionResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -492,8 +636,7 @@ func (c *Client) BeginTransaction(ctx context.Context, req *firestorepb.BeginTra return resp, nil } -// Commit commits a transaction, while optionally updating documents. -func (c *Client) Commit(ctx context.Context, req *firestorepb.CommitRequest, opts ...gax.CallOption) (*firestorepb.CommitResponse, error) { +func (c *gRPCClient) Commit(ctx context.Context, req *firestorepb.CommitRequest, opts ...gax.CallOption) (*firestorepb.CommitResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -501,7 +644,7 @@ func (c *Client) Commit(ctx context.Context, req *firestorepb.CommitRequest, opt } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.Commit[0:len(c.CallOptions.Commit):len(c.CallOptions.Commit)], opts...) + opts = append((*c.CallOptions).Commit[0:len((*c.CallOptions).Commit):len((*c.CallOptions).Commit)], opts...) var resp *firestorepb.CommitResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -514,8 +657,7 @@ func (c *Client) Commit(ctx context.Context, req *firestorepb.CommitRequest, opt return resp, nil } -// Rollback rolls back a transaction. -func (c *Client) Rollback(ctx context.Context, req *firestorepb.RollbackRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) Rollback(ctx context.Context, req *firestorepb.RollbackRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -523,7 +665,7 @@ func (c *Client) Rollback(ctx context.Context, req *firestorepb.RollbackRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.Rollback[0:len(c.CallOptions.Rollback):len(c.CallOptions.Rollback)], opts...) + opts = append((*c.CallOptions).Rollback[0:len((*c.CallOptions).Rollback):len((*c.CallOptions).Rollback)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.Rollback(ctx, req, settings.GRPC...) @@ -532,11 +674,9 @@ func (c *Client) Rollback(ctx context.Context, req *firestorepb.RollbackRequest, return err } -// RunQuery runs a query. -func (c *Client) RunQuery(ctx context.Context, req *firestorepb.RunQueryRequest, opts ...gax.CallOption) (firestorepb.Firestore_RunQueryClient, error) { +func (c *gRPCClient) RunQuery(ctx context.Context, req *firestorepb.RunQueryRequest, opts ...gax.CallOption) (firestorepb.Firestore_RunQueryClient, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RunQuery[0:len(c.CallOptions.RunQuery):len(c.CallOptions.RunQuery)], opts...) var resp firestorepb.Firestore_RunQueryClient err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -549,13 +689,10 @@ func (c *Client) RunQuery(ctx context.Context, req *firestorepb.RunQueryRequest, return resp, nil } -// PartitionQuery partitions a query by returning partition cursors that can be used to run -// the query in parallel. The returned partition cursors are split points that -// can be used by RunQuery as starting/end points for the query results. -func (c *Client) PartitionQuery(ctx context.Context, req *firestorepb.PartitionQueryRequest, opts ...gax.CallOption) *CursorIterator { +func (c *gRPCClient) PartitionQuery(ctx context.Context, req *firestorepb.PartitionQueryRequest, opts ...gax.CallOption) *CursorIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PartitionQuery[0:len(c.CallOptions.PartitionQuery):len(c.CallOptions.PartitionQuery)], opts...) + opts = append((*c.CallOptions).PartitionQuery[0:len((*c.CallOptions).PartitionQuery):len((*c.CallOptions).PartitionQuery)], opts...) it := &CursorIterator{} req = proto.Clone(req).(*firestorepb.PartitionQueryRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*firestorepb.Cursor, string, error) { @@ -592,11 +729,10 @@ func (c *Client) PartitionQuery(ctx context.Context, req *firestorepb.PartitionQ return it } -// Write streams batches of document updates and deletes, in order. -func (c *Client) Write(ctx context.Context, opts ...gax.CallOption) (firestorepb.Firestore_WriteClient, error) { +func (c *gRPCClient) Write(ctx context.Context, opts ...gax.CallOption) (firestorepb.Firestore_WriteClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.Write[0:len(c.CallOptions.Write):len(c.CallOptions.Write)], opts...) var resp firestorepb.Firestore_WriteClient + opts = append((*c.CallOptions).Write[0:len((*c.CallOptions).Write):len((*c.CallOptions).Write)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.client.Write(ctx, settings.GRPC...) @@ -608,11 +744,10 @@ func (c *Client) Write(ctx context.Context, opts ...gax.CallOption) (firestorepb return resp, nil } -// Listen listens to changes. -func (c *Client) Listen(ctx context.Context, opts ...gax.CallOption) (firestorepb.Firestore_ListenClient, error) { +func (c *gRPCClient) Listen(ctx context.Context, opts ...gax.CallOption) (firestorepb.Firestore_ListenClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.Listen[0:len(c.CallOptions.Listen):len(c.CallOptions.Listen)], opts...) var resp firestorepb.Firestore_ListenClient + opts = append((*c.CallOptions).Listen[0:len((*c.CallOptions).Listen):len((*c.CallOptions).Listen)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.client.Listen(ctx, settings.GRPC...) @@ -624,11 +759,10 @@ func (c *Client) Listen(ctx context.Context, opts ...gax.CallOption) (firestorep return resp, nil } -// ListCollectionIds lists all the collection IDs underneath a document. -func (c *Client) ListCollectionIds(ctx context.Context, req *firestorepb.ListCollectionIdsRequest, opts ...gax.CallOption) *StringIterator { +func (c *gRPCClient) ListCollectionIds(ctx context.Context, req *firestorepb.ListCollectionIdsRequest, opts ...gax.CallOption) *StringIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCollectionIds[0:len(c.CallOptions.ListCollectionIds):len(c.CallOptions.ListCollectionIds)], opts...) + opts = append((*c.CallOptions).ListCollectionIds[0:len((*c.CallOptions).ListCollectionIds):len((*c.CallOptions).ListCollectionIds)], opts...) it := &StringIterator{} req = proto.Clone(req).(*firestorepb.ListCollectionIdsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]string, string, error) { @@ -665,16 +799,7 @@ func (c *Client) ListCollectionIds(ctx context.Context, req *firestorepb.ListCol return it } -// BatchWrite applies a batch of write operations. -// -// The BatchWrite method does not apply the write operations atomically -// and can apply them out of order. Method does not allow more than one write -// per document. Each write succeeds or fails independently. See the -// BatchWriteResponse for the success status of each write. -// -// If you require an atomically applied set of writes, use -// Commit instead. -func (c *Client) BatchWrite(ctx context.Context, req *firestorepb.BatchWriteRequest, opts ...gax.CallOption) (*firestorepb.BatchWriteResponse, error) { +func (c *gRPCClient) BatchWrite(ctx context.Context, req *firestorepb.BatchWriteRequest, opts ...gax.CallOption) (*firestorepb.BatchWriteResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -682,7 +807,7 @@ func (c *Client) BatchWrite(ctx context.Context, req *firestorepb.BatchWriteRequ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchWrite[0:len(c.CallOptions.BatchWrite):len(c.CallOptions.BatchWrite)], opts...) + opts = append((*c.CallOptions).BatchWrite[0:len((*c.CallOptions).BatchWrite):len((*c.CallOptions).BatchWrite)], opts...) var resp *firestorepb.BatchWriteResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -695,8 +820,7 @@ func (c *Client) BatchWrite(ctx context.Context, req *firestorepb.BatchWriteRequ return resp, nil } -// CreateDocument creates a new document. -func (c *Client) CreateDocument(ctx context.Context, req *firestorepb.CreateDocumentRequest, opts ...gax.CallOption) (*firestorepb.Document, error) { +func (c *gRPCClient) CreateDocument(ctx context.Context, req *firestorepb.CreateDocumentRequest, opts ...gax.CallOption) (*firestorepb.Document, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -704,7 +828,7 @@ func (c *Client) CreateDocument(ctx context.Context, req *firestorepb.CreateDocu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "parent", url.QueryEscape(req.GetParent()), "collection_id", url.QueryEscape(req.GetCollectionId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateDocument[0:len(c.CallOptions.CreateDocument):len(c.CallOptions.CreateDocument)], opts...) + opts = append((*c.CallOptions).CreateDocument[0:len((*c.CallOptions).CreateDocument):len((*c.CallOptions).CreateDocument)], opts...) var resp *firestorepb.Document err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/firestore/apiv1/firestore_client_example_test.go b/firestore/apiv1/firestore_client_example_test.go index f991d808d633..1e997e6d1887 100644 --- a/firestore/apiv1/firestore_client_example_test.go +++ b/firestore/apiv1/firestore_client_example_test.go @@ -31,18 +31,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_GetDocument() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.GetDocumentRequest{ // TODO: Fill request struct fields. @@ -56,14 +57,12 @@ func ExampleClient_GetDocument() { } func ExampleClient_ListDocuments() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.ListDocumentsRequest{ // TODO: Fill request struct fields. @@ -83,13 +82,12 @@ func ExampleClient_ListDocuments() { } func ExampleClient_UpdateDocument() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.UpdateDocumentRequest{ // TODO: Fill request struct fields. @@ -108,6 +106,7 @@ func ExampleClient_DeleteDocument() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.DeleteDocumentRequest{ // TODO: Fill request struct fields. @@ -119,13 +118,12 @@ func ExampleClient_DeleteDocument() { } func ExampleClient_BeginTransaction() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.BeginTransactionRequest{ // TODO: Fill request struct fields. @@ -139,13 +137,12 @@ func ExampleClient_BeginTransaction() { } func ExampleClient_Commit() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.CommitRequest{ // TODO: Fill request struct fields. @@ -164,6 +161,7 @@ func ExampleClient_Rollback() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.RollbackRequest{ // TODO: Fill request struct fields. @@ -175,14 +173,12 @@ func ExampleClient_Rollback() { } func ExampleClient_PartitionQuery() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.PartitionQueryRequest{ // TODO: Fill request struct fields. @@ -202,13 +198,12 @@ func ExampleClient_PartitionQuery() { } func ExampleClient_Write() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.Write(ctx) if err != nil { // TODO: Handle error. @@ -238,13 +233,12 @@ func ExampleClient_Write() { } func ExampleClient_Listen() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.Listen(ctx) if err != nil { // TODO: Handle error. @@ -274,14 +268,12 @@ func ExampleClient_Listen() { } func ExampleClient_ListCollectionIds() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.ListCollectionIdsRequest{ // TODO: Fill request struct fields. @@ -301,13 +293,12 @@ func ExampleClient_ListCollectionIds() { } func ExampleClient_BatchWrite() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.BatchWriteRequest{ // TODO: Fill request struct fields. @@ -321,13 +312,12 @@ func ExampleClient_BatchWrite() { } func ExampleClient_CreateDocument() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.CreateDocumentRequest{ // TODO: Fill request struct fields. diff --git a/firestore/go.mod b/firestore/go.mod index 339bea6e9e83..3bcf9fd2507c 100644 --- a/firestore/go.mod +++ b/firestore/go.mod @@ -7,7 +7,7 @@ require ( github.com/golang/protobuf v1.5.2 github.com/google/go-cmp v0.5.5 github.com/googleapis/gax-go/v2 v2.0.5 - google.golang.org/api v0.46.0 - google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a + google.golang.org/api v0.47.0 + google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d google.golang.org/grpc v1.37.1 ) diff --git a/firestore/go.sum b/firestore/go.sum index 21f3a0377fc0..259241ea7f17 100644 --- a/firestore/go.sum +++ b/firestore/go.sum @@ -144,6 +144,7 @@ github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -179,8 +180,9 @@ golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5 h1:2M3HP5CCK1Si9FQhwnzYhXdG6DXeebvUHFpre8QvbyI= golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 h1:VLliZ0d+/avPrXXH+OakdXhpJuEoBZuwh1m2j7U6Iug= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= @@ -190,8 +192,9 @@ golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.1 h1:Kvvh58BN8Y9/lBi7hTekvtMpm07eUZ0ck5pRHpsMWrY= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -225,6 +228,7 @@ golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420 h1:a8jGStKg0XqKDlKqjLrXn0ioF5MH36pT7Z0BRTqLhbk= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -238,8 +242,8 @@ golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210427180440-81ed05c6b58c h1:SgVl/sCtkicsS7psKkje4H9YtjdEl3xsYh7N+5TDHqY= -golang.org/x/oauth2 v0.0.0-20210427180440-81ed05c6b58c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c h1:pkQiBZBvdos9qq4wBAHqlzuZHEXo07pqV06ef90u1WI= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -286,9 +290,11 @@ golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210503080704-8803ae5d1324 h1:pAwJxDByZctfPwzlNGrDN2BQLsdPb9NkhoTJtUkAO28= -golang.org/x/sys v0.0.0-20210503080704-8803ae5d1324/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015 h1:hZR0X1kPW+nwyJ9xRxqZk1vx5RUObAPBdKVvXPDUH/E= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -347,8 +353,9 @@ golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.0 h1:po9/4sTYwZU9lPhi1tOrb4hCv3qrhiQ77LZfGa2OjwY= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.1 h1:wGiQel/hW0NnEkJUk8lbzkX2gFJU6PFxf1v5OlCfuOs= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -375,8 +382,8 @@ google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34q google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= -google.golang.org/api v0.46.0 h1:jkDWHOBIoNSD0OQpq4rtBVu+Rh325MPjXG1rakAp8JU= -google.golang.org/api v0.46.0/go.mod h1:ceL4oozhkAiTID8XMmJBsIxID/9wMXJVVFXPg4ylg3I= +google.golang.org/api v0.47.0 h1:sQLWZQvP6jPGIP4JGPkJu4zHswrv81iobiyszr3b/0I= +google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -424,9 +431,9 @@ google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= -google.golang.org/genproto v0.0.0-20210429181445-86c259c2b4ab/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= -google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a h1:VA0wtJaR+W1I11P2f535J7D/YxyvEFMTMvcmyeZ9FBE= -google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d h1:bRz6UmsZEz/CzoTjUDp4ZcdguhSWi6CyU299wMQBpZU= +google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= @@ -445,7 +452,6 @@ google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA5 google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.37.1 h1:ARnQJNWxGyYJpdf/JXscNlQr/uv607ZPU9Z7ogHi+iI= google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= diff --git a/functions/apiv1/cloud_functions_client.go b/functions/apiv1/cloud_functions_client.go index d69f27782958..c43ba084d0fc 100644 --- a/functions/apiv1/cloud_functions_client.go +++ b/functions/apiv1/cloud_functions_client.go @@ -56,7 +56,7 @@ type CloudFunctionsCallOptions struct { TestIamPermissions []gax.CallOption } -func defaultCloudFunctionsClientOptions() []option.ClientOption { +func defaultCloudFunctionsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudfunctions.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudfunctions.mtls.googleapis.com:443"), @@ -128,37 +128,214 @@ func defaultCloudFunctionsCallOptions() *CloudFunctionsCallOptions { } } +// internalCloudFunctionsClient is an interface that defines the methods availaible from Cloud Functions API. +type internalCloudFunctionsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListFunctions(context.Context, *functionspb.ListFunctionsRequest, ...gax.CallOption) *CloudFunctionIterator + GetFunction(context.Context, *functionspb.GetFunctionRequest, ...gax.CallOption) (*functionspb.CloudFunction, error) + CreateFunction(context.Context, *functionspb.CreateFunctionRequest, ...gax.CallOption) (*CreateFunctionOperation, error) + CreateFunctionOperation(name string) *CreateFunctionOperation + UpdateFunction(context.Context, *functionspb.UpdateFunctionRequest, ...gax.CallOption) (*UpdateFunctionOperation, error) + UpdateFunctionOperation(name string) *UpdateFunctionOperation + DeleteFunction(context.Context, *functionspb.DeleteFunctionRequest, ...gax.CallOption) (*DeleteFunctionOperation, error) + DeleteFunctionOperation(name string) *DeleteFunctionOperation + CallFunction(context.Context, *functionspb.CallFunctionRequest, ...gax.CallOption) (*functionspb.CallFunctionResponse, error) + GenerateUploadUrl(context.Context, *functionspb.GenerateUploadUrlRequest, ...gax.CallOption) (*functionspb.GenerateUploadUrlResponse, error) + GenerateDownloadUrl(context.Context, *functionspb.GenerateDownloadUrlRequest, ...gax.CallOption) (*functionspb.GenerateDownloadUrlResponse, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) +} + // CloudFunctionsClient is a client for interacting with Cloud Functions API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A service that application uses to manipulate triggers and functions. type CloudFunctionsClient struct { + // The internal transport-dependent client. + internalClient internalCloudFunctionsClient + + // The call options for this service. + CallOptions *CloudFunctionsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CloudFunctionsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CloudFunctionsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CloudFunctionsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListFunctions returns a list of functions that belong to the requested project. +func (c *CloudFunctionsClient) ListFunctions(ctx context.Context, req *functionspb.ListFunctionsRequest, opts ...gax.CallOption) *CloudFunctionIterator { + return c.internalClient.ListFunctions(ctx, req, opts...) +} + +// GetFunction returns a function with the given name from the requested project. +func (c *CloudFunctionsClient) GetFunction(ctx context.Context, req *functionspb.GetFunctionRequest, opts ...gax.CallOption) (*functionspb.CloudFunction, error) { + return c.internalClient.GetFunction(ctx, req, opts...) +} + +// CreateFunction creates a new function. If a function with the given name already exists in +// the specified project, the long running operation will return +// ALREADY_EXISTS error. +func (c *CloudFunctionsClient) CreateFunction(ctx context.Context, req *functionspb.CreateFunctionRequest, opts ...gax.CallOption) (*CreateFunctionOperation, error) { + return c.internalClient.CreateFunction(ctx, req, opts...) +} + +// CreateFunctionOperation returns a new CreateFunctionOperation from a given name. +// The name must be that of a previously created CreateFunctionOperation, possibly from a different process. +func (c *CloudFunctionsClient) CreateFunctionOperation(name string) *CreateFunctionOperation { + return c.internalClient.CreateFunctionOperation(name) +} + +// UpdateFunction updates existing function. +func (c *CloudFunctionsClient) UpdateFunction(ctx context.Context, req *functionspb.UpdateFunctionRequest, opts ...gax.CallOption) (*UpdateFunctionOperation, error) { + return c.internalClient.UpdateFunction(ctx, req, opts...) +} + +// UpdateFunctionOperation returns a new UpdateFunctionOperation from a given name. +// The name must be that of a previously created UpdateFunctionOperation, possibly from a different process. +func (c *CloudFunctionsClient) UpdateFunctionOperation(name string) *UpdateFunctionOperation { + return c.internalClient.UpdateFunctionOperation(name) +} + +// DeleteFunction deletes a function with the given name from the specified project. If the +// given function is used by some trigger, the trigger will be updated to +// remove this function. +func (c *CloudFunctionsClient) DeleteFunction(ctx context.Context, req *functionspb.DeleteFunctionRequest, opts ...gax.CallOption) (*DeleteFunctionOperation, error) { + return c.internalClient.DeleteFunction(ctx, req, opts...) +} + +// DeleteFunctionOperation returns a new DeleteFunctionOperation from a given name. +// The name must be that of a previously created DeleteFunctionOperation, possibly from a different process. +func (c *CloudFunctionsClient) DeleteFunctionOperation(name string) *DeleteFunctionOperation { + return c.internalClient.DeleteFunctionOperation(name) +} + +// CallFunction synchronously invokes a deployed Cloud Function. To be used for testing +// purposes as very limited traffic is allowed. For more information on +// the actual limits, refer to +// Rate Limits (at https://cloud.google.com/functions/quotas#rate_limits). +func (c *CloudFunctionsClient) CallFunction(ctx context.Context, req *functionspb.CallFunctionRequest, opts ...gax.CallOption) (*functionspb.CallFunctionResponse, error) { + return c.internalClient.CallFunction(ctx, req, opts...) +} + +// GenerateUploadUrl returns a signed URL for uploading a function source code. +// For more information about the signed URL usage see: +// https://cloud.google.com/storage/docs/access-control/signed-urls (at https://cloud.google.com/storage/docs/access-control/signed-urls). +// Once the function source code upload is complete, the used signed +// URL should be provided in CreateFunction or UpdateFunction request +// as a reference to the function source code. +// +// When uploading source code to the generated signed URL, please follow +// these restrictions: +// +// Source file type should be a zip file. +// +// Source file size should not exceed 100MB limit. +// +// No credentials should be attached - the signed URLs provide access to the +// target bucket using internal service identity; if credentials were +// attached, the identity from the credentials would be used, but that +// identity does not have permissions to upload files to the URL. +// +// When making a HTTP PUT request, these two headers need to be specified: +// +// content-type: application/zip +// +// x-goog-content-length-range: 0,104857600 +// +// And this header SHOULD NOT be specified: +// +// Authorization: Bearer YOUR_TOKEN +func (c *CloudFunctionsClient) GenerateUploadUrl(ctx context.Context, req *functionspb.GenerateUploadUrlRequest, opts ...gax.CallOption) (*functionspb.GenerateUploadUrlResponse, error) { + return c.internalClient.GenerateUploadUrl(ctx, req, opts...) +} + +// GenerateDownloadUrl returns a signed URL for downloading deployed function source code. +// The URL is only valid for a limited period and should be used within +// minutes after generation. +// For more information about the signed URL usage see: +// https://cloud.google.com/storage/docs/access-control/signed-urls (at https://cloud.google.com/storage/docs/access-control/signed-urls) +func (c *CloudFunctionsClient) GenerateDownloadUrl(ctx context.Context, req *functionspb.GenerateDownloadUrlRequest, opts ...gax.CallOption) (*functionspb.GenerateDownloadUrlResponse, error) { + return c.internalClient.GenerateDownloadUrl(ctx, req, opts...) +} + +// SetIamPolicy sets the IAM access control policy on the specified function. +// Replaces any existing policy. +func (c *CloudFunctionsClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// GetIamPolicy gets the IAM access control policy for a function. +// Returns an empty policy if the function exists and does not have a policy +// set. +func (c *CloudFunctionsClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions tests the specified permissions against the IAM access control policy +// for a function. +// If the function does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +func (c *CloudFunctionsClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// cloudFunctionsGRPCClient is a client for interacting with Cloud Functions API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudFunctionsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CloudFunctionsClient + CallOptions **CloudFunctionsCallOptions + // The gRPC API client. cloudFunctionsClient functionspb.CloudFunctionsServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CloudFunctionsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCloudFunctionsClient creates a new cloud functions service client. +// NewCloudFunctionsClient creates a new cloud functions service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A service that application uses to manipulate triggers and functions. func NewCloudFunctionsClient(ctx context.Context, opts ...option.ClientOption) (*CloudFunctionsClient, error) { - clientOpts := defaultCloudFunctionsClientOptions() - + clientOpts := defaultCloudFunctionsGRPCClientOptions() if newCloudFunctionsClientHook != nil { hookOpts, err := newCloudFunctionsClientHook(ctx, clientHookParams{}) if err != nil { @@ -176,16 +353,19 @@ func NewCloudFunctionsClient(ctx context.Context, opts ...option.ClientOption) ( if err != nil { return nil, err } - c := &CloudFunctionsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultCloudFunctionsCallOptions(), + client := CloudFunctionsClient{CallOptions: defaultCloudFunctionsCallOptions()} + c := &cloudFunctionsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, cloudFunctionsClient: functionspb.NewCloudFunctionsServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -195,36 +375,36 @@ func NewCloudFunctionsClient(ctx context.Context, opts ...option.ClientOption) ( // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CloudFunctionsClient) Connection() *grpc.ClientConn { +func (c *cloudFunctionsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CloudFunctionsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CloudFunctionsClient) setGoogleClientInfo(keyval ...string) { +func (c *cloudFunctionsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListFunctions returns a list of functions that belong to the requested project. -func (c *CloudFunctionsClient) ListFunctions(ctx context.Context, req *functionspb.ListFunctionsRequest, opts ...gax.CallOption) *CloudFunctionIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudFunctionsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *cloudFunctionsGRPCClient) ListFunctions(ctx context.Context, req *functionspb.ListFunctionsRequest, opts ...gax.CallOption) *CloudFunctionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListFunctions[0:len(c.CallOptions.ListFunctions):len(c.CallOptions.ListFunctions)], opts...) + opts = append((*c.CallOptions).ListFunctions[0:len((*c.CallOptions).ListFunctions):len((*c.CallOptions).ListFunctions)], opts...) it := &CloudFunctionIterator{} req = proto.Clone(req).(*functionspb.ListFunctionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*functionspb.CloudFunction, string, error) { @@ -261,8 +441,7 @@ func (c *CloudFunctionsClient) ListFunctions(ctx context.Context, req *functions return it } -// GetFunction returns a function with the given name from the requested project. -func (c *CloudFunctionsClient) GetFunction(ctx context.Context, req *functionspb.GetFunctionRequest, opts ...gax.CallOption) (*functionspb.CloudFunction, error) { +func (c *cloudFunctionsGRPCClient) GetFunction(ctx context.Context, req *functionspb.GetFunctionRequest, opts ...gax.CallOption) (*functionspb.CloudFunction, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -270,7 +449,7 @@ func (c *CloudFunctionsClient) GetFunction(ctx context.Context, req *functionspb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetFunction[0:len(c.CallOptions.GetFunction):len(c.CallOptions.GetFunction)], opts...) + opts = append((*c.CallOptions).GetFunction[0:len((*c.CallOptions).GetFunction):len((*c.CallOptions).GetFunction)], opts...) var resp *functionspb.CloudFunction err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -283,10 +462,7 @@ func (c *CloudFunctionsClient) GetFunction(ctx context.Context, req *functionspb return resp, nil } -// CreateFunction creates a new function. If a function with the given name already exists in -// the specified project, the long running operation will return -// ALREADY_EXISTS error. -func (c *CloudFunctionsClient) CreateFunction(ctx context.Context, req *functionspb.CreateFunctionRequest, opts ...gax.CallOption) (*CreateFunctionOperation, error) { +func (c *cloudFunctionsGRPCClient) CreateFunction(ctx context.Context, req *functionspb.CreateFunctionRequest, opts ...gax.CallOption) (*CreateFunctionOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -294,7 +470,7 @@ func (c *CloudFunctionsClient) CreateFunction(ctx context.Context, req *function } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "location", url.QueryEscape(req.GetLocation()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateFunction[0:len(c.CallOptions.CreateFunction):len(c.CallOptions.CreateFunction)], opts...) + opts = append((*c.CallOptions).CreateFunction[0:len((*c.CallOptions).CreateFunction):len((*c.CallOptions).CreateFunction)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -305,12 +481,11 @@ func (c *CloudFunctionsClient) CreateFunction(ctx context.Context, req *function return nil, err } return &CreateFunctionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateFunction updates existing function. -func (c *CloudFunctionsClient) UpdateFunction(ctx context.Context, req *functionspb.UpdateFunctionRequest, opts ...gax.CallOption) (*UpdateFunctionOperation, error) { +func (c *cloudFunctionsGRPCClient) UpdateFunction(ctx context.Context, req *functionspb.UpdateFunctionRequest, opts ...gax.CallOption) (*UpdateFunctionOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -318,7 +493,7 @@ func (c *CloudFunctionsClient) UpdateFunction(ctx context.Context, req *function } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "function.name", url.QueryEscape(req.GetFunction().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateFunction[0:len(c.CallOptions.UpdateFunction):len(c.CallOptions.UpdateFunction)], opts...) + opts = append((*c.CallOptions).UpdateFunction[0:len((*c.CallOptions).UpdateFunction):len((*c.CallOptions).UpdateFunction)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -329,14 +504,11 @@ func (c *CloudFunctionsClient) UpdateFunction(ctx context.Context, req *function return nil, err } return &UpdateFunctionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteFunction deletes a function with the given name from the specified project. If the -// given function is used by some trigger, the trigger will be updated to -// remove this function. -func (c *CloudFunctionsClient) DeleteFunction(ctx context.Context, req *functionspb.DeleteFunctionRequest, opts ...gax.CallOption) (*DeleteFunctionOperation, error) { +func (c *cloudFunctionsGRPCClient) DeleteFunction(ctx context.Context, req *functionspb.DeleteFunctionRequest, opts ...gax.CallOption) (*DeleteFunctionOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -344,7 +516,7 @@ func (c *CloudFunctionsClient) DeleteFunction(ctx context.Context, req *function } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteFunction[0:len(c.CallOptions.DeleteFunction):len(c.CallOptions.DeleteFunction)], opts...) + opts = append((*c.CallOptions).DeleteFunction[0:len((*c.CallOptions).DeleteFunction):len((*c.CallOptions).DeleteFunction)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -355,15 +527,11 @@ func (c *CloudFunctionsClient) DeleteFunction(ctx context.Context, req *function return nil, err } return &DeleteFunctionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// CallFunction synchronously invokes a deployed Cloud Function. To be used for testing -// purposes as very limited traffic is allowed. For more information on -// the actual limits, refer to -// Rate Limits (at https://cloud.google.com/functions/quotas#rate_limits). -func (c *CloudFunctionsClient) CallFunction(ctx context.Context, req *functionspb.CallFunctionRequest, opts ...gax.CallOption) (*functionspb.CallFunctionResponse, error) { +func (c *cloudFunctionsGRPCClient) CallFunction(ctx context.Context, req *functionspb.CallFunctionRequest, opts ...gax.CallOption) (*functionspb.CallFunctionResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -371,7 +539,7 @@ func (c *CloudFunctionsClient) CallFunction(ctx context.Context, req *functionsp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CallFunction[0:len(c.CallOptions.CallFunction):len(c.CallOptions.CallFunction)], opts...) + opts = append((*c.CallOptions).CallFunction[0:len((*c.CallOptions).CallFunction):len((*c.CallOptions).CallFunction)], opts...) var resp *functionspb.CallFunctionResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -384,38 +552,10 @@ func (c *CloudFunctionsClient) CallFunction(ctx context.Context, req *functionsp return resp, nil } -// GenerateUploadUrl returns a signed URL for uploading a function source code. -// For more information about the signed URL usage see: -// https://cloud.google.com/storage/docs/access-control/signed-urls (at https://cloud.google.com/storage/docs/access-control/signed-urls). -// Once the function source code upload is complete, the used signed -// URL should be provided in CreateFunction or UpdateFunction request -// as a reference to the function source code. -// -// When uploading source code to the generated signed URL, please follow -// these restrictions: -// -// Source file type should be a zip file. -// -// Source file size should not exceed 100MB limit. -// -// No credentials should be attached - the signed URLs provide access to the -// target bucket using internal service identity; if credentials were -// attached, the identity from the credentials would be used, but that -// identity does not have permissions to upload files to the URL. -// -// When making a HTTP PUT request, these two headers need to be specified: -// -// content-type: application/zip -// -// x-goog-content-length-range: 0,104857600 -// -// And this header SHOULD NOT be specified: -// -// Authorization: Bearer YOUR_TOKEN -func (c *CloudFunctionsClient) GenerateUploadUrl(ctx context.Context, req *functionspb.GenerateUploadUrlRequest, opts ...gax.CallOption) (*functionspb.GenerateUploadUrlResponse, error) { +func (c *cloudFunctionsGRPCClient) GenerateUploadUrl(ctx context.Context, req *functionspb.GenerateUploadUrlRequest, opts ...gax.CallOption) (*functionspb.GenerateUploadUrlResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GenerateUploadUrl[0:len(c.CallOptions.GenerateUploadUrl):len(c.CallOptions.GenerateUploadUrl)], opts...) + opts = append((*c.CallOptions).GenerateUploadUrl[0:len((*c.CallOptions).GenerateUploadUrl):len((*c.CallOptions).GenerateUploadUrl)], opts...) var resp *functionspb.GenerateUploadUrlResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -428,15 +568,10 @@ func (c *CloudFunctionsClient) GenerateUploadUrl(ctx context.Context, req *funct return resp, nil } -// GenerateDownloadUrl returns a signed URL for downloading deployed function source code. -// The URL is only valid for a limited period and should be used within -// minutes after generation. -// For more information about the signed URL usage see: -// https://cloud.google.com/storage/docs/access-control/signed-urls (at https://cloud.google.com/storage/docs/access-control/signed-urls) -func (c *CloudFunctionsClient) GenerateDownloadUrl(ctx context.Context, req *functionspb.GenerateDownloadUrlRequest, opts ...gax.CallOption) (*functionspb.GenerateDownloadUrlResponse, error) { +func (c *cloudFunctionsGRPCClient) GenerateDownloadUrl(ctx context.Context, req *functionspb.GenerateDownloadUrlRequest, opts ...gax.CallOption) (*functionspb.GenerateDownloadUrlResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GenerateDownloadUrl[0:len(c.CallOptions.GenerateDownloadUrl):len(c.CallOptions.GenerateDownloadUrl)], opts...) + opts = append((*c.CallOptions).GenerateDownloadUrl[0:len((*c.CallOptions).GenerateDownloadUrl):len((*c.CallOptions).GenerateDownloadUrl)], opts...) var resp *functionspb.GenerateDownloadUrlResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -449,12 +584,10 @@ func (c *CloudFunctionsClient) GenerateDownloadUrl(ctx context.Context, req *fun return resp, nil } -// SetIamPolicy sets the IAM access control policy on the specified function. -// Replaces any existing policy. -func (c *CloudFunctionsClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *cloudFunctionsGRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -467,13 +600,10 @@ func (c *CloudFunctionsClient) SetIamPolicy(ctx context.Context, req *iampb.SetI return resp, nil } -// GetIamPolicy gets the IAM access control policy for a function. -// Returns an empty policy if the function exists and does not have a policy -// set. -func (c *CloudFunctionsClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *cloudFunctionsGRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -486,14 +616,10 @@ func (c *CloudFunctionsClient) GetIamPolicy(ctx context.Context, req *iampb.GetI return resp, nil } -// TestIamPermissions tests the specified permissions against the IAM access control policy -// for a function. -// If the function does not exist, this will return an empty set of -// permissions, not a NOT_FOUND error. -func (c *CloudFunctionsClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *cloudFunctionsGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -513,9 +639,9 @@ type CreateFunctionOperation struct { // CreateFunctionOperation returns a new CreateFunctionOperation from a given name. // The name must be that of a previously created CreateFunctionOperation, possibly from a different process. -func (c *CloudFunctionsClient) CreateFunctionOperation(name string) *CreateFunctionOperation { +func (c *cloudFunctionsGRPCClient) CreateFunctionOperation(name string) *CreateFunctionOperation { return &CreateFunctionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -582,9 +708,9 @@ type DeleteFunctionOperation struct { // DeleteFunctionOperation returns a new DeleteFunctionOperation from a given name. // The name must be that of a previously created DeleteFunctionOperation, possibly from a different process. -func (c *CloudFunctionsClient) DeleteFunctionOperation(name string) *DeleteFunctionOperation { +func (c *cloudFunctionsGRPCClient) DeleteFunctionOperation(name string) *DeleteFunctionOperation { return &DeleteFunctionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -640,9 +766,9 @@ type UpdateFunctionOperation struct { // UpdateFunctionOperation returns a new UpdateFunctionOperation from a given name. // The name must be that of a previously created UpdateFunctionOperation, possibly from a different process. -func (c *CloudFunctionsClient) UpdateFunctionOperation(name string) *UpdateFunctionOperation { +func (c *cloudFunctionsGRPCClient) UpdateFunctionOperation(name string) *UpdateFunctionOperation { return &UpdateFunctionOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/functions/apiv1/cloud_functions_client_example_test.go b/functions/apiv1/cloud_functions_client_example_test.go index 58321e4bb0a0..9a5ab221d0b0 100644 --- a/functions/apiv1/cloud_functions_client_example_test.go +++ b/functions/apiv1/cloud_functions_client_example_test.go @@ -31,19 +31,19 @@ func ExampleNewCloudFunctionsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCloudFunctionsClient_ListFunctions() { - // import functionspb "google.golang.org/genproto/googleapis/cloud/functions/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &functionspb.ListFunctionsRequest{ // TODO: Fill request struct fields. @@ -63,13 +63,12 @@ func ExampleCloudFunctionsClient_ListFunctions() { } func ExampleCloudFunctionsClient_GetFunction() { - // import functionspb "google.golang.org/genproto/googleapis/cloud/functions/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &functionspb.GetFunctionRequest{ // TODO: Fill request struct fields. @@ -83,13 +82,12 @@ func ExampleCloudFunctionsClient_GetFunction() { } func ExampleCloudFunctionsClient_CreateFunction() { - // import functionspb "google.golang.org/genproto/googleapis/cloud/functions/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &functionspb.CreateFunctionRequest{ // TODO: Fill request struct fields. @@ -108,13 +106,12 @@ func ExampleCloudFunctionsClient_CreateFunction() { } func ExampleCloudFunctionsClient_UpdateFunction() { - // import functionspb "google.golang.org/genproto/googleapis/cloud/functions/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &functionspb.UpdateFunctionRequest{ // TODO: Fill request struct fields. @@ -133,13 +130,12 @@ func ExampleCloudFunctionsClient_UpdateFunction() { } func ExampleCloudFunctionsClient_DeleteFunction() { - // import functionspb "google.golang.org/genproto/googleapis/cloud/functions/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &functionspb.DeleteFunctionRequest{ // TODO: Fill request struct fields. @@ -156,13 +152,12 @@ func ExampleCloudFunctionsClient_DeleteFunction() { } func ExampleCloudFunctionsClient_CallFunction() { - // import functionspb "google.golang.org/genproto/googleapis/cloud/functions/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &functionspb.CallFunctionRequest{ // TODO: Fill request struct fields. @@ -176,13 +171,12 @@ func ExampleCloudFunctionsClient_CallFunction() { } func ExampleCloudFunctionsClient_GenerateUploadUrl() { - // import functionspb "google.golang.org/genproto/googleapis/cloud/functions/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &functionspb.GenerateUploadUrlRequest{ // TODO: Fill request struct fields. @@ -196,13 +190,12 @@ func ExampleCloudFunctionsClient_GenerateUploadUrl() { } func ExampleCloudFunctionsClient_GenerateDownloadUrl() { - // import functionspb "google.golang.org/genproto/googleapis/cloud/functions/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &functionspb.GenerateDownloadUrlRequest{ // TODO: Fill request struct fields. @@ -216,13 +209,12 @@ func ExampleCloudFunctionsClient_GenerateDownloadUrl() { } func ExampleCloudFunctionsClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -236,13 +228,12 @@ func ExampleCloudFunctionsClient_SetIamPolicy() { } func ExampleCloudFunctionsClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -256,13 +247,12 @@ func ExampleCloudFunctionsClient_GetIamPolicy() { } func ExampleCloudFunctionsClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/functions/apiv1/doc.go b/functions/apiv1/doc.go index 26f960d08164..1319d03526c7 100644 --- a/functions/apiv1/doc.go +++ b/functions/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package functions // import "cloud.google.com/go/functions/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/gaming/apiv1/doc.go b/gaming/apiv1/doc.go index 65b02e524f43..f140775f538b 100644 --- a/gaming/apiv1/doc.go +++ b/gaming/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package gaming // import "cloud.google.com/go/gaming/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/gaming/apiv1/game_server_clusters_client.go b/gaming/apiv1/game_server_clusters_client.go index 1718bd5f1a19..a020c066f14b 100644 --- a/gaming/apiv1/game_server_clusters_client.go +++ b/gaming/apiv1/game_server_clusters_client.go @@ -52,7 +52,7 @@ type GameServerClustersCallOptions struct { PreviewUpdateGameServerCluster []gax.CallOption } -func defaultGameServerClustersClientOptions() []option.ClientOption { +func defaultGameServerClustersGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("gameservices.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("gameservices.mtls.googleapis.com:443"), @@ -127,38 +127,155 @@ func defaultGameServerClustersCallOptions() *GameServerClustersCallOptions { } } +// internalGameServerClustersClient is an interface that defines the methods availaible from Game Services API. +type internalGameServerClustersClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListGameServerClusters(context.Context, *gamingpb.ListGameServerClustersRequest, ...gax.CallOption) *GameServerClusterIterator + GetGameServerCluster(context.Context, *gamingpb.GetGameServerClusterRequest, ...gax.CallOption) (*gamingpb.GameServerCluster, error) + CreateGameServerCluster(context.Context, *gamingpb.CreateGameServerClusterRequest, ...gax.CallOption) (*CreateGameServerClusterOperation, error) + CreateGameServerClusterOperation(name string) *CreateGameServerClusterOperation + PreviewCreateGameServerCluster(context.Context, *gamingpb.PreviewCreateGameServerClusterRequest, ...gax.CallOption) (*gamingpb.PreviewCreateGameServerClusterResponse, error) + DeleteGameServerCluster(context.Context, *gamingpb.DeleteGameServerClusterRequest, ...gax.CallOption) (*DeleteGameServerClusterOperation, error) + DeleteGameServerClusterOperation(name string) *DeleteGameServerClusterOperation + PreviewDeleteGameServerCluster(context.Context, *gamingpb.PreviewDeleteGameServerClusterRequest, ...gax.CallOption) (*gamingpb.PreviewDeleteGameServerClusterResponse, error) + UpdateGameServerCluster(context.Context, *gamingpb.UpdateGameServerClusterRequest, ...gax.CallOption) (*UpdateGameServerClusterOperation, error) + UpdateGameServerClusterOperation(name string) *UpdateGameServerClusterOperation + PreviewUpdateGameServerCluster(context.Context, *gamingpb.PreviewUpdateGameServerClusterRequest, ...gax.CallOption) (*gamingpb.PreviewUpdateGameServerClusterResponse, error) +} + // GameServerClustersClient is a client for interacting with Game Services API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The game server cluster maps to Kubernetes clusters running Agones and is +// used to manage fleets within clusters. type GameServerClustersClient struct { + // The internal transport-dependent client. + internalClient internalGameServerClustersClient + + // The call options for this service. + CallOptions *GameServerClustersCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *GameServerClustersClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *GameServerClustersClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *GameServerClustersClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListGameServerClusters lists game server clusters in a given project and location. +func (c *GameServerClustersClient) ListGameServerClusters(ctx context.Context, req *gamingpb.ListGameServerClustersRequest, opts ...gax.CallOption) *GameServerClusterIterator { + return c.internalClient.ListGameServerClusters(ctx, req, opts...) +} + +// GetGameServerCluster gets details of a single game server cluster. +func (c *GameServerClustersClient) GetGameServerCluster(ctx context.Context, req *gamingpb.GetGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.GameServerCluster, error) { + return c.internalClient.GetGameServerCluster(ctx, req, opts...) +} + +// CreateGameServerCluster creates a new game server cluster in a given project and location. +func (c *GameServerClustersClient) CreateGameServerCluster(ctx context.Context, req *gamingpb.CreateGameServerClusterRequest, opts ...gax.CallOption) (*CreateGameServerClusterOperation, error) { + return c.internalClient.CreateGameServerCluster(ctx, req, opts...) +} + +// CreateGameServerClusterOperation returns a new CreateGameServerClusterOperation from a given name. +// The name must be that of a previously created CreateGameServerClusterOperation, possibly from a different process. +func (c *GameServerClustersClient) CreateGameServerClusterOperation(name string) *CreateGameServerClusterOperation { + return c.internalClient.CreateGameServerClusterOperation(name) +} + +// PreviewCreateGameServerCluster previews creation of a new game server cluster in a given project and +// location. +func (c *GameServerClustersClient) PreviewCreateGameServerCluster(ctx context.Context, req *gamingpb.PreviewCreateGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewCreateGameServerClusterResponse, error) { + return c.internalClient.PreviewCreateGameServerCluster(ctx, req, opts...) +} + +// DeleteGameServerCluster deletes a single game server cluster. +func (c *GameServerClustersClient) DeleteGameServerCluster(ctx context.Context, req *gamingpb.DeleteGameServerClusterRequest, opts ...gax.CallOption) (*DeleteGameServerClusterOperation, error) { + return c.internalClient.DeleteGameServerCluster(ctx, req, opts...) +} + +// DeleteGameServerClusterOperation returns a new DeleteGameServerClusterOperation from a given name. +// The name must be that of a previously created DeleteGameServerClusterOperation, possibly from a different process. +func (c *GameServerClustersClient) DeleteGameServerClusterOperation(name string) *DeleteGameServerClusterOperation { + return c.internalClient.DeleteGameServerClusterOperation(name) +} + +// PreviewDeleteGameServerCluster previews deletion of a single game server cluster. +func (c *GameServerClustersClient) PreviewDeleteGameServerCluster(ctx context.Context, req *gamingpb.PreviewDeleteGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewDeleteGameServerClusterResponse, error) { + return c.internalClient.PreviewDeleteGameServerCluster(ctx, req, opts...) +} + +// UpdateGameServerCluster patches a single game server cluster. +func (c *GameServerClustersClient) UpdateGameServerCluster(ctx context.Context, req *gamingpb.UpdateGameServerClusterRequest, opts ...gax.CallOption) (*UpdateGameServerClusterOperation, error) { + return c.internalClient.UpdateGameServerCluster(ctx, req, opts...) +} + +// UpdateGameServerClusterOperation returns a new UpdateGameServerClusterOperation from a given name. +// The name must be that of a previously created UpdateGameServerClusterOperation, possibly from a different process. +func (c *GameServerClustersClient) UpdateGameServerClusterOperation(name string) *UpdateGameServerClusterOperation { + return c.internalClient.UpdateGameServerClusterOperation(name) +} + +// PreviewUpdateGameServerCluster previews updating a GameServerCluster. +func (c *GameServerClustersClient) PreviewUpdateGameServerCluster(ctx context.Context, req *gamingpb.PreviewUpdateGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewUpdateGameServerClusterResponse, error) { + return c.internalClient.PreviewUpdateGameServerCluster(ctx, req, opts...) +} + +// gameServerClustersGRPCClient is a client for interacting with Game Services API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gameServerClustersGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing GameServerClustersClient + CallOptions **GameServerClustersCallOptions + // The gRPC API client. gameServerClustersClient gamingpb.GameServerClustersServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *GameServerClustersCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewGameServerClustersClient creates a new game server clusters service client. +// NewGameServerClustersClient creates a new game server clusters service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The game server cluster maps to Kubernetes clusters running Agones and is // used to manage fleets within clusters. func NewGameServerClustersClient(ctx context.Context, opts ...option.ClientOption) (*GameServerClustersClient, error) { - clientOpts := defaultGameServerClustersClientOptions() - + clientOpts := defaultGameServerClustersGRPCClientOptions() if newGameServerClustersClientHook != nil { hookOpts, err := newGameServerClustersClientHook(ctx, clientHookParams{}) if err != nil { @@ -176,16 +293,19 @@ func NewGameServerClustersClient(ctx context.Context, opts ...option.ClientOptio if err != nil { return nil, err } - c := &GameServerClustersClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultGameServerClustersCallOptions(), + client := GameServerClustersClient{CallOptions: defaultGameServerClustersCallOptions()} + c := &gameServerClustersGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, gameServerClustersClient: gamingpb.NewGameServerClustersServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -195,36 +315,36 @@ func NewGameServerClustersClient(ctx context.Context, opts ...option.ClientOptio // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *GameServerClustersClient) Connection() *grpc.ClientConn { +func (c *gameServerClustersGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *GameServerClustersClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *GameServerClustersClient) setGoogleClientInfo(keyval ...string) { +func (c *gameServerClustersGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListGameServerClusters lists game server clusters in a given project and location. -func (c *GameServerClustersClient) ListGameServerClusters(ctx context.Context, req *gamingpb.ListGameServerClustersRequest, opts ...gax.CallOption) *GameServerClusterIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gameServerClustersGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gameServerClustersGRPCClient) ListGameServerClusters(ctx context.Context, req *gamingpb.ListGameServerClustersRequest, opts ...gax.CallOption) *GameServerClusterIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListGameServerClusters[0:len(c.CallOptions.ListGameServerClusters):len(c.CallOptions.ListGameServerClusters)], opts...) + opts = append((*c.CallOptions).ListGameServerClusters[0:len((*c.CallOptions).ListGameServerClusters):len((*c.CallOptions).ListGameServerClusters)], opts...) it := &GameServerClusterIterator{} req = proto.Clone(req).(*gamingpb.ListGameServerClustersRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*gamingpb.GameServerCluster, string, error) { @@ -261,8 +381,7 @@ func (c *GameServerClustersClient) ListGameServerClusters(ctx context.Context, r return it } -// GetGameServerCluster gets details of a single game server cluster. -func (c *GameServerClustersClient) GetGameServerCluster(ctx context.Context, req *gamingpb.GetGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.GameServerCluster, error) { +func (c *gameServerClustersGRPCClient) GetGameServerCluster(ctx context.Context, req *gamingpb.GetGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.GameServerCluster, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -270,7 +389,7 @@ func (c *GameServerClustersClient) GetGameServerCluster(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetGameServerCluster[0:len(c.CallOptions.GetGameServerCluster):len(c.CallOptions.GetGameServerCluster)], opts...) + opts = append((*c.CallOptions).GetGameServerCluster[0:len((*c.CallOptions).GetGameServerCluster):len((*c.CallOptions).GetGameServerCluster)], opts...) var resp *gamingpb.GameServerCluster err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -283,8 +402,7 @@ func (c *GameServerClustersClient) GetGameServerCluster(ctx context.Context, req return resp, nil } -// CreateGameServerCluster creates a new game server cluster in a given project and location. -func (c *GameServerClustersClient) CreateGameServerCluster(ctx context.Context, req *gamingpb.CreateGameServerClusterRequest, opts ...gax.CallOption) (*CreateGameServerClusterOperation, error) { +func (c *gameServerClustersGRPCClient) CreateGameServerCluster(ctx context.Context, req *gamingpb.CreateGameServerClusterRequest, opts ...gax.CallOption) (*CreateGameServerClusterOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -292,7 +410,7 @@ func (c *GameServerClustersClient) CreateGameServerCluster(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateGameServerCluster[0:len(c.CallOptions.CreateGameServerCluster):len(c.CallOptions.CreateGameServerCluster)], opts...) + opts = append((*c.CallOptions).CreateGameServerCluster[0:len((*c.CallOptions).CreateGameServerCluster):len((*c.CallOptions).CreateGameServerCluster)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -303,13 +421,11 @@ func (c *GameServerClustersClient) CreateGameServerCluster(ctx context.Context, return nil, err } return &CreateGameServerClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// PreviewCreateGameServerCluster previews creation of a new game server cluster in a given project and -// location. -func (c *GameServerClustersClient) PreviewCreateGameServerCluster(ctx context.Context, req *gamingpb.PreviewCreateGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewCreateGameServerClusterResponse, error) { +func (c *gameServerClustersGRPCClient) PreviewCreateGameServerCluster(ctx context.Context, req *gamingpb.PreviewCreateGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewCreateGameServerClusterResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -317,7 +433,7 @@ func (c *GameServerClustersClient) PreviewCreateGameServerCluster(ctx context.Co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PreviewCreateGameServerCluster[0:len(c.CallOptions.PreviewCreateGameServerCluster):len(c.CallOptions.PreviewCreateGameServerCluster)], opts...) + opts = append((*c.CallOptions).PreviewCreateGameServerCluster[0:len((*c.CallOptions).PreviewCreateGameServerCluster):len((*c.CallOptions).PreviewCreateGameServerCluster)], opts...) var resp *gamingpb.PreviewCreateGameServerClusterResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -330,8 +446,7 @@ func (c *GameServerClustersClient) PreviewCreateGameServerCluster(ctx context.Co return resp, nil } -// DeleteGameServerCluster deletes a single game server cluster. -func (c *GameServerClustersClient) DeleteGameServerCluster(ctx context.Context, req *gamingpb.DeleteGameServerClusterRequest, opts ...gax.CallOption) (*DeleteGameServerClusterOperation, error) { +func (c *gameServerClustersGRPCClient) DeleteGameServerCluster(ctx context.Context, req *gamingpb.DeleteGameServerClusterRequest, opts ...gax.CallOption) (*DeleteGameServerClusterOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -339,7 +454,7 @@ func (c *GameServerClustersClient) DeleteGameServerCluster(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteGameServerCluster[0:len(c.CallOptions.DeleteGameServerCluster):len(c.CallOptions.DeleteGameServerCluster)], opts...) + opts = append((*c.CallOptions).DeleteGameServerCluster[0:len((*c.CallOptions).DeleteGameServerCluster):len((*c.CallOptions).DeleteGameServerCluster)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -350,12 +465,11 @@ func (c *GameServerClustersClient) DeleteGameServerCluster(ctx context.Context, return nil, err } return &DeleteGameServerClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// PreviewDeleteGameServerCluster previews deletion of a single game server cluster. -func (c *GameServerClustersClient) PreviewDeleteGameServerCluster(ctx context.Context, req *gamingpb.PreviewDeleteGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewDeleteGameServerClusterResponse, error) { +func (c *gameServerClustersGRPCClient) PreviewDeleteGameServerCluster(ctx context.Context, req *gamingpb.PreviewDeleteGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewDeleteGameServerClusterResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -363,7 +477,7 @@ func (c *GameServerClustersClient) PreviewDeleteGameServerCluster(ctx context.Co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PreviewDeleteGameServerCluster[0:len(c.CallOptions.PreviewDeleteGameServerCluster):len(c.CallOptions.PreviewDeleteGameServerCluster)], opts...) + opts = append((*c.CallOptions).PreviewDeleteGameServerCluster[0:len((*c.CallOptions).PreviewDeleteGameServerCluster):len((*c.CallOptions).PreviewDeleteGameServerCluster)], opts...) var resp *gamingpb.PreviewDeleteGameServerClusterResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -376,8 +490,7 @@ func (c *GameServerClustersClient) PreviewDeleteGameServerCluster(ctx context.Co return resp, nil } -// UpdateGameServerCluster patches a single game server cluster. -func (c *GameServerClustersClient) UpdateGameServerCluster(ctx context.Context, req *gamingpb.UpdateGameServerClusterRequest, opts ...gax.CallOption) (*UpdateGameServerClusterOperation, error) { +func (c *gameServerClustersGRPCClient) UpdateGameServerCluster(ctx context.Context, req *gamingpb.UpdateGameServerClusterRequest, opts ...gax.CallOption) (*UpdateGameServerClusterOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -385,7 +498,7 @@ func (c *GameServerClustersClient) UpdateGameServerCluster(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "game_server_cluster.name", url.QueryEscape(req.GetGameServerCluster().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateGameServerCluster[0:len(c.CallOptions.UpdateGameServerCluster):len(c.CallOptions.UpdateGameServerCluster)], opts...) + opts = append((*c.CallOptions).UpdateGameServerCluster[0:len((*c.CallOptions).UpdateGameServerCluster):len((*c.CallOptions).UpdateGameServerCluster)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -396,12 +509,11 @@ func (c *GameServerClustersClient) UpdateGameServerCluster(ctx context.Context, return nil, err } return &UpdateGameServerClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// PreviewUpdateGameServerCluster previews updating a GameServerCluster. -func (c *GameServerClustersClient) PreviewUpdateGameServerCluster(ctx context.Context, req *gamingpb.PreviewUpdateGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewUpdateGameServerClusterResponse, error) { +func (c *gameServerClustersGRPCClient) PreviewUpdateGameServerCluster(ctx context.Context, req *gamingpb.PreviewUpdateGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewUpdateGameServerClusterResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -409,7 +521,7 @@ func (c *GameServerClustersClient) PreviewUpdateGameServerCluster(ctx context.Co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "game_server_cluster.name", url.QueryEscape(req.GetGameServerCluster().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PreviewUpdateGameServerCluster[0:len(c.CallOptions.PreviewUpdateGameServerCluster):len(c.CallOptions.PreviewUpdateGameServerCluster)], opts...) + opts = append((*c.CallOptions).PreviewUpdateGameServerCluster[0:len((*c.CallOptions).PreviewUpdateGameServerCluster):len((*c.CallOptions).PreviewUpdateGameServerCluster)], opts...) var resp *gamingpb.PreviewUpdateGameServerClusterResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -429,9 +541,9 @@ type CreateGameServerClusterOperation struct { // CreateGameServerClusterOperation returns a new CreateGameServerClusterOperation from a given name. // The name must be that of a previously created CreateGameServerClusterOperation, possibly from a different process. -func (c *GameServerClustersClient) CreateGameServerClusterOperation(name string) *CreateGameServerClusterOperation { +func (c *gameServerClustersGRPCClient) CreateGameServerClusterOperation(name string) *CreateGameServerClusterOperation { return &CreateGameServerClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -498,9 +610,9 @@ type DeleteGameServerClusterOperation struct { // DeleteGameServerClusterOperation returns a new DeleteGameServerClusterOperation from a given name. // The name must be that of a previously created DeleteGameServerClusterOperation, possibly from a different process. -func (c *GameServerClustersClient) DeleteGameServerClusterOperation(name string) *DeleteGameServerClusterOperation { +func (c *gameServerClustersGRPCClient) DeleteGameServerClusterOperation(name string) *DeleteGameServerClusterOperation { return &DeleteGameServerClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -556,9 +668,9 @@ type UpdateGameServerClusterOperation struct { // UpdateGameServerClusterOperation returns a new UpdateGameServerClusterOperation from a given name. // The name must be that of a previously created UpdateGameServerClusterOperation, possibly from a different process. -func (c *GameServerClustersClient) UpdateGameServerClusterOperation(name string) *UpdateGameServerClusterOperation { +func (c *gameServerClustersGRPCClient) UpdateGameServerClusterOperation(name string) *UpdateGameServerClusterOperation { return &UpdateGameServerClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/gaming/apiv1/game_server_clusters_client_example_test.go b/gaming/apiv1/game_server_clusters_client_example_test.go index 8ac306357702..3331dd3b90df 100644 --- a/gaming/apiv1/game_server_clusters_client_example_test.go +++ b/gaming/apiv1/game_server_clusters_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewGameServerClustersClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleGameServerClustersClient_ListGameServerClusters() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.ListGameServerClustersRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleGameServerClustersClient_ListGameServerClusters() { } func ExampleGameServerClustersClient_GetGameServerCluster() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetGameServerClusterRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleGameServerClustersClient_GetGameServerCluster() { } func ExampleGameServerClustersClient_CreateGameServerCluster() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.CreateGameServerClusterRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleGameServerClustersClient_CreateGameServerCluster() { } func ExampleGameServerClustersClient_PreviewCreateGameServerCluster() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewCreateGameServerClusterRequest{ // TODO: Fill request struct fields. @@ -127,13 +124,12 @@ func ExampleGameServerClustersClient_PreviewCreateGameServerCluster() { } func ExampleGameServerClustersClient_DeleteGameServerCluster() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.DeleteGameServerClusterRequest{ // TODO: Fill request struct fields. @@ -150,13 +146,12 @@ func ExampleGameServerClustersClient_DeleteGameServerCluster() { } func ExampleGameServerClustersClient_PreviewDeleteGameServerCluster() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewDeleteGameServerClusterRequest{ // TODO: Fill request struct fields. @@ -170,13 +165,12 @@ func ExampleGameServerClustersClient_PreviewDeleteGameServerCluster() { } func ExampleGameServerClustersClient_UpdateGameServerCluster() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.UpdateGameServerClusterRequest{ // TODO: Fill request struct fields. @@ -195,13 +189,12 @@ func ExampleGameServerClustersClient_UpdateGameServerCluster() { } func ExampleGameServerClustersClient_PreviewUpdateGameServerCluster() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewUpdateGameServerClusterRequest{ // TODO: Fill request struct fields. diff --git a/gaming/apiv1/game_server_configs_client.go b/gaming/apiv1/game_server_configs_client.go index c7542df45c97..7f8909172600 100644 --- a/gaming/apiv1/game_server_configs_client.go +++ b/gaming/apiv1/game_server_configs_client.go @@ -48,7 +48,7 @@ type GameServerConfigsCallOptions struct { DeleteGameServerConfig []gax.CallOption } -func defaultGameServerConfigsClientOptions() []option.ClientOption { +func defaultGameServerConfigsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("gameservices.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("gameservices.mtls.googleapis.com:443"), @@ -89,37 +89,125 @@ func defaultGameServerConfigsCallOptions() *GameServerConfigsCallOptions { } } +// internalGameServerConfigsClient is an interface that defines the methods availaible from Game Services API. +type internalGameServerConfigsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListGameServerConfigs(context.Context, *gamingpb.ListGameServerConfigsRequest, ...gax.CallOption) *GameServerConfigIterator + GetGameServerConfig(context.Context, *gamingpb.GetGameServerConfigRequest, ...gax.CallOption) (*gamingpb.GameServerConfig, error) + CreateGameServerConfig(context.Context, *gamingpb.CreateGameServerConfigRequest, ...gax.CallOption) (*CreateGameServerConfigOperation, error) + CreateGameServerConfigOperation(name string) *CreateGameServerConfigOperation + DeleteGameServerConfig(context.Context, *gamingpb.DeleteGameServerConfigRequest, ...gax.CallOption) (*DeleteGameServerConfigOperation, error) + DeleteGameServerConfigOperation(name string) *DeleteGameServerConfigOperation +} + // GameServerConfigsClient is a client for interacting with Game Services API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The game server config configures the game servers in an Agones fleet. type GameServerConfigsClient struct { + // The internal transport-dependent client. + internalClient internalGameServerConfigsClient + + // The call options for this service. + CallOptions *GameServerConfigsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *GameServerConfigsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *GameServerConfigsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *GameServerConfigsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListGameServerConfigs lists game server configs in a given project, location, and game server +// deployment. +func (c *GameServerConfigsClient) ListGameServerConfigs(ctx context.Context, req *gamingpb.ListGameServerConfigsRequest, opts ...gax.CallOption) *GameServerConfigIterator { + return c.internalClient.ListGameServerConfigs(ctx, req, opts...) +} + +// GetGameServerConfig gets details of a single game server config. +func (c *GameServerConfigsClient) GetGameServerConfig(ctx context.Context, req *gamingpb.GetGameServerConfigRequest, opts ...gax.CallOption) (*gamingpb.GameServerConfig, error) { + return c.internalClient.GetGameServerConfig(ctx, req, opts...) +} + +// CreateGameServerConfig creates a new game server config in a given project, location, and game +// server deployment. Game server configs are immutable, and are not applied +// until referenced in the game server deployment rollout resource. +func (c *GameServerConfigsClient) CreateGameServerConfig(ctx context.Context, req *gamingpb.CreateGameServerConfigRequest, opts ...gax.CallOption) (*CreateGameServerConfigOperation, error) { + return c.internalClient.CreateGameServerConfig(ctx, req, opts...) +} + +// CreateGameServerConfigOperation returns a new CreateGameServerConfigOperation from a given name. +// The name must be that of a previously created CreateGameServerConfigOperation, possibly from a different process. +func (c *GameServerConfigsClient) CreateGameServerConfigOperation(name string) *CreateGameServerConfigOperation { + return c.internalClient.CreateGameServerConfigOperation(name) +} + +// DeleteGameServerConfig deletes a single game server config. The deletion will fail if the game +// server config is referenced in a game server deployment rollout. +func (c *GameServerConfigsClient) DeleteGameServerConfig(ctx context.Context, req *gamingpb.DeleteGameServerConfigRequest, opts ...gax.CallOption) (*DeleteGameServerConfigOperation, error) { + return c.internalClient.DeleteGameServerConfig(ctx, req, opts...) +} + +// DeleteGameServerConfigOperation returns a new DeleteGameServerConfigOperation from a given name. +// The name must be that of a previously created DeleteGameServerConfigOperation, possibly from a different process. +func (c *GameServerConfigsClient) DeleteGameServerConfigOperation(name string) *DeleteGameServerConfigOperation { + return c.internalClient.DeleteGameServerConfigOperation(name) +} + +// gameServerConfigsGRPCClient is a client for interacting with Game Services API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gameServerConfigsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing GameServerConfigsClient + CallOptions **GameServerConfigsCallOptions + // The gRPC API client. gameServerConfigsClient gamingpb.GameServerConfigsServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *GameServerConfigsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewGameServerConfigsClient creates a new game server configs service client. +// NewGameServerConfigsClient creates a new game server configs service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The game server config configures the game servers in an Agones fleet. func NewGameServerConfigsClient(ctx context.Context, opts ...option.ClientOption) (*GameServerConfigsClient, error) { - clientOpts := defaultGameServerConfigsClientOptions() - + clientOpts := defaultGameServerConfigsGRPCClientOptions() if newGameServerConfigsClientHook != nil { hookOpts, err := newGameServerConfigsClientHook(ctx, clientHookParams{}) if err != nil { @@ -137,16 +225,19 @@ func NewGameServerConfigsClient(ctx context.Context, opts ...option.ClientOption if err != nil { return nil, err } - c := &GameServerConfigsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultGameServerConfigsCallOptions(), + client := GameServerConfigsClient{CallOptions: defaultGameServerConfigsCallOptions()} + c := &gameServerConfigsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, gameServerConfigsClient: gamingpb.NewGameServerConfigsServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -156,37 +247,36 @@ func NewGameServerConfigsClient(ctx context.Context, opts ...option.ClientOption // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *GameServerConfigsClient) Connection() *grpc.ClientConn { +func (c *gameServerConfigsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *GameServerConfigsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *GameServerConfigsClient) setGoogleClientInfo(keyval ...string) { +func (c *gameServerConfigsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListGameServerConfigs lists game server configs in a given project, location, and game server -// deployment. -func (c *GameServerConfigsClient) ListGameServerConfigs(ctx context.Context, req *gamingpb.ListGameServerConfigsRequest, opts ...gax.CallOption) *GameServerConfigIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gameServerConfigsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gameServerConfigsGRPCClient) ListGameServerConfigs(ctx context.Context, req *gamingpb.ListGameServerConfigsRequest, opts ...gax.CallOption) *GameServerConfigIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListGameServerConfigs[0:len(c.CallOptions.ListGameServerConfigs):len(c.CallOptions.ListGameServerConfigs)], opts...) + opts = append((*c.CallOptions).ListGameServerConfigs[0:len((*c.CallOptions).ListGameServerConfigs):len((*c.CallOptions).ListGameServerConfigs)], opts...) it := &GameServerConfigIterator{} req = proto.Clone(req).(*gamingpb.ListGameServerConfigsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*gamingpb.GameServerConfig, string, error) { @@ -223,8 +313,7 @@ func (c *GameServerConfigsClient) ListGameServerConfigs(ctx context.Context, req return it } -// GetGameServerConfig gets details of a single game server config. -func (c *GameServerConfigsClient) GetGameServerConfig(ctx context.Context, req *gamingpb.GetGameServerConfigRequest, opts ...gax.CallOption) (*gamingpb.GameServerConfig, error) { +func (c *gameServerConfigsGRPCClient) GetGameServerConfig(ctx context.Context, req *gamingpb.GetGameServerConfigRequest, opts ...gax.CallOption) (*gamingpb.GameServerConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -232,7 +321,7 @@ func (c *GameServerConfigsClient) GetGameServerConfig(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetGameServerConfig[0:len(c.CallOptions.GetGameServerConfig):len(c.CallOptions.GetGameServerConfig)], opts...) + opts = append((*c.CallOptions).GetGameServerConfig[0:len((*c.CallOptions).GetGameServerConfig):len((*c.CallOptions).GetGameServerConfig)], opts...) var resp *gamingpb.GameServerConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -245,10 +334,7 @@ func (c *GameServerConfigsClient) GetGameServerConfig(ctx context.Context, req * return resp, nil } -// CreateGameServerConfig creates a new game server config in a given project, location, and game -// server deployment. Game server configs are immutable, and are not applied -// until referenced in the game server deployment rollout resource. -func (c *GameServerConfigsClient) CreateGameServerConfig(ctx context.Context, req *gamingpb.CreateGameServerConfigRequest, opts ...gax.CallOption) (*CreateGameServerConfigOperation, error) { +func (c *gameServerConfigsGRPCClient) CreateGameServerConfig(ctx context.Context, req *gamingpb.CreateGameServerConfigRequest, opts ...gax.CallOption) (*CreateGameServerConfigOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -256,7 +342,7 @@ func (c *GameServerConfigsClient) CreateGameServerConfig(ctx context.Context, re } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateGameServerConfig[0:len(c.CallOptions.CreateGameServerConfig):len(c.CallOptions.CreateGameServerConfig)], opts...) + opts = append((*c.CallOptions).CreateGameServerConfig[0:len((*c.CallOptions).CreateGameServerConfig):len((*c.CallOptions).CreateGameServerConfig)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -267,13 +353,11 @@ func (c *GameServerConfigsClient) CreateGameServerConfig(ctx context.Context, re return nil, err } return &CreateGameServerConfigOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteGameServerConfig deletes a single game server config. The deletion will fail if the game -// server config is referenced in a game server deployment rollout. -func (c *GameServerConfigsClient) DeleteGameServerConfig(ctx context.Context, req *gamingpb.DeleteGameServerConfigRequest, opts ...gax.CallOption) (*DeleteGameServerConfigOperation, error) { +func (c *gameServerConfigsGRPCClient) DeleteGameServerConfig(ctx context.Context, req *gamingpb.DeleteGameServerConfigRequest, opts ...gax.CallOption) (*DeleteGameServerConfigOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -281,7 +365,7 @@ func (c *GameServerConfigsClient) DeleteGameServerConfig(ctx context.Context, re } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteGameServerConfig[0:len(c.CallOptions.DeleteGameServerConfig):len(c.CallOptions.DeleteGameServerConfig)], opts...) + opts = append((*c.CallOptions).DeleteGameServerConfig[0:len((*c.CallOptions).DeleteGameServerConfig):len((*c.CallOptions).DeleteGameServerConfig)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -292,7 +376,7 @@ func (c *GameServerConfigsClient) DeleteGameServerConfig(ctx context.Context, re return nil, err } return &DeleteGameServerConfigOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -303,9 +387,9 @@ type CreateGameServerConfigOperation struct { // CreateGameServerConfigOperation returns a new CreateGameServerConfigOperation from a given name. // The name must be that of a previously created CreateGameServerConfigOperation, possibly from a different process. -func (c *GameServerConfigsClient) CreateGameServerConfigOperation(name string) *CreateGameServerConfigOperation { +func (c *gameServerConfigsGRPCClient) CreateGameServerConfigOperation(name string) *CreateGameServerConfigOperation { return &CreateGameServerConfigOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -372,9 +456,9 @@ type DeleteGameServerConfigOperation struct { // DeleteGameServerConfigOperation returns a new DeleteGameServerConfigOperation from a given name. // The name must be that of a previously created DeleteGameServerConfigOperation, possibly from a different process. -func (c *GameServerConfigsClient) DeleteGameServerConfigOperation(name string) *DeleteGameServerConfigOperation { +func (c *gameServerConfigsGRPCClient) DeleteGameServerConfigOperation(name string) *DeleteGameServerConfigOperation { return &DeleteGameServerConfigOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/gaming/apiv1/game_server_configs_client_example_test.go b/gaming/apiv1/game_server_configs_client_example_test.go index 2d92e99c1c90..fdfde17ae76b 100644 --- a/gaming/apiv1/game_server_configs_client_example_test.go +++ b/gaming/apiv1/game_server_configs_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewGameServerConfigsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleGameServerConfigsClient_ListGameServerConfigs() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gaming.NewGameServerConfigsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.ListGameServerConfigsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleGameServerConfigsClient_ListGameServerConfigs() { } func ExampleGameServerConfigsClient_GetGameServerConfig() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerConfigsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetGameServerConfigRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleGameServerConfigsClient_GetGameServerConfig() { } func ExampleGameServerConfigsClient_CreateGameServerConfig() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerConfigsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.CreateGameServerConfigRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleGameServerConfigsClient_CreateGameServerConfig() { } func ExampleGameServerConfigsClient_DeleteGameServerConfig() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerConfigsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.DeleteGameServerConfigRequest{ // TODO: Fill request struct fields. diff --git a/gaming/apiv1/game_server_deployments_client.go b/gaming/apiv1/game_server_deployments_client.go index 4b06c6d13ced..a065fb7da422 100644 --- a/gaming/apiv1/game_server_deployments_client.go +++ b/gaming/apiv1/game_server_deployments_client.go @@ -53,7 +53,7 @@ type GameServerDeploymentsCallOptions struct { FetchDeploymentState []gax.CallOption } -func defaultGameServerDeploymentsClientOptions() []option.ClientOption { +func defaultGameServerDeploymentsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("gameservices.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("gameservices.mtls.googleapis.com:443"), @@ -129,38 +129,175 @@ func defaultGameServerDeploymentsCallOptions() *GameServerDeploymentsCallOptions } } +// internalGameServerDeploymentsClient is an interface that defines the methods availaible from Game Services API. +type internalGameServerDeploymentsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListGameServerDeployments(context.Context, *gamingpb.ListGameServerDeploymentsRequest, ...gax.CallOption) *GameServerDeploymentIterator + GetGameServerDeployment(context.Context, *gamingpb.GetGameServerDeploymentRequest, ...gax.CallOption) (*gamingpb.GameServerDeployment, error) + CreateGameServerDeployment(context.Context, *gamingpb.CreateGameServerDeploymentRequest, ...gax.CallOption) (*CreateGameServerDeploymentOperation, error) + CreateGameServerDeploymentOperation(name string) *CreateGameServerDeploymentOperation + DeleteGameServerDeployment(context.Context, *gamingpb.DeleteGameServerDeploymentRequest, ...gax.CallOption) (*DeleteGameServerDeploymentOperation, error) + DeleteGameServerDeploymentOperation(name string) *DeleteGameServerDeploymentOperation + UpdateGameServerDeployment(context.Context, *gamingpb.UpdateGameServerDeploymentRequest, ...gax.CallOption) (*UpdateGameServerDeploymentOperation, error) + UpdateGameServerDeploymentOperation(name string) *UpdateGameServerDeploymentOperation + GetGameServerDeploymentRollout(context.Context, *gamingpb.GetGameServerDeploymentRolloutRequest, ...gax.CallOption) (*gamingpb.GameServerDeploymentRollout, error) + UpdateGameServerDeploymentRollout(context.Context, *gamingpb.UpdateGameServerDeploymentRolloutRequest, ...gax.CallOption) (*UpdateGameServerDeploymentRolloutOperation, error) + UpdateGameServerDeploymentRolloutOperation(name string) *UpdateGameServerDeploymentRolloutOperation + PreviewGameServerDeploymentRollout(context.Context, *gamingpb.PreviewGameServerDeploymentRolloutRequest, ...gax.CallOption) (*gamingpb.PreviewGameServerDeploymentRolloutResponse, error) + FetchDeploymentState(context.Context, *gamingpb.FetchDeploymentStateRequest, ...gax.CallOption) (*gamingpb.FetchDeploymentStateResponse, error) +} + // GameServerDeploymentsClient is a client for interacting with Game Services API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The game server deployment is used to control the deployment of Agones +// fleets. type GameServerDeploymentsClient struct { + // The internal transport-dependent client. + internalClient internalGameServerDeploymentsClient + + // The call options for this service. + CallOptions *GameServerDeploymentsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *GameServerDeploymentsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *GameServerDeploymentsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *GameServerDeploymentsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListGameServerDeployments lists game server deployments in a given project and location. +func (c *GameServerDeploymentsClient) ListGameServerDeployments(ctx context.Context, req *gamingpb.ListGameServerDeploymentsRequest, opts ...gax.CallOption) *GameServerDeploymentIterator { + return c.internalClient.ListGameServerDeployments(ctx, req, opts...) +} + +// GetGameServerDeployment gets details of a single game server deployment. +func (c *GameServerDeploymentsClient) GetGameServerDeployment(ctx context.Context, req *gamingpb.GetGameServerDeploymentRequest, opts ...gax.CallOption) (*gamingpb.GameServerDeployment, error) { + return c.internalClient.GetGameServerDeployment(ctx, req, opts...) +} + +// CreateGameServerDeployment creates a new game server deployment in a given project and location. +func (c *GameServerDeploymentsClient) CreateGameServerDeployment(ctx context.Context, req *gamingpb.CreateGameServerDeploymentRequest, opts ...gax.CallOption) (*CreateGameServerDeploymentOperation, error) { + return c.internalClient.CreateGameServerDeployment(ctx, req, opts...) +} + +// CreateGameServerDeploymentOperation returns a new CreateGameServerDeploymentOperation from a given name. +// The name must be that of a previously created CreateGameServerDeploymentOperation, possibly from a different process. +func (c *GameServerDeploymentsClient) CreateGameServerDeploymentOperation(name string) *CreateGameServerDeploymentOperation { + return c.internalClient.CreateGameServerDeploymentOperation(name) +} + +// DeleteGameServerDeployment deletes a single game server deployment. +func (c *GameServerDeploymentsClient) DeleteGameServerDeployment(ctx context.Context, req *gamingpb.DeleteGameServerDeploymentRequest, opts ...gax.CallOption) (*DeleteGameServerDeploymentOperation, error) { + return c.internalClient.DeleteGameServerDeployment(ctx, req, opts...) +} + +// DeleteGameServerDeploymentOperation returns a new DeleteGameServerDeploymentOperation from a given name. +// The name must be that of a previously created DeleteGameServerDeploymentOperation, possibly from a different process. +func (c *GameServerDeploymentsClient) DeleteGameServerDeploymentOperation(name string) *DeleteGameServerDeploymentOperation { + return c.internalClient.DeleteGameServerDeploymentOperation(name) +} + +// UpdateGameServerDeployment patches a game server deployment. +func (c *GameServerDeploymentsClient) UpdateGameServerDeployment(ctx context.Context, req *gamingpb.UpdateGameServerDeploymentRequest, opts ...gax.CallOption) (*UpdateGameServerDeploymentOperation, error) { + return c.internalClient.UpdateGameServerDeployment(ctx, req, opts...) +} + +// UpdateGameServerDeploymentOperation returns a new UpdateGameServerDeploymentOperation from a given name. +// The name must be that of a previously created UpdateGameServerDeploymentOperation, possibly from a different process. +func (c *GameServerDeploymentsClient) UpdateGameServerDeploymentOperation(name string) *UpdateGameServerDeploymentOperation { + return c.internalClient.UpdateGameServerDeploymentOperation(name) +} + +// GetGameServerDeploymentRollout gets details a single game server deployment rollout. +func (c *GameServerDeploymentsClient) GetGameServerDeploymentRollout(ctx context.Context, req *gamingpb.GetGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*gamingpb.GameServerDeploymentRollout, error) { + return c.internalClient.GetGameServerDeploymentRollout(ctx, req, opts...) +} + +// UpdateGameServerDeploymentRollout patches a single game server deployment rollout. +// The method will not return an error if the update does not affect any +// existing realms. For example - if the default_game_server_config is changed +// but all existing realms use the override, that is valid. Similarly, if a +// non existing realm is explicitly called out in game_server_config_overrides +// field, that will also not result in an error. +func (c *GameServerDeploymentsClient) UpdateGameServerDeploymentRollout(ctx context.Context, req *gamingpb.UpdateGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*UpdateGameServerDeploymentRolloutOperation, error) { + return c.internalClient.UpdateGameServerDeploymentRollout(ctx, req, opts...) +} + +// UpdateGameServerDeploymentRolloutOperation returns a new UpdateGameServerDeploymentRolloutOperation from a given name. +// The name must be that of a previously created UpdateGameServerDeploymentRolloutOperation, possibly from a different process. +func (c *GameServerDeploymentsClient) UpdateGameServerDeploymentRolloutOperation(name string) *UpdateGameServerDeploymentRolloutOperation { + return c.internalClient.UpdateGameServerDeploymentRolloutOperation(name) +} + +// PreviewGameServerDeploymentRollout previews the game server deployment rollout. This API does not mutate the +// rollout resource. +func (c *GameServerDeploymentsClient) PreviewGameServerDeploymentRollout(ctx context.Context, req *gamingpb.PreviewGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*gamingpb.PreviewGameServerDeploymentRolloutResponse, error) { + return c.internalClient.PreviewGameServerDeploymentRollout(ctx, req, opts...) +} + +// FetchDeploymentState retrieves information about the current state of the game server +// deployment. Gathers all the Agones fleets and Agones autoscalers, +// including fleets running an older version of the game server deployment. +func (c *GameServerDeploymentsClient) FetchDeploymentState(ctx context.Context, req *gamingpb.FetchDeploymentStateRequest, opts ...gax.CallOption) (*gamingpb.FetchDeploymentStateResponse, error) { + return c.internalClient.FetchDeploymentState(ctx, req, opts...) +} + +// gameServerDeploymentsGRPCClient is a client for interacting with Game Services API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gameServerDeploymentsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing GameServerDeploymentsClient + CallOptions **GameServerDeploymentsCallOptions + // The gRPC API client. gameServerDeploymentsClient gamingpb.GameServerDeploymentsServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *GameServerDeploymentsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewGameServerDeploymentsClient creates a new game server deployments service client. +// NewGameServerDeploymentsClient creates a new game server deployments service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The game server deployment is used to control the deployment of Agones // fleets. func NewGameServerDeploymentsClient(ctx context.Context, opts ...option.ClientOption) (*GameServerDeploymentsClient, error) { - clientOpts := defaultGameServerDeploymentsClientOptions() - + clientOpts := defaultGameServerDeploymentsGRPCClientOptions() if newGameServerDeploymentsClientHook != nil { hookOpts, err := newGameServerDeploymentsClientHook(ctx, clientHookParams{}) if err != nil { @@ -178,16 +315,19 @@ func NewGameServerDeploymentsClient(ctx context.Context, opts ...option.ClientOp if err != nil { return nil, err } - c := &GameServerDeploymentsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultGameServerDeploymentsCallOptions(), + client := GameServerDeploymentsClient{CallOptions: defaultGameServerDeploymentsCallOptions()} + c := &gameServerDeploymentsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, gameServerDeploymentsClient: gamingpb.NewGameServerDeploymentsServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -197,36 +337,36 @@ func NewGameServerDeploymentsClient(ctx context.Context, opts ...option.ClientOp // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *GameServerDeploymentsClient) Connection() *grpc.ClientConn { +func (c *gameServerDeploymentsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *GameServerDeploymentsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *GameServerDeploymentsClient) setGoogleClientInfo(keyval ...string) { +func (c *gameServerDeploymentsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListGameServerDeployments lists game server deployments in a given project and location. -func (c *GameServerDeploymentsClient) ListGameServerDeployments(ctx context.Context, req *gamingpb.ListGameServerDeploymentsRequest, opts ...gax.CallOption) *GameServerDeploymentIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gameServerDeploymentsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gameServerDeploymentsGRPCClient) ListGameServerDeployments(ctx context.Context, req *gamingpb.ListGameServerDeploymentsRequest, opts ...gax.CallOption) *GameServerDeploymentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListGameServerDeployments[0:len(c.CallOptions.ListGameServerDeployments):len(c.CallOptions.ListGameServerDeployments)], opts...) + opts = append((*c.CallOptions).ListGameServerDeployments[0:len((*c.CallOptions).ListGameServerDeployments):len((*c.CallOptions).ListGameServerDeployments)], opts...) it := &GameServerDeploymentIterator{} req = proto.Clone(req).(*gamingpb.ListGameServerDeploymentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*gamingpb.GameServerDeployment, string, error) { @@ -263,8 +403,7 @@ func (c *GameServerDeploymentsClient) ListGameServerDeployments(ctx context.Cont return it } -// GetGameServerDeployment gets details of a single game server deployment. -func (c *GameServerDeploymentsClient) GetGameServerDeployment(ctx context.Context, req *gamingpb.GetGameServerDeploymentRequest, opts ...gax.CallOption) (*gamingpb.GameServerDeployment, error) { +func (c *gameServerDeploymentsGRPCClient) GetGameServerDeployment(ctx context.Context, req *gamingpb.GetGameServerDeploymentRequest, opts ...gax.CallOption) (*gamingpb.GameServerDeployment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -272,7 +411,7 @@ func (c *GameServerDeploymentsClient) GetGameServerDeployment(ctx context.Contex } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetGameServerDeployment[0:len(c.CallOptions.GetGameServerDeployment):len(c.CallOptions.GetGameServerDeployment)], opts...) + opts = append((*c.CallOptions).GetGameServerDeployment[0:len((*c.CallOptions).GetGameServerDeployment):len((*c.CallOptions).GetGameServerDeployment)], opts...) var resp *gamingpb.GameServerDeployment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -285,8 +424,7 @@ func (c *GameServerDeploymentsClient) GetGameServerDeployment(ctx context.Contex return resp, nil } -// CreateGameServerDeployment creates a new game server deployment in a given project and location. -func (c *GameServerDeploymentsClient) CreateGameServerDeployment(ctx context.Context, req *gamingpb.CreateGameServerDeploymentRequest, opts ...gax.CallOption) (*CreateGameServerDeploymentOperation, error) { +func (c *gameServerDeploymentsGRPCClient) CreateGameServerDeployment(ctx context.Context, req *gamingpb.CreateGameServerDeploymentRequest, opts ...gax.CallOption) (*CreateGameServerDeploymentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -294,7 +432,7 @@ func (c *GameServerDeploymentsClient) CreateGameServerDeployment(ctx context.Con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateGameServerDeployment[0:len(c.CallOptions.CreateGameServerDeployment):len(c.CallOptions.CreateGameServerDeployment)], opts...) + opts = append((*c.CallOptions).CreateGameServerDeployment[0:len((*c.CallOptions).CreateGameServerDeployment):len((*c.CallOptions).CreateGameServerDeployment)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -305,12 +443,11 @@ func (c *GameServerDeploymentsClient) CreateGameServerDeployment(ctx context.Con return nil, err } return &CreateGameServerDeploymentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteGameServerDeployment deletes a single game server deployment. -func (c *GameServerDeploymentsClient) DeleteGameServerDeployment(ctx context.Context, req *gamingpb.DeleteGameServerDeploymentRequest, opts ...gax.CallOption) (*DeleteGameServerDeploymentOperation, error) { +func (c *gameServerDeploymentsGRPCClient) DeleteGameServerDeployment(ctx context.Context, req *gamingpb.DeleteGameServerDeploymentRequest, opts ...gax.CallOption) (*DeleteGameServerDeploymentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -318,7 +455,7 @@ func (c *GameServerDeploymentsClient) DeleteGameServerDeployment(ctx context.Con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteGameServerDeployment[0:len(c.CallOptions.DeleteGameServerDeployment):len(c.CallOptions.DeleteGameServerDeployment)], opts...) + opts = append((*c.CallOptions).DeleteGameServerDeployment[0:len((*c.CallOptions).DeleteGameServerDeployment):len((*c.CallOptions).DeleteGameServerDeployment)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -329,12 +466,11 @@ func (c *GameServerDeploymentsClient) DeleteGameServerDeployment(ctx context.Con return nil, err } return &DeleteGameServerDeploymentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateGameServerDeployment patches a game server deployment. -func (c *GameServerDeploymentsClient) UpdateGameServerDeployment(ctx context.Context, req *gamingpb.UpdateGameServerDeploymentRequest, opts ...gax.CallOption) (*UpdateGameServerDeploymentOperation, error) { +func (c *gameServerDeploymentsGRPCClient) UpdateGameServerDeployment(ctx context.Context, req *gamingpb.UpdateGameServerDeploymentRequest, opts ...gax.CallOption) (*UpdateGameServerDeploymentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -342,7 +478,7 @@ func (c *GameServerDeploymentsClient) UpdateGameServerDeployment(ctx context.Con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "game_server_deployment.name", url.QueryEscape(req.GetGameServerDeployment().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateGameServerDeployment[0:len(c.CallOptions.UpdateGameServerDeployment):len(c.CallOptions.UpdateGameServerDeployment)], opts...) + opts = append((*c.CallOptions).UpdateGameServerDeployment[0:len((*c.CallOptions).UpdateGameServerDeployment):len((*c.CallOptions).UpdateGameServerDeployment)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -353,12 +489,11 @@ func (c *GameServerDeploymentsClient) UpdateGameServerDeployment(ctx context.Con return nil, err } return &UpdateGameServerDeploymentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetGameServerDeploymentRollout gets details a single game server deployment rollout. -func (c *GameServerDeploymentsClient) GetGameServerDeploymentRollout(ctx context.Context, req *gamingpb.GetGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*gamingpb.GameServerDeploymentRollout, error) { +func (c *gameServerDeploymentsGRPCClient) GetGameServerDeploymentRollout(ctx context.Context, req *gamingpb.GetGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*gamingpb.GameServerDeploymentRollout, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -366,7 +501,7 @@ func (c *GameServerDeploymentsClient) GetGameServerDeploymentRollout(ctx context } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetGameServerDeploymentRollout[0:len(c.CallOptions.GetGameServerDeploymentRollout):len(c.CallOptions.GetGameServerDeploymentRollout)], opts...) + opts = append((*c.CallOptions).GetGameServerDeploymentRollout[0:len((*c.CallOptions).GetGameServerDeploymentRollout):len((*c.CallOptions).GetGameServerDeploymentRollout)], opts...) var resp *gamingpb.GameServerDeploymentRollout err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -379,13 +514,7 @@ func (c *GameServerDeploymentsClient) GetGameServerDeploymentRollout(ctx context return resp, nil } -// UpdateGameServerDeploymentRollout patches a single game server deployment rollout. -// The method will not return an error if the update does not affect any -// existing realms. For example - if the default_game_server_config is changed -// but all existing realms use the override, that is valid. Similarly, if a -// non existing realm is explicitly called out in game_server_config_overrides -// field, that will also not result in an error. -func (c *GameServerDeploymentsClient) UpdateGameServerDeploymentRollout(ctx context.Context, req *gamingpb.UpdateGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*UpdateGameServerDeploymentRolloutOperation, error) { +func (c *gameServerDeploymentsGRPCClient) UpdateGameServerDeploymentRollout(ctx context.Context, req *gamingpb.UpdateGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*UpdateGameServerDeploymentRolloutOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -393,7 +522,7 @@ func (c *GameServerDeploymentsClient) UpdateGameServerDeploymentRollout(ctx cont } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "rollout.name", url.QueryEscape(req.GetRollout().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateGameServerDeploymentRollout[0:len(c.CallOptions.UpdateGameServerDeploymentRollout):len(c.CallOptions.UpdateGameServerDeploymentRollout)], opts...) + opts = append((*c.CallOptions).UpdateGameServerDeploymentRollout[0:len((*c.CallOptions).UpdateGameServerDeploymentRollout):len((*c.CallOptions).UpdateGameServerDeploymentRollout)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -404,13 +533,11 @@ func (c *GameServerDeploymentsClient) UpdateGameServerDeploymentRollout(ctx cont return nil, err } return &UpdateGameServerDeploymentRolloutOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// PreviewGameServerDeploymentRollout previews the game server deployment rollout. This API does not mutate the -// rollout resource. -func (c *GameServerDeploymentsClient) PreviewGameServerDeploymentRollout(ctx context.Context, req *gamingpb.PreviewGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*gamingpb.PreviewGameServerDeploymentRolloutResponse, error) { +func (c *gameServerDeploymentsGRPCClient) PreviewGameServerDeploymentRollout(ctx context.Context, req *gamingpb.PreviewGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*gamingpb.PreviewGameServerDeploymentRolloutResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -418,7 +545,7 @@ func (c *GameServerDeploymentsClient) PreviewGameServerDeploymentRollout(ctx con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "rollout.name", url.QueryEscape(req.GetRollout().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PreviewGameServerDeploymentRollout[0:len(c.CallOptions.PreviewGameServerDeploymentRollout):len(c.CallOptions.PreviewGameServerDeploymentRollout)], opts...) + opts = append((*c.CallOptions).PreviewGameServerDeploymentRollout[0:len((*c.CallOptions).PreviewGameServerDeploymentRollout):len((*c.CallOptions).PreviewGameServerDeploymentRollout)], opts...) var resp *gamingpb.PreviewGameServerDeploymentRolloutResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -431,10 +558,7 @@ func (c *GameServerDeploymentsClient) PreviewGameServerDeploymentRollout(ctx con return resp, nil } -// FetchDeploymentState retrieves information about the current state of the game server -// deployment. Gathers all the Agones fleets and Agones autoscalers, -// including fleets running an older version of the game server deployment. -func (c *GameServerDeploymentsClient) FetchDeploymentState(ctx context.Context, req *gamingpb.FetchDeploymentStateRequest, opts ...gax.CallOption) (*gamingpb.FetchDeploymentStateResponse, error) { +func (c *gameServerDeploymentsGRPCClient) FetchDeploymentState(ctx context.Context, req *gamingpb.FetchDeploymentStateRequest, opts ...gax.CallOption) (*gamingpb.FetchDeploymentStateResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -442,7 +566,7 @@ func (c *GameServerDeploymentsClient) FetchDeploymentState(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.FetchDeploymentState[0:len(c.CallOptions.FetchDeploymentState):len(c.CallOptions.FetchDeploymentState)], opts...) + opts = append((*c.CallOptions).FetchDeploymentState[0:len((*c.CallOptions).FetchDeploymentState):len((*c.CallOptions).FetchDeploymentState)], opts...) var resp *gamingpb.FetchDeploymentStateResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -462,9 +586,9 @@ type CreateGameServerDeploymentOperation struct { // CreateGameServerDeploymentOperation returns a new CreateGameServerDeploymentOperation from a given name. // The name must be that of a previously created CreateGameServerDeploymentOperation, possibly from a different process. -func (c *GameServerDeploymentsClient) CreateGameServerDeploymentOperation(name string) *CreateGameServerDeploymentOperation { +func (c *gameServerDeploymentsGRPCClient) CreateGameServerDeploymentOperation(name string) *CreateGameServerDeploymentOperation { return &CreateGameServerDeploymentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -531,9 +655,9 @@ type DeleteGameServerDeploymentOperation struct { // DeleteGameServerDeploymentOperation returns a new DeleteGameServerDeploymentOperation from a given name. // The name must be that of a previously created DeleteGameServerDeploymentOperation, possibly from a different process. -func (c *GameServerDeploymentsClient) DeleteGameServerDeploymentOperation(name string) *DeleteGameServerDeploymentOperation { +func (c *gameServerDeploymentsGRPCClient) DeleteGameServerDeploymentOperation(name string) *DeleteGameServerDeploymentOperation { return &DeleteGameServerDeploymentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -589,9 +713,9 @@ type UpdateGameServerDeploymentOperation struct { // UpdateGameServerDeploymentOperation returns a new UpdateGameServerDeploymentOperation from a given name. // The name must be that of a previously created UpdateGameServerDeploymentOperation, possibly from a different process. -func (c *GameServerDeploymentsClient) UpdateGameServerDeploymentOperation(name string) *UpdateGameServerDeploymentOperation { +func (c *gameServerDeploymentsGRPCClient) UpdateGameServerDeploymentOperation(name string) *UpdateGameServerDeploymentOperation { return &UpdateGameServerDeploymentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -658,9 +782,9 @@ type UpdateGameServerDeploymentRolloutOperation struct { // UpdateGameServerDeploymentRolloutOperation returns a new UpdateGameServerDeploymentRolloutOperation from a given name. // The name must be that of a previously created UpdateGameServerDeploymentRolloutOperation, possibly from a different process. -func (c *GameServerDeploymentsClient) UpdateGameServerDeploymentRolloutOperation(name string) *UpdateGameServerDeploymentRolloutOperation { +func (c *gameServerDeploymentsGRPCClient) UpdateGameServerDeploymentRolloutOperation(name string) *UpdateGameServerDeploymentRolloutOperation { return &UpdateGameServerDeploymentRolloutOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/gaming/apiv1/game_server_deployments_client_example_test.go b/gaming/apiv1/game_server_deployments_client_example_test.go index 4237050e8a41..87674fb7ed0b 100644 --- a/gaming/apiv1/game_server_deployments_client_example_test.go +++ b/gaming/apiv1/game_server_deployments_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewGameServerDeploymentsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleGameServerDeploymentsClient_ListGameServerDeployments() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.ListGameServerDeploymentsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleGameServerDeploymentsClient_ListGameServerDeployments() { } func ExampleGameServerDeploymentsClient_GetGameServerDeployment() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetGameServerDeploymentRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleGameServerDeploymentsClient_GetGameServerDeployment() { } func ExampleGameServerDeploymentsClient_CreateGameServerDeployment() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.CreateGameServerDeploymentRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleGameServerDeploymentsClient_CreateGameServerDeployment() { } func ExampleGameServerDeploymentsClient_DeleteGameServerDeployment() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.DeleteGameServerDeploymentRequest{ // TODO: Fill request struct fields. @@ -130,13 +127,12 @@ func ExampleGameServerDeploymentsClient_DeleteGameServerDeployment() { } func ExampleGameServerDeploymentsClient_UpdateGameServerDeployment() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.UpdateGameServerDeploymentRequest{ // TODO: Fill request struct fields. @@ -155,13 +151,12 @@ func ExampleGameServerDeploymentsClient_UpdateGameServerDeployment() { } func ExampleGameServerDeploymentsClient_GetGameServerDeploymentRollout() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetGameServerDeploymentRolloutRequest{ // TODO: Fill request struct fields. @@ -175,13 +170,12 @@ func ExampleGameServerDeploymentsClient_GetGameServerDeploymentRollout() { } func ExampleGameServerDeploymentsClient_UpdateGameServerDeploymentRollout() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.UpdateGameServerDeploymentRolloutRequest{ // TODO: Fill request struct fields. @@ -200,13 +194,12 @@ func ExampleGameServerDeploymentsClient_UpdateGameServerDeploymentRollout() { } func ExampleGameServerDeploymentsClient_PreviewGameServerDeploymentRollout() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewGameServerDeploymentRolloutRequest{ // TODO: Fill request struct fields. @@ -220,13 +213,12 @@ func ExampleGameServerDeploymentsClient_PreviewGameServerDeploymentRollout() { } func ExampleGameServerDeploymentsClient_FetchDeploymentState() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.FetchDeploymentStateRequest{ // TODO: Fill request struct fields. diff --git a/gaming/apiv1/realms_client.go b/gaming/apiv1/realms_client.go index 7821a056d70b..1f98b7d106e7 100644 --- a/gaming/apiv1/realms_client.go +++ b/gaming/apiv1/realms_client.go @@ -50,7 +50,7 @@ type RealmsCallOptions struct { PreviewRealmUpdate []gax.CallOption } -func defaultRealmsClientOptions() []option.ClientOption { +func defaultRealmsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("gameservices.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("gameservices.mtls.googleapis.com:443"), @@ -103,38 +103,142 @@ func defaultRealmsCallOptions() *RealmsCallOptions { } } +// internalRealmsClient is an interface that defines the methods availaible from Game Services API. +type internalRealmsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListRealms(context.Context, *gamingpb.ListRealmsRequest, ...gax.CallOption) *RealmIterator + GetRealm(context.Context, *gamingpb.GetRealmRequest, ...gax.CallOption) (*gamingpb.Realm, error) + CreateRealm(context.Context, *gamingpb.CreateRealmRequest, ...gax.CallOption) (*CreateRealmOperation, error) + CreateRealmOperation(name string) *CreateRealmOperation + DeleteRealm(context.Context, *gamingpb.DeleteRealmRequest, ...gax.CallOption) (*DeleteRealmOperation, error) + DeleteRealmOperation(name string) *DeleteRealmOperation + UpdateRealm(context.Context, *gamingpb.UpdateRealmRequest, ...gax.CallOption) (*UpdateRealmOperation, error) + UpdateRealmOperation(name string) *UpdateRealmOperation + PreviewRealmUpdate(context.Context, *gamingpb.PreviewRealmUpdateRequest, ...gax.CallOption) (*gamingpb.PreviewRealmUpdateResponse, error) +} + // RealmsClient is a client for interacting with Game Services API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A realm is a grouping of game server clusters that are considered +// interchangeable. type RealmsClient struct { + // The internal transport-dependent client. + internalClient internalRealmsClient + + // The call options for this service. + CallOptions *RealmsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *RealmsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *RealmsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *RealmsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListRealms lists realms in a given project and location. +func (c *RealmsClient) ListRealms(ctx context.Context, req *gamingpb.ListRealmsRequest, opts ...gax.CallOption) *RealmIterator { + return c.internalClient.ListRealms(ctx, req, opts...) +} + +// GetRealm gets details of a single realm. +func (c *RealmsClient) GetRealm(ctx context.Context, req *gamingpb.GetRealmRequest, opts ...gax.CallOption) (*gamingpb.Realm, error) { + return c.internalClient.GetRealm(ctx, req, opts...) +} + +// CreateRealm creates a new realm in a given project and location. +func (c *RealmsClient) CreateRealm(ctx context.Context, req *gamingpb.CreateRealmRequest, opts ...gax.CallOption) (*CreateRealmOperation, error) { + return c.internalClient.CreateRealm(ctx, req, opts...) +} + +// CreateRealmOperation returns a new CreateRealmOperation from a given name. +// The name must be that of a previously created CreateRealmOperation, possibly from a different process. +func (c *RealmsClient) CreateRealmOperation(name string) *CreateRealmOperation { + return c.internalClient.CreateRealmOperation(name) +} + +// DeleteRealm deletes a single realm. +func (c *RealmsClient) DeleteRealm(ctx context.Context, req *gamingpb.DeleteRealmRequest, opts ...gax.CallOption) (*DeleteRealmOperation, error) { + return c.internalClient.DeleteRealm(ctx, req, opts...) +} + +// DeleteRealmOperation returns a new DeleteRealmOperation from a given name. +// The name must be that of a previously created DeleteRealmOperation, possibly from a different process. +func (c *RealmsClient) DeleteRealmOperation(name string) *DeleteRealmOperation { + return c.internalClient.DeleteRealmOperation(name) +} + +// UpdateRealm patches a single realm. +func (c *RealmsClient) UpdateRealm(ctx context.Context, req *gamingpb.UpdateRealmRequest, opts ...gax.CallOption) (*UpdateRealmOperation, error) { + return c.internalClient.UpdateRealm(ctx, req, opts...) +} + +// UpdateRealmOperation returns a new UpdateRealmOperation from a given name. +// The name must be that of a previously created UpdateRealmOperation, possibly from a different process. +func (c *RealmsClient) UpdateRealmOperation(name string) *UpdateRealmOperation { + return c.internalClient.UpdateRealmOperation(name) +} + +// PreviewRealmUpdate previews patches to a single realm. +func (c *RealmsClient) PreviewRealmUpdate(ctx context.Context, req *gamingpb.PreviewRealmUpdateRequest, opts ...gax.CallOption) (*gamingpb.PreviewRealmUpdateResponse, error) { + return c.internalClient.PreviewRealmUpdate(ctx, req, opts...) +} + +// realmsGRPCClient is a client for interacting with Game Services API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type realmsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing RealmsClient + CallOptions **RealmsCallOptions + // The gRPC API client. realmsClient gamingpb.RealmsServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *RealmsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewRealmsClient creates a new realms service client. +// NewRealmsClient creates a new realms service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A realm is a grouping of game server clusters that are considered // interchangeable. func NewRealmsClient(ctx context.Context, opts ...option.ClientOption) (*RealmsClient, error) { - clientOpts := defaultRealmsClientOptions() - + clientOpts := defaultRealmsGRPCClientOptions() if newRealmsClientHook != nil { hookOpts, err := newRealmsClientHook(ctx, clientHookParams{}) if err != nil { @@ -152,16 +256,19 @@ func NewRealmsClient(ctx context.Context, opts ...option.ClientOption) (*RealmsC if err != nil { return nil, err } - c := &RealmsClient{ + client := RealmsClient{CallOptions: defaultRealmsCallOptions()} + + c := &realmsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultRealmsCallOptions(), - - realmsClient: gamingpb.NewRealmsServiceClient(connPool), + realmsClient: gamingpb.NewRealmsServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -171,36 +278,36 @@ func NewRealmsClient(ctx context.Context, opts ...option.ClientOption) (*RealmsC // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *RealmsClient) Connection() *grpc.ClientConn { +func (c *realmsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *RealmsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *RealmsClient) setGoogleClientInfo(keyval ...string) { +func (c *realmsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListRealms lists realms in a given project and location. -func (c *RealmsClient) ListRealms(ctx context.Context, req *gamingpb.ListRealmsRequest, opts ...gax.CallOption) *RealmIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *realmsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *realmsGRPCClient) ListRealms(ctx context.Context, req *gamingpb.ListRealmsRequest, opts ...gax.CallOption) *RealmIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListRealms[0:len(c.CallOptions.ListRealms):len(c.CallOptions.ListRealms)], opts...) + opts = append((*c.CallOptions).ListRealms[0:len((*c.CallOptions).ListRealms):len((*c.CallOptions).ListRealms)], opts...) it := &RealmIterator{} req = proto.Clone(req).(*gamingpb.ListRealmsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*gamingpb.Realm, string, error) { @@ -237,8 +344,7 @@ func (c *RealmsClient) ListRealms(ctx context.Context, req *gamingpb.ListRealmsR return it } -// GetRealm gets details of a single realm. -func (c *RealmsClient) GetRealm(ctx context.Context, req *gamingpb.GetRealmRequest, opts ...gax.CallOption) (*gamingpb.Realm, error) { +func (c *realmsGRPCClient) GetRealm(ctx context.Context, req *gamingpb.GetRealmRequest, opts ...gax.CallOption) (*gamingpb.Realm, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -246,7 +352,7 @@ func (c *RealmsClient) GetRealm(ctx context.Context, req *gamingpb.GetRealmReque } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetRealm[0:len(c.CallOptions.GetRealm):len(c.CallOptions.GetRealm)], opts...) + opts = append((*c.CallOptions).GetRealm[0:len((*c.CallOptions).GetRealm):len((*c.CallOptions).GetRealm)], opts...) var resp *gamingpb.Realm err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -259,8 +365,7 @@ func (c *RealmsClient) GetRealm(ctx context.Context, req *gamingpb.GetRealmReque return resp, nil } -// CreateRealm creates a new realm in a given project and location. -func (c *RealmsClient) CreateRealm(ctx context.Context, req *gamingpb.CreateRealmRequest, opts ...gax.CallOption) (*CreateRealmOperation, error) { +func (c *realmsGRPCClient) CreateRealm(ctx context.Context, req *gamingpb.CreateRealmRequest, opts ...gax.CallOption) (*CreateRealmOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -268,7 +373,7 @@ func (c *RealmsClient) CreateRealm(ctx context.Context, req *gamingpb.CreateReal } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateRealm[0:len(c.CallOptions.CreateRealm):len(c.CallOptions.CreateRealm)], opts...) + opts = append((*c.CallOptions).CreateRealm[0:len((*c.CallOptions).CreateRealm):len((*c.CallOptions).CreateRealm)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -279,12 +384,11 @@ func (c *RealmsClient) CreateRealm(ctx context.Context, req *gamingpb.CreateReal return nil, err } return &CreateRealmOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteRealm deletes a single realm. -func (c *RealmsClient) DeleteRealm(ctx context.Context, req *gamingpb.DeleteRealmRequest, opts ...gax.CallOption) (*DeleteRealmOperation, error) { +func (c *realmsGRPCClient) DeleteRealm(ctx context.Context, req *gamingpb.DeleteRealmRequest, opts ...gax.CallOption) (*DeleteRealmOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -292,7 +396,7 @@ func (c *RealmsClient) DeleteRealm(ctx context.Context, req *gamingpb.DeleteReal } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteRealm[0:len(c.CallOptions.DeleteRealm):len(c.CallOptions.DeleteRealm)], opts...) + opts = append((*c.CallOptions).DeleteRealm[0:len((*c.CallOptions).DeleteRealm):len((*c.CallOptions).DeleteRealm)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -303,12 +407,11 @@ func (c *RealmsClient) DeleteRealm(ctx context.Context, req *gamingpb.DeleteReal return nil, err } return &DeleteRealmOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateRealm patches a single realm. -func (c *RealmsClient) UpdateRealm(ctx context.Context, req *gamingpb.UpdateRealmRequest, opts ...gax.CallOption) (*UpdateRealmOperation, error) { +func (c *realmsGRPCClient) UpdateRealm(ctx context.Context, req *gamingpb.UpdateRealmRequest, opts ...gax.CallOption) (*UpdateRealmOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -316,7 +419,7 @@ func (c *RealmsClient) UpdateRealm(ctx context.Context, req *gamingpb.UpdateReal } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "realm.name", url.QueryEscape(req.GetRealm().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateRealm[0:len(c.CallOptions.UpdateRealm):len(c.CallOptions.UpdateRealm)], opts...) + opts = append((*c.CallOptions).UpdateRealm[0:len((*c.CallOptions).UpdateRealm):len((*c.CallOptions).UpdateRealm)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -327,12 +430,11 @@ func (c *RealmsClient) UpdateRealm(ctx context.Context, req *gamingpb.UpdateReal return nil, err } return &UpdateRealmOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// PreviewRealmUpdate previews patches to a single realm. -func (c *RealmsClient) PreviewRealmUpdate(ctx context.Context, req *gamingpb.PreviewRealmUpdateRequest, opts ...gax.CallOption) (*gamingpb.PreviewRealmUpdateResponse, error) { +func (c *realmsGRPCClient) PreviewRealmUpdate(ctx context.Context, req *gamingpb.PreviewRealmUpdateRequest, opts ...gax.CallOption) (*gamingpb.PreviewRealmUpdateResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -340,7 +442,7 @@ func (c *RealmsClient) PreviewRealmUpdate(ctx context.Context, req *gamingpb.Pre } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "realm.name", url.QueryEscape(req.GetRealm().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PreviewRealmUpdate[0:len(c.CallOptions.PreviewRealmUpdate):len(c.CallOptions.PreviewRealmUpdate)], opts...) + opts = append((*c.CallOptions).PreviewRealmUpdate[0:len((*c.CallOptions).PreviewRealmUpdate):len((*c.CallOptions).PreviewRealmUpdate)], opts...) var resp *gamingpb.PreviewRealmUpdateResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -360,9 +462,9 @@ type CreateRealmOperation struct { // CreateRealmOperation returns a new CreateRealmOperation from a given name. // The name must be that of a previously created CreateRealmOperation, possibly from a different process. -func (c *RealmsClient) CreateRealmOperation(name string) *CreateRealmOperation { +func (c *realmsGRPCClient) CreateRealmOperation(name string) *CreateRealmOperation { return &CreateRealmOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -429,9 +531,9 @@ type DeleteRealmOperation struct { // DeleteRealmOperation returns a new DeleteRealmOperation from a given name. // The name must be that of a previously created DeleteRealmOperation, possibly from a different process. -func (c *RealmsClient) DeleteRealmOperation(name string) *DeleteRealmOperation { +func (c *realmsGRPCClient) DeleteRealmOperation(name string) *DeleteRealmOperation { return &DeleteRealmOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -487,9 +589,9 @@ type UpdateRealmOperation struct { // UpdateRealmOperation returns a new UpdateRealmOperation from a given name. // The name must be that of a previously created UpdateRealmOperation, possibly from a different process. -func (c *RealmsClient) UpdateRealmOperation(name string) *UpdateRealmOperation { +func (c *realmsGRPCClient) UpdateRealmOperation(name string) *UpdateRealmOperation { return &UpdateRealmOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/gaming/apiv1/realms_client_example_test.go b/gaming/apiv1/realms_client_example_test.go index f0b198e710b1..606fefce5517 100644 --- a/gaming/apiv1/realms_client_example_test.go +++ b/gaming/apiv1/realms_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewRealmsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleRealmsClient_ListRealms() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.ListRealmsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleRealmsClient_ListRealms() { } func ExampleRealmsClient_GetRealm() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetRealmRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleRealmsClient_GetRealm() { } func ExampleRealmsClient_CreateRealm() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.CreateRealmRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleRealmsClient_CreateRealm() { } func ExampleRealmsClient_DeleteRealm() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.DeleteRealmRequest{ // TODO: Fill request struct fields. @@ -130,13 +127,12 @@ func ExampleRealmsClient_DeleteRealm() { } func ExampleRealmsClient_UpdateRealm() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.UpdateRealmRequest{ // TODO: Fill request struct fields. @@ -155,13 +151,12 @@ func ExampleRealmsClient_UpdateRealm() { } func ExampleRealmsClient_PreviewRealmUpdate() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewRealmUpdateRequest{ // TODO: Fill request struct fields. diff --git a/gaming/apiv1beta/doc.go b/gaming/apiv1beta/doc.go index 071ec365f34d..468384f0934a 100644 --- a/gaming/apiv1beta/doc.go +++ b/gaming/apiv1beta/doc.go @@ -20,6 +20,8 @@ // Deploy and manage infrastructure for global multiplayer gaming // experiences. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package gaming // import "cloud.google.com/go/gaming/apiv1beta" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/gaming/apiv1beta/game_server_clusters_client.go b/gaming/apiv1beta/game_server_clusters_client.go index 162172291713..e580fd643864 100644 --- a/gaming/apiv1beta/game_server_clusters_client.go +++ b/gaming/apiv1beta/game_server_clusters_client.go @@ -52,7 +52,7 @@ type GameServerClustersCallOptions struct { PreviewUpdateGameServerCluster []gax.CallOption } -func defaultGameServerClustersClientOptions() []option.ClientOption { +func defaultGameServerClustersGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("gameservices.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("gameservices.mtls.googleapis.com:443"), @@ -127,38 +127,155 @@ func defaultGameServerClustersCallOptions() *GameServerClustersCallOptions { } } +// internalGameServerClustersClient is an interface that defines the methods availaible from Game Services API. +type internalGameServerClustersClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListGameServerClusters(context.Context, *gamingpb.ListGameServerClustersRequest, ...gax.CallOption) *GameServerClusterIterator + GetGameServerCluster(context.Context, *gamingpb.GetGameServerClusterRequest, ...gax.CallOption) (*gamingpb.GameServerCluster, error) + CreateGameServerCluster(context.Context, *gamingpb.CreateGameServerClusterRequest, ...gax.CallOption) (*CreateGameServerClusterOperation, error) + CreateGameServerClusterOperation(name string) *CreateGameServerClusterOperation + PreviewCreateGameServerCluster(context.Context, *gamingpb.PreviewCreateGameServerClusterRequest, ...gax.CallOption) (*gamingpb.PreviewCreateGameServerClusterResponse, error) + DeleteGameServerCluster(context.Context, *gamingpb.DeleteGameServerClusterRequest, ...gax.CallOption) (*DeleteGameServerClusterOperation, error) + DeleteGameServerClusterOperation(name string) *DeleteGameServerClusterOperation + PreviewDeleteGameServerCluster(context.Context, *gamingpb.PreviewDeleteGameServerClusterRequest, ...gax.CallOption) (*gamingpb.PreviewDeleteGameServerClusterResponse, error) + UpdateGameServerCluster(context.Context, *gamingpb.UpdateGameServerClusterRequest, ...gax.CallOption) (*UpdateGameServerClusterOperation, error) + UpdateGameServerClusterOperation(name string) *UpdateGameServerClusterOperation + PreviewUpdateGameServerCluster(context.Context, *gamingpb.PreviewUpdateGameServerClusterRequest, ...gax.CallOption) (*gamingpb.PreviewUpdateGameServerClusterResponse, error) +} + // GameServerClustersClient is a client for interacting with Game Services API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The game server cluster maps to Kubernetes clusters running Agones and is +// used to manage fleets within clusters. type GameServerClustersClient struct { + // The internal transport-dependent client. + internalClient internalGameServerClustersClient + + // The call options for this service. + CallOptions *GameServerClustersCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *GameServerClustersClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *GameServerClustersClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *GameServerClustersClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListGameServerClusters lists game server clusters in a given project and location. +func (c *GameServerClustersClient) ListGameServerClusters(ctx context.Context, req *gamingpb.ListGameServerClustersRequest, opts ...gax.CallOption) *GameServerClusterIterator { + return c.internalClient.ListGameServerClusters(ctx, req, opts...) +} + +// GetGameServerCluster gets details of a single game server cluster. +func (c *GameServerClustersClient) GetGameServerCluster(ctx context.Context, req *gamingpb.GetGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.GameServerCluster, error) { + return c.internalClient.GetGameServerCluster(ctx, req, opts...) +} + +// CreateGameServerCluster creates a new game server cluster in a given project and location. +func (c *GameServerClustersClient) CreateGameServerCluster(ctx context.Context, req *gamingpb.CreateGameServerClusterRequest, opts ...gax.CallOption) (*CreateGameServerClusterOperation, error) { + return c.internalClient.CreateGameServerCluster(ctx, req, opts...) +} + +// CreateGameServerClusterOperation returns a new CreateGameServerClusterOperation from a given name. +// The name must be that of a previously created CreateGameServerClusterOperation, possibly from a different process. +func (c *GameServerClustersClient) CreateGameServerClusterOperation(name string) *CreateGameServerClusterOperation { + return c.internalClient.CreateGameServerClusterOperation(name) +} + +// PreviewCreateGameServerCluster previews creation of a new game server cluster in a given project and +// location. +func (c *GameServerClustersClient) PreviewCreateGameServerCluster(ctx context.Context, req *gamingpb.PreviewCreateGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewCreateGameServerClusterResponse, error) { + return c.internalClient.PreviewCreateGameServerCluster(ctx, req, opts...) +} + +// DeleteGameServerCluster deletes a single game server cluster. +func (c *GameServerClustersClient) DeleteGameServerCluster(ctx context.Context, req *gamingpb.DeleteGameServerClusterRequest, opts ...gax.CallOption) (*DeleteGameServerClusterOperation, error) { + return c.internalClient.DeleteGameServerCluster(ctx, req, opts...) +} + +// DeleteGameServerClusterOperation returns a new DeleteGameServerClusterOperation from a given name. +// The name must be that of a previously created DeleteGameServerClusterOperation, possibly from a different process. +func (c *GameServerClustersClient) DeleteGameServerClusterOperation(name string) *DeleteGameServerClusterOperation { + return c.internalClient.DeleteGameServerClusterOperation(name) +} + +// PreviewDeleteGameServerCluster previews deletion of a single game server cluster. +func (c *GameServerClustersClient) PreviewDeleteGameServerCluster(ctx context.Context, req *gamingpb.PreviewDeleteGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewDeleteGameServerClusterResponse, error) { + return c.internalClient.PreviewDeleteGameServerCluster(ctx, req, opts...) +} + +// UpdateGameServerCluster patches a single game server cluster. +func (c *GameServerClustersClient) UpdateGameServerCluster(ctx context.Context, req *gamingpb.UpdateGameServerClusterRequest, opts ...gax.CallOption) (*UpdateGameServerClusterOperation, error) { + return c.internalClient.UpdateGameServerCluster(ctx, req, opts...) +} + +// UpdateGameServerClusterOperation returns a new UpdateGameServerClusterOperation from a given name. +// The name must be that of a previously created UpdateGameServerClusterOperation, possibly from a different process. +func (c *GameServerClustersClient) UpdateGameServerClusterOperation(name string) *UpdateGameServerClusterOperation { + return c.internalClient.UpdateGameServerClusterOperation(name) +} + +// PreviewUpdateGameServerCluster previews updating a GameServerCluster. +func (c *GameServerClustersClient) PreviewUpdateGameServerCluster(ctx context.Context, req *gamingpb.PreviewUpdateGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewUpdateGameServerClusterResponse, error) { + return c.internalClient.PreviewUpdateGameServerCluster(ctx, req, opts...) +} + +// gameServerClustersGRPCClient is a client for interacting with Game Services API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gameServerClustersGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing GameServerClustersClient + CallOptions **GameServerClustersCallOptions + // The gRPC API client. gameServerClustersClient gamingpb.GameServerClustersServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *GameServerClustersCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewGameServerClustersClient creates a new game server clusters service client. +// NewGameServerClustersClient creates a new game server clusters service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The game server cluster maps to Kubernetes clusters running Agones and is // used to manage fleets within clusters. func NewGameServerClustersClient(ctx context.Context, opts ...option.ClientOption) (*GameServerClustersClient, error) { - clientOpts := defaultGameServerClustersClientOptions() - + clientOpts := defaultGameServerClustersGRPCClientOptions() if newGameServerClustersClientHook != nil { hookOpts, err := newGameServerClustersClientHook(ctx, clientHookParams{}) if err != nil { @@ -176,16 +293,19 @@ func NewGameServerClustersClient(ctx context.Context, opts ...option.ClientOptio if err != nil { return nil, err } - c := &GameServerClustersClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultGameServerClustersCallOptions(), + client := GameServerClustersClient{CallOptions: defaultGameServerClustersCallOptions()} + c := &gameServerClustersGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, gameServerClustersClient: gamingpb.NewGameServerClustersServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -195,36 +315,36 @@ func NewGameServerClustersClient(ctx context.Context, opts ...option.ClientOptio // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *GameServerClustersClient) Connection() *grpc.ClientConn { +func (c *gameServerClustersGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *GameServerClustersClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *GameServerClustersClient) setGoogleClientInfo(keyval ...string) { +func (c *gameServerClustersGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListGameServerClusters lists game server clusters in a given project and location. -func (c *GameServerClustersClient) ListGameServerClusters(ctx context.Context, req *gamingpb.ListGameServerClustersRequest, opts ...gax.CallOption) *GameServerClusterIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gameServerClustersGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gameServerClustersGRPCClient) ListGameServerClusters(ctx context.Context, req *gamingpb.ListGameServerClustersRequest, opts ...gax.CallOption) *GameServerClusterIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListGameServerClusters[0:len(c.CallOptions.ListGameServerClusters):len(c.CallOptions.ListGameServerClusters)], opts...) + opts = append((*c.CallOptions).ListGameServerClusters[0:len((*c.CallOptions).ListGameServerClusters):len((*c.CallOptions).ListGameServerClusters)], opts...) it := &GameServerClusterIterator{} req = proto.Clone(req).(*gamingpb.ListGameServerClustersRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*gamingpb.GameServerCluster, string, error) { @@ -261,8 +381,7 @@ func (c *GameServerClustersClient) ListGameServerClusters(ctx context.Context, r return it } -// GetGameServerCluster gets details of a single game server cluster. -func (c *GameServerClustersClient) GetGameServerCluster(ctx context.Context, req *gamingpb.GetGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.GameServerCluster, error) { +func (c *gameServerClustersGRPCClient) GetGameServerCluster(ctx context.Context, req *gamingpb.GetGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.GameServerCluster, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -270,7 +389,7 @@ func (c *GameServerClustersClient) GetGameServerCluster(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetGameServerCluster[0:len(c.CallOptions.GetGameServerCluster):len(c.CallOptions.GetGameServerCluster)], opts...) + opts = append((*c.CallOptions).GetGameServerCluster[0:len((*c.CallOptions).GetGameServerCluster):len((*c.CallOptions).GetGameServerCluster)], opts...) var resp *gamingpb.GameServerCluster err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -283,8 +402,7 @@ func (c *GameServerClustersClient) GetGameServerCluster(ctx context.Context, req return resp, nil } -// CreateGameServerCluster creates a new game server cluster in a given project and location. -func (c *GameServerClustersClient) CreateGameServerCluster(ctx context.Context, req *gamingpb.CreateGameServerClusterRequest, opts ...gax.CallOption) (*CreateGameServerClusterOperation, error) { +func (c *gameServerClustersGRPCClient) CreateGameServerCluster(ctx context.Context, req *gamingpb.CreateGameServerClusterRequest, opts ...gax.CallOption) (*CreateGameServerClusterOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -292,7 +410,7 @@ func (c *GameServerClustersClient) CreateGameServerCluster(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateGameServerCluster[0:len(c.CallOptions.CreateGameServerCluster):len(c.CallOptions.CreateGameServerCluster)], opts...) + opts = append((*c.CallOptions).CreateGameServerCluster[0:len((*c.CallOptions).CreateGameServerCluster):len((*c.CallOptions).CreateGameServerCluster)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -303,13 +421,11 @@ func (c *GameServerClustersClient) CreateGameServerCluster(ctx context.Context, return nil, err } return &CreateGameServerClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// PreviewCreateGameServerCluster previews creation of a new game server cluster in a given project and -// location. -func (c *GameServerClustersClient) PreviewCreateGameServerCluster(ctx context.Context, req *gamingpb.PreviewCreateGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewCreateGameServerClusterResponse, error) { +func (c *gameServerClustersGRPCClient) PreviewCreateGameServerCluster(ctx context.Context, req *gamingpb.PreviewCreateGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewCreateGameServerClusterResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -317,7 +433,7 @@ func (c *GameServerClustersClient) PreviewCreateGameServerCluster(ctx context.Co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PreviewCreateGameServerCluster[0:len(c.CallOptions.PreviewCreateGameServerCluster):len(c.CallOptions.PreviewCreateGameServerCluster)], opts...) + opts = append((*c.CallOptions).PreviewCreateGameServerCluster[0:len((*c.CallOptions).PreviewCreateGameServerCluster):len((*c.CallOptions).PreviewCreateGameServerCluster)], opts...) var resp *gamingpb.PreviewCreateGameServerClusterResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -330,8 +446,7 @@ func (c *GameServerClustersClient) PreviewCreateGameServerCluster(ctx context.Co return resp, nil } -// DeleteGameServerCluster deletes a single game server cluster. -func (c *GameServerClustersClient) DeleteGameServerCluster(ctx context.Context, req *gamingpb.DeleteGameServerClusterRequest, opts ...gax.CallOption) (*DeleteGameServerClusterOperation, error) { +func (c *gameServerClustersGRPCClient) DeleteGameServerCluster(ctx context.Context, req *gamingpb.DeleteGameServerClusterRequest, opts ...gax.CallOption) (*DeleteGameServerClusterOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -339,7 +454,7 @@ func (c *GameServerClustersClient) DeleteGameServerCluster(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteGameServerCluster[0:len(c.CallOptions.DeleteGameServerCluster):len(c.CallOptions.DeleteGameServerCluster)], opts...) + opts = append((*c.CallOptions).DeleteGameServerCluster[0:len((*c.CallOptions).DeleteGameServerCluster):len((*c.CallOptions).DeleteGameServerCluster)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -350,12 +465,11 @@ func (c *GameServerClustersClient) DeleteGameServerCluster(ctx context.Context, return nil, err } return &DeleteGameServerClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// PreviewDeleteGameServerCluster previews deletion of a single game server cluster. -func (c *GameServerClustersClient) PreviewDeleteGameServerCluster(ctx context.Context, req *gamingpb.PreviewDeleteGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewDeleteGameServerClusterResponse, error) { +func (c *gameServerClustersGRPCClient) PreviewDeleteGameServerCluster(ctx context.Context, req *gamingpb.PreviewDeleteGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewDeleteGameServerClusterResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -363,7 +477,7 @@ func (c *GameServerClustersClient) PreviewDeleteGameServerCluster(ctx context.Co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PreviewDeleteGameServerCluster[0:len(c.CallOptions.PreviewDeleteGameServerCluster):len(c.CallOptions.PreviewDeleteGameServerCluster)], opts...) + opts = append((*c.CallOptions).PreviewDeleteGameServerCluster[0:len((*c.CallOptions).PreviewDeleteGameServerCluster):len((*c.CallOptions).PreviewDeleteGameServerCluster)], opts...) var resp *gamingpb.PreviewDeleteGameServerClusterResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -376,8 +490,7 @@ func (c *GameServerClustersClient) PreviewDeleteGameServerCluster(ctx context.Co return resp, nil } -// UpdateGameServerCluster patches a single game server cluster. -func (c *GameServerClustersClient) UpdateGameServerCluster(ctx context.Context, req *gamingpb.UpdateGameServerClusterRequest, opts ...gax.CallOption) (*UpdateGameServerClusterOperation, error) { +func (c *gameServerClustersGRPCClient) UpdateGameServerCluster(ctx context.Context, req *gamingpb.UpdateGameServerClusterRequest, opts ...gax.CallOption) (*UpdateGameServerClusterOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -385,7 +498,7 @@ func (c *GameServerClustersClient) UpdateGameServerCluster(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "game_server_cluster.name", url.QueryEscape(req.GetGameServerCluster().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateGameServerCluster[0:len(c.CallOptions.UpdateGameServerCluster):len(c.CallOptions.UpdateGameServerCluster)], opts...) + opts = append((*c.CallOptions).UpdateGameServerCluster[0:len((*c.CallOptions).UpdateGameServerCluster):len((*c.CallOptions).UpdateGameServerCluster)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -396,12 +509,11 @@ func (c *GameServerClustersClient) UpdateGameServerCluster(ctx context.Context, return nil, err } return &UpdateGameServerClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// PreviewUpdateGameServerCluster previews updating a GameServerCluster. -func (c *GameServerClustersClient) PreviewUpdateGameServerCluster(ctx context.Context, req *gamingpb.PreviewUpdateGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewUpdateGameServerClusterResponse, error) { +func (c *gameServerClustersGRPCClient) PreviewUpdateGameServerCluster(ctx context.Context, req *gamingpb.PreviewUpdateGameServerClusterRequest, opts ...gax.CallOption) (*gamingpb.PreviewUpdateGameServerClusterResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -409,7 +521,7 @@ func (c *GameServerClustersClient) PreviewUpdateGameServerCluster(ctx context.Co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "game_server_cluster.name", url.QueryEscape(req.GetGameServerCluster().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PreviewUpdateGameServerCluster[0:len(c.CallOptions.PreviewUpdateGameServerCluster):len(c.CallOptions.PreviewUpdateGameServerCluster)], opts...) + opts = append((*c.CallOptions).PreviewUpdateGameServerCluster[0:len((*c.CallOptions).PreviewUpdateGameServerCluster):len((*c.CallOptions).PreviewUpdateGameServerCluster)], opts...) var resp *gamingpb.PreviewUpdateGameServerClusterResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -429,9 +541,9 @@ type CreateGameServerClusterOperation struct { // CreateGameServerClusterOperation returns a new CreateGameServerClusterOperation from a given name. // The name must be that of a previously created CreateGameServerClusterOperation, possibly from a different process. -func (c *GameServerClustersClient) CreateGameServerClusterOperation(name string) *CreateGameServerClusterOperation { +func (c *gameServerClustersGRPCClient) CreateGameServerClusterOperation(name string) *CreateGameServerClusterOperation { return &CreateGameServerClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -498,9 +610,9 @@ type DeleteGameServerClusterOperation struct { // DeleteGameServerClusterOperation returns a new DeleteGameServerClusterOperation from a given name. // The name must be that of a previously created DeleteGameServerClusterOperation, possibly from a different process. -func (c *GameServerClustersClient) DeleteGameServerClusterOperation(name string) *DeleteGameServerClusterOperation { +func (c *gameServerClustersGRPCClient) DeleteGameServerClusterOperation(name string) *DeleteGameServerClusterOperation { return &DeleteGameServerClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -556,9 +668,9 @@ type UpdateGameServerClusterOperation struct { // UpdateGameServerClusterOperation returns a new UpdateGameServerClusterOperation from a given name. // The name must be that of a previously created UpdateGameServerClusterOperation, possibly from a different process. -func (c *GameServerClustersClient) UpdateGameServerClusterOperation(name string) *UpdateGameServerClusterOperation { +func (c *gameServerClustersGRPCClient) UpdateGameServerClusterOperation(name string) *UpdateGameServerClusterOperation { return &UpdateGameServerClusterOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/gaming/apiv1beta/game_server_clusters_client_example_test.go b/gaming/apiv1beta/game_server_clusters_client_example_test.go index 3084b6e12ada..6d320d7ba85a 100644 --- a/gaming/apiv1beta/game_server_clusters_client_example_test.go +++ b/gaming/apiv1beta/game_server_clusters_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewGameServerClustersClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleGameServerClustersClient_ListGameServerClusters() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.ListGameServerClustersRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleGameServerClustersClient_ListGameServerClusters() { } func ExampleGameServerClustersClient_GetGameServerCluster() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetGameServerClusterRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleGameServerClustersClient_GetGameServerCluster() { } func ExampleGameServerClustersClient_CreateGameServerCluster() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.CreateGameServerClusterRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleGameServerClustersClient_CreateGameServerCluster() { } func ExampleGameServerClustersClient_PreviewCreateGameServerCluster() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewCreateGameServerClusterRequest{ // TODO: Fill request struct fields. @@ -127,13 +124,12 @@ func ExampleGameServerClustersClient_PreviewCreateGameServerCluster() { } func ExampleGameServerClustersClient_DeleteGameServerCluster() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.DeleteGameServerClusterRequest{ // TODO: Fill request struct fields. @@ -150,13 +146,12 @@ func ExampleGameServerClustersClient_DeleteGameServerCluster() { } func ExampleGameServerClustersClient_PreviewDeleteGameServerCluster() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewDeleteGameServerClusterRequest{ // TODO: Fill request struct fields. @@ -170,13 +165,12 @@ func ExampleGameServerClustersClient_PreviewDeleteGameServerCluster() { } func ExampleGameServerClustersClient_UpdateGameServerCluster() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.UpdateGameServerClusterRequest{ // TODO: Fill request struct fields. @@ -195,13 +189,12 @@ func ExampleGameServerClustersClient_UpdateGameServerCluster() { } func ExampleGameServerClustersClient_PreviewUpdateGameServerCluster() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewUpdateGameServerClusterRequest{ // TODO: Fill request struct fields. diff --git a/gaming/apiv1beta/game_server_configs_client.go b/gaming/apiv1beta/game_server_configs_client.go index 936bd3d23824..b7a714621381 100644 --- a/gaming/apiv1beta/game_server_configs_client.go +++ b/gaming/apiv1beta/game_server_configs_client.go @@ -48,7 +48,7 @@ type GameServerConfigsCallOptions struct { DeleteGameServerConfig []gax.CallOption } -func defaultGameServerConfigsClientOptions() []option.ClientOption { +func defaultGameServerConfigsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("gameservices.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("gameservices.mtls.googleapis.com:443"), @@ -89,37 +89,125 @@ func defaultGameServerConfigsCallOptions() *GameServerConfigsCallOptions { } } +// internalGameServerConfigsClient is an interface that defines the methods availaible from Game Services API. +type internalGameServerConfigsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListGameServerConfigs(context.Context, *gamingpb.ListGameServerConfigsRequest, ...gax.CallOption) *GameServerConfigIterator + GetGameServerConfig(context.Context, *gamingpb.GetGameServerConfigRequest, ...gax.CallOption) (*gamingpb.GameServerConfig, error) + CreateGameServerConfig(context.Context, *gamingpb.CreateGameServerConfigRequest, ...gax.CallOption) (*CreateGameServerConfigOperation, error) + CreateGameServerConfigOperation(name string) *CreateGameServerConfigOperation + DeleteGameServerConfig(context.Context, *gamingpb.DeleteGameServerConfigRequest, ...gax.CallOption) (*DeleteGameServerConfigOperation, error) + DeleteGameServerConfigOperation(name string) *DeleteGameServerConfigOperation +} + // GameServerConfigsClient is a client for interacting with Game Services API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The game server config configures the game servers in an Agones fleet. type GameServerConfigsClient struct { + // The internal transport-dependent client. + internalClient internalGameServerConfigsClient + + // The call options for this service. + CallOptions *GameServerConfigsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *GameServerConfigsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *GameServerConfigsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *GameServerConfigsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListGameServerConfigs lists game server configs in a given project, location, and game server +// deployment. +func (c *GameServerConfigsClient) ListGameServerConfigs(ctx context.Context, req *gamingpb.ListGameServerConfigsRequest, opts ...gax.CallOption) *GameServerConfigIterator { + return c.internalClient.ListGameServerConfigs(ctx, req, opts...) +} + +// GetGameServerConfig gets details of a single game server config. +func (c *GameServerConfigsClient) GetGameServerConfig(ctx context.Context, req *gamingpb.GetGameServerConfigRequest, opts ...gax.CallOption) (*gamingpb.GameServerConfig, error) { + return c.internalClient.GetGameServerConfig(ctx, req, opts...) +} + +// CreateGameServerConfig creates a new game server config in a given project, location, and game +// server deployment. Game server configs are immutable, and are not applied +// until referenced in the game server deployment rollout resource. +func (c *GameServerConfigsClient) CreateGameServerConfig(ctx context.Context, req *gamingpb.CreateGameServerConfigRequest, opts ...gax.CallOption) (*CreateGameServerConfigOperation, error) { + return c.internalClient.CreateGameServerConfig(ctx, req, opts...) +} + +// CreateGameServerConfigOperation returns a new CreateGameServerConfigOperation from a given name. +// The name must be that of a previously created CreateGameServerConfigOperation, possibly from a different process. +func (c *GameServerConfigsClient) CreateGameServerConfigOperation(name string) *CreateGameServerConfigOperation { + return c.internalClient.CreateGameServerConfigOperation(name) +} + +// DeleteGameServerConfig deletes a single game server config. The deletion will fail if the game +// server config is referenced in a game server deployment rollout. +func (c *GameServerConfigsClient) DeleteGameServerConfig(ctx context.Context, req *gamingpb.DeleteGameServerConfigRequest, opts ...gax.CallOption) (*DeleteGameServerConfigOperation, error) { + return c.internalClient.DeleteGameServerConfig(ctx, req, opts...) +} + +// DeleteGameServerConfigOperation returns a new DeleteGameServerConfigOperation from a given name. +// The name must be that of a previously created DeleteGameServerConfigOperation, possibly from a different process. +func (c *GameServerConfigsClient) DeleteGameServerConfigOperation(name string) *DeleteGameServerConfigOperation { + return c.internalClient.DeleteGameServerConfigOperation(name) +} + +// gameServerConfigsGRPCClient is a client for interacting with Game Services API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gameServerConfigsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing GameServerConfigsClient + CallOptions **GameServerConfigsCallOptions + // The gRPC API client. gameServerConfigsClient gamingpb.GameServerConfigsServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *GameServerConfigsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewGameServerConfigsClient creates a new game server configs service client. +// NewGameServerConfigsClient creates a new game server configs service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The game server config configures the game servers in an Agones fleet. func NewGameServerConfigsClient(ctx context.Context, opts ...option.ClientOption) (*GameServerConfigsClient, error) { - clientOpts := defaultGameServerConfigsClientOptions() - + clientOpts := defaultGameServerConfigsGRPCClientOptions() if newGameServerConfigsClientHook != nil { hookOpts, err := newGameServerConfigsClientHook(ctx, clientHookParams{}) if err != nil { @@ -137,16 +225,19 @@ func NewGameServerConfigsClient(ctx context.Context, opts ...option.ClientOption if err != nil { return nil, err } - c := &GameServerConfigsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultGameServerConfigsCallOptions(), + client := GameServerConfigsClient{CallOptions: defaultGameServerConfigsCallOptions()} + c := &gameServerConfigsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, gameServerConfigsClient: gamingpb.NewGameServerConfigsServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -156,37 +247,36 @@ func NewGameServerConfigsClient(ctx context.Context, opts ...option.ClientOption // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *GameServerConfigsClient) Connection() *grpc.ClientConn { +func (c *gameServerConfigsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *GameServerConfigsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *GameServerConfigsClient) setGoogleClientInfo(keyval ...string) { +func (c *gameServerConfigsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListGameServerConfigs lists game server configs in a given project, location, and game server -// deployment. -func (c *GameServerConfigsClient) ListGameServerConfigs(ctx context.Context, req *gamingpb.ListGameServerConfigsRequest, opts ...gax.CallOption) *GameServerConfigIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gameServerConfigsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gameServerConfigsGRPCClient) ListGameServerConfigs(ctx context.Context, req *gamingpb.ListGameServerConfigsRequest, opts ...gax.CallOption) *GameServerConfigIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListGameServerConfigs[0:len(c.CallOptions.ListGameServerConfigs):len(c.CallOptions.ListGameServerConfigs)], opts...) + opts = append((*c.CallOptions).ListGameServerConfigs[0:len((*c.CallOptions).ListGameServerConfigs):len((*c.CallOptions).ListGameServerConfigs)], opts...) it := &GameServerConfigIterator{} req = proto.Clone(req).(*gamingpb.ListGameServerConfigsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*gamingpb.GameServerConfig, string, error) { @@ -223,8 +313,7 @@ func (c *GameServerConfigsClient) ListGameServerConfigs(ctx context.Context, req return it } -// GetGameServerConfig gets details of a single game server config. -func (c *GameServerConfigsClient) GetGameServerConfig(ctx context.Context, req *gamingpb.GetGameServerConfigRequest, opts ...gax.CallOption) (*gamingpb.GameServerConfig, error) { +func (c *gameServerConfigsGRPCClient) GetGameServerConfig(ctx context.Context, req *gamingpb.GetGameServerConfigRequest, opts ...gax.CallOption) (*gamingpb.GameServerConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -232,7 +321,7 @@ func (c *GameServerConfigsClient) GetGameServerConfig(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetGameServerConfig[0:len(c.CallOptions.GetGameServerConfig):len(c.CallOptions.GetGameServerConfig)], opts...) + opts = append((*c.CallOptions).GetGameServerConfig[0:len((*c.CallOptions).GetGameServerConfig):len((*c.CallOptions).GetGameServerConfig)], opts...) var resp *gamingpb.GameServerConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -245,10 +334,7 @@ func (c *GameServerConfigsClient) GetGameServerConfig(ctx context.Context, req * return resp, nil } -// CreateGameServerConfig creates a new game server config in a given project, location, and game -// server deployment. Game server configs are immutable, and are not applied -// until referenced in the game server deployment rollout resource. -func (c *GameServerConfigsClient) CreateGameServerConfig(ctx context.Context, req *gamingpb.CreateGameServerConfigRequest, opts ...gax.CallOption) (*CreateGameServerConfigOperation, error) { +func (c *gameServerConfigsGRPCClient) CreateGameServerConfig(ctx context.Context, req *gamingpb.CreateGameServerConfigRequest, opts ...gax.CallOption) (*CreateGameServerConfigOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -256,7 +342,7 @@ func (c *GameServerConfigsClient) CreateGameServerConfig(ctx context.Context, re } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateGameServerConfig[0:len(c.CallOptions.CreateGameServerConfig):len(c.CallOptions.CreateGameServerConfig)], opts...) + opts = append((*c.CallOptions).CreateGameServerConfig[0:len((*c.CallOptions).CreateGameServerConfig):len((*c.CallOptions).CreateGameServerConfig)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -267,13 +353,11 @@ func (c *GameServerConfigsClient) CreateGameServerConfig(ctx context.Context, re return nil, err } return &CreateGameServerConfigOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteGameServerConfig deletes a single game server config. The deletion will fail if the game -// server config is referenced in a game server deployment rollout. -func (c *GameServerConfigsClient) DeleteGameServerConfig(ctx context.Context, req *gamingpb.DeleteGameServerConfigRequest, opts ...gax.CallOption) (*DeleteGameServerConfigOperation, error) { +func (c *gameServerConfigsGRPCClient) DeleteGameServerConfig(ctx context.Context, req *gamingpb.DeleteGameServerConfigRequest, opts ...gax.CallOption) (*DeleteGameServerConfigOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -281,7 +365,7 @@ func (c *GameServerConfigsClient) DeleteGameServerConfig(ctx context.Context, re } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteGameServerConfig[0:len(c.CallOptions.DeleteGameServerConfig):len(c.CallOptions.DeleteGameServerConfig)], opts...) + opts = append((*c.CallOptions).DeleteGameServerConfig[0:len((*c.CallOptions).DeleteGameServerConfig):len((*c.CallOptions).DeleteGameServerConfig)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -292,7 +376,7 @@ func (c *GameServerConfigsClient) DeleteGameServerConfig(ctx context.Context, re return nil, err } return &DeleteGameServerConfigOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -303,9 +387,9 @@ type CreateGameServerConfigOperation struct { // CreateGameServerConfigOperation returns a new CreateGameServerConfigOperation from a given name. // The name must be that of a previously created CreateGameServerConfigOperation, possibly from a different process. -func (c *GameServerConfigsClient) CreateGameServerConfigOperation(name string) *CreateGameServerConfigOperation { +func (c *gameServerConfigsGRPCClient) CreateGameServerConfigOperation(name string) *CreateGameServerConfigOperation { return &CreateGameServerConfigOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -372,9 +456,9 @@ type DeleteGameServerConfigOperation struct { // DeleteGameServerConfigOperation returns a new DeleteGameServerConfigOperation from a given name. // The name must be that of a previously created DeleteGameServerConfigOperation, possibly from a different process. -func (c *GameServerConfigsClient) DeleteGameServerConfigOperation(name string) *DeleteGameServerConfigOperation { +func (c *gameServerConfigsGRPCClient) DeleteGameServerConfigOperation(name string) *DeleteGameServerConfigOperation { return &DeleteGameServerConfigOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/gaming/apiv1beta/game_server_configs_client_example_test.go b/gaming/apiv1beta/game_server_configs_client_example_test.go index e4a2c93bfb58..07111f6c9517 100644 --- a/gaming/apiv1beta/game_server_configs_client_example_test.go +++ b/gaming/apiv1beta/game_server_configs_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewGameServerConfigsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleGameServerConfigsClient_ListGameServerConfigs() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gaming.NewGameServerConfigsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.ListGameServerConfigsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleGameServerConfigsClient_ListGameServerConfigs() { } func ExampleGameServerConfigsClient_GetGameServerConfig() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerConfigsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetGameServerConfigRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleGameServerConfigsClient_GetGameServerConfig() { } func ExampleGameServerConfigsClient_CreateGameServerConfig() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerConfigsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.CreateGameServerConfigRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleGameServerConfigsClient_CreateGameServerConfig() { } func ExampleGameServerConfigsClient_DeleteGameServerConfig() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerConfigsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.DeleteGameServerConfigRequest{ // TODO: Fill request struct fields. diff --git a/gaming/apiv1beta/game_server_deployments_client.go b/gaming/apiv1beta/game_server_deployments_client.go index f17f1e47bdb4..8718fe2aa39d 100644 --- a/gaming/apiv1beta/game_server_deployments_client.go +++ b/gaming/apiv1beta/game_server_deployments_client.go @@ -53,7 +53,7 @@ type GameServerDeploymentsCallOptions struct { FetchDeploymentState []gax.CallOption } -func defaultGameServerDeploymentsClientOptions() []option.ClientOption { +func defaultGameServerDeploymentsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("gameservices.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("gameservices.mtls.googleapis.com:443"), @@ -129,38 +129,175 @@ func defaultGameServerDeploymentsCallOptions() *GameServerDeploymentsCallOptions } } +// internalGameServerDeploymentsClient is an interface that defines the methods availaible from Game Services API. +type internalGameServerDeploymentsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListGameServerDeployments(context.Context, *gamingpb.ListGameServerDeploymentsRequest, ...gax.CallOption) *GameServerDeploymentIterator + GetGameServerDeployment(context.Context, *gamingpb.GetGameServerDeploymentRequest, ...gax.CallOption) (*gamingpb.GameServerDeployment, error) + CreateGameServerDeployment(context.Context, *gamingpb.CreateGameServerDeploymentRequest, ...gax.CallOption) (*CreateGameServerDeploymentOperation, error) + CreateGameServerDeploymentOperation(name string) *CreateGameServerDeploymentOperation + DeleteGameServerDeployment(context.Context, *gamingpb.DeleteGameServerDeploymentRequest, ...gax.CallOption) (*DeleteGameServerDeploymentOperation, error) + DeleteGameServerDeploymentOperation(name string) *DeleteGameServerDeploymentOperation + UpdateGameServerDeployment(context.Context, *gamingpb.UpdateGameServerDeploymentRequest, ...gax.CallOption) (*UpdateGameServerDeploymentOperation, error) + UpdateGameServerDeploymentOperation(name string) *UpdateGameServerDeploymentOperation + GetGameServerDeploymentRollout(context.Context, *gamingpb.GetGameServerDeploymentRolloutRequest, ...gax.CallOption) (*gamingpb.GameServerDeploymentRollout, error) + UpdateGameServerDeploymentRollout(context.Context, *gamingpb.UpdateGameServerDeploymentRolloutRequest, ...gax.CallOption) (*UpdateGameServerDeploymentRolloutOperation, error) + UpdateGameServerDeploymentRolloutOperation(name string) *UpdateGameServerDeploymentRolloutOperation + PreviewGameServerDeploymentRollout(context.Context, *gamingpb.PreviewGameServerDeploymentRolloutRequest, ...gax.CallOption) (*gamingpb.PreviewGameServerDeploymentRolloutResponse, error) + FetchDeploymentState(context.Context, *gamingpb.FetchDeploymentStateRequest, ...gax.CallOption) (*gamingpb.FetchDeploymentStateResponse, error) +} + // GameServerDeploymentsClient is a client for interacting with Game Services API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The game server deployment is used to control the deployment of Agones +// fleets. type GameServerDeploymentsClient struct { + // The internal transport-dependent client. + internalClient internalGameServerDeploymentsClient + + // The call options for this service. + CallOptions *GameServerDeploymentsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *GameServerDeploymentsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *GameServerDeploymentsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *GameServerDeploymentsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListGameServerDeployments lists game server deployments in a given project and location. +func (c *GameServerDeploymentsClient) ListGameServerDeployments(ctx context.Context, req *gamingpb.ListGameServerDeploymentsRequest, opts ...gax.CallOption) *GameServerDeploymentIterator { + return c.internalClient.ListGameServerDeployments(ctx, req, opts...) +} + +// GetGameServerDeployment gets details of a single game server deployment. +func (c *GameServerDeploymentsClient) GetGameServerDeployment(ctx context.Context, req *gamingpb.GetGameServerDeploymentRequest, opts ...gax.CallOption) (*gamingpb.GameServerDeployment, error) { + return c.internalClient.GetGameServerDeployment(ctx, req, opts...) +} + +// CreateGameServerDeployment creates a new game server deployment in a given project and location. +func (c *GameServerDeploymentsClient) CreateGameServerDeployment(ctx context.Context, req *gamingpb.CreateGameServerDeploymentRequest, opts ...gax.CallOption) (*CreateGameServerDeploymentOperation, error) { + return c.internalClient.CreateGameServerDeployment(ctx, req, opts...) +} + +// CreateGameServerDeploymentOperation returns a new CreateGameServerDeploymentOperation from a given name. +// The name must be that of a previously created CreateGameServerDeploymentOperation, possibly from a different process. +func (c *GameServerDeploymentsClient) CreateGameServerDeploymentOperation(name string) *CreateGameServerDeploymentOperation { + return c.internalClient.CreateGameServerDeploymentOperation(name) +} + +// DeleteGameServerDeployment deletes a single game server deployment. +func (c *GameServerDeploymentsClient) DeleteGameServerDeployment(ctx context.Context, req *gamingpb.DeleteGameServerDeploymentRequest, opts ...gax.CallOption) (*DeleteGameServerDeploymentOperation, error) { + return c.internalClient.DeleteGameServerDeployment(ctx, req, opts...) +} + +// DeleteGameServerDeploymentOperation returns a new DeleteGameServerDeploymentOperation from a given name. +// The name must be that of a previously created DeleteGameServerDeploymentOperation, possibly from a different process. +func (c *GameServerDeploymentsClient) DeleteGameServerDeploymentOperation(name string) *DeleteGameServerDeploymentOperation { + return c.internalClient.DeleteGameServerDeploymentOperation(name) +} + +// UpdateGameServerDeployment patches a game server deployment. +func (c *GameServerDeploymentsClient) UpdateGameServerDeployment(ctx context.Context, req *gamingpb.UpdateGameServerDeploymentRequest, opts ...gax.CallOption) (*UpdateGameServerDeploymentOperation, error) { + return c.internalClient.UpdateGameServerDeployment(ctx, req, opts...) +} + +// UpdateGameServerDeploymentOperation returns a new UpdateGameServerDeploymentOperation from a given name. +// The name must be that of a previously created UpdateGameServerDeploymentOperation, possibly from a different process. +func (c *GameServerDeploymentsClient) UpdateGameServerDeploymentOperation(name string) *UpdateGameServerDeploymentOperation { + return c.internalClient.UpdateGameServerDeploymentOperation(name) +} + +// GetGameServerDeploymentRollout gets details a single game server deployment rollout. +func (c *GameServerDeploymentsClient) GetGameServerDeploymentRollout(ctx context.Context, req *gamingpb.GetGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*gamingpb.GameServerDeploymentRollout, error) { + return c.internalClient.GetGameServerDeploymentRollout(ctx, req, opts...) +} + +// UpdateGameServerDeploymentRollout patches a single game server deployment rollout. +// The method will not return an error if the update does not affect any +// existing realms. For example - if the default_game_server_config is changed +// but all existing realms use the override, that is valid. Similarly, if a +// non existing realm is explicitly called out in game_server_config_overrides +// field, that will also not result in an error. +func (c *GameServerDeploymentsClient) UpdateGameServerDeploymentRollout(ctx context.Context, req *gamingpb.UpdateGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*UpdateGameServerDeploymentRolloutOperation, error) { + return c.internalClient.UpdateGameServerDeploymentRollout(ctx, req, opts...) +} + +// UpdateGameServerDeploymentRolloutOperation returns a new UpdateGameServerDeploymentRolloutOperation from a given name. +// The name must be that of a previously created UpdateGameServerDeploymentRolloutOperation, possibly from a different process. +func (c *GameServerDeploymentsClient) UpdateGameServerDeploymentRolloutOperation(name string) *UpdateGameServerDeploymentRolloutOperation { + return c.internalClient.UpdateGameServerDeploymentRolloutOperation(name) +} + +// PreviewGameServerDeploymentRollout previews the game server deployment rollout. This API does not mutate the +// rollout resource. +func (c *GameServerDeploymentsClient) PreviewGameServerDeploymentRollout(ctx context.Context, req *gamingpb.PreviewGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*gamingpb.PreviewGameServerDeploymentRolloutResponse, error) { + return c.internalClient.PreviewGameServerDeploymentRollout(ctx, req, opts...) +} + +// FetchDeploymentState retrieves information about the current state of the game server +// deployment. Gathers all the Agones fleets and Agones autoscalers, +// including fleets running an older version of the game server deployment. +func (c *GameServerDeploymentsClient) FetchDeploymentState(ctx context.Context, req *gamingpb.FetchDeploymentStateRequest, opts ...gax.CallOption) (*gamingpb.FetchDeploymentStateResponse, error) { + return c.internalClient.FetchDeploymentState(ctx, req, opts...) +} + +// gameServerDeploymentsGRPCClient is a client for interacting with Game Services API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gameServerDeploymentsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing GameServerDeploymentsClient + CallOptions **GameServerDeploymentsCallOptions + // The gRPC API client. gameServerDeploymentsClient gamingpb.GameServerDeploymentsServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *GameServerDeploymentsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewGameServerDeploymentsClient creates a new game server deployments service client. +// NewGameServerDeploymentsClient creates a new game server deployments service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The game server deployment is used to control the deployment of Agones // fleets. func NewGameServerDeploymentsClient(ctx context.Context, opts ...option.ClientOption) (*GameServerDeploymentsClient, error) { - clientOpts := defaultGameServerDeploymentsClientOptions() - + clientOpts := defaultGameServerDeploymentsGRPCClientOptions() if newGameServerDeploymentsClientHook != nil { hookOpts, err := newGameServerDeploymentsClientHook(ctx, clientHookParams{}) if err != nil { @@ -178,16 +315,19 @@ func NewGameServerDeploymentsClient(ctx context.Context, opts ...option.ClientOp if err != nil { return nil, err } - c := &GameServerDeploymentsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultGameServerDeploymentsCallOptions(), + client := GameServerDeploymentsClient{CallOptions: defaultGameServerDeploymentsCallOptions()} + c := &gameServerDeploymentsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, gameServerDeploymentsClient: gamingpb.NewGameServerDeploymentsServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -197,36 +337,36 @@ func NewGameServerDeploymentsClient(ctx context.Context, opts ...option.ClientOp // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *GameServerDeploymentsClient) Connection() *grpc.ClientConn { +func (c *gameServerDeploymentsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *GameServerDeploymentsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *GameServerDeploymentsClient) setGoogleClientInfo(keyval ...string) { +func (c *gameServerDeploymentsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListGameServerDeployments lists game server deployments in a given project and location. -func (c *GameServerDeploymentsClient) ListGameServerDeployments(ctx context.Context, req *gamingpb.ListGameServerDeploymentsRequest, opts ...gax.CallOption) *GameServerDeploymentIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gameServerDeploymentsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gameServerDeploymentsGRPCClient) ListGameServerDeployments(ctx context.Context, req *gamingpb.ListGameServerDeploymentsRequest, opts ...gax.CallOption) *GameServerDeploymentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListGameServerDeployments[0:len(c.CallOptions.ListGameServerDeployments):len(c.CallOptions.ListGameServerDeployments)], opts...) + opts = append((*c.CallOptions).ListGameServerDeployments[0:len((*c.CallOptions).ListGameServerDeployments):len((*c.CallOptions).ListGameServerDeployments)], opts...) it := &GameServerDeploymentIterator{} req = proto.Clone(req).(*gamingpb.ListGameServerDeploymentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*gamingpb.GameServerDeployment, string, error) { @@ -263,8 +403,7 @@ func (c *GameServerDeploymentsClient) ListGameServerDeployments(ctx context.Cont return it } -// GetGameServerDeployment gets details of a single game server deployment. -func (c *GameServerDeploymentsClient) GetGameServerDeployment(ctx context.Context, req *gamingpb.GetGameServerDeploymentRequest, opts ...gax.CallOption) (*gamingpb.GameServerDeployment, error) { +func (c *gameServerDeploymentsGRPCClient) GetGameServerDeployment(ctx context.Context, req *gamingpb.GetGameServerDeploymentRequest, opts ...gax.CallOption) (*gamingpb.GameServerDeployment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -272,7 +411,7 @@ func (c *GameServerDeploymentsClient) GetGameServerDeployment(ctx context.Contex } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetGameServerDeployment[0:len(c.CallOptions.GetGameServerDeployment):len(c.CallOptions.GetGameServerDeployment)], opts...) + opts = append((*c.CallOptions).GetGameServerDeployment[0:len((*c.CallOptions).GetGameServerDeployment):len((*c.CallOptions).GetGameServerDeployment)], opts...) var resp *gamingpb.GameServerDeployment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -285,8 +424,7 @@ func (c *GameServerDeploymentsClient) GetGameServerDeployment(ctx context.Contex return resp, nil } -// CreateGameServerDeployment creates a new game server deployment in a given project and location. -func (c *GameServerDeploymentsClient) CreateGameServerDeployment(ctx context.Context, req *gamingpb.CreateGameServerDeploymentRequest, opts ...gax.CallOption) (*CreateGameServerDeploymentOperation, error) { +func (c *gameServerDeploymentsGRPCClient) CreateGameServerDeployment(ctx context.Context, req *gamingpb.CreateGameServerDeploymentRequest, opts ...gax.CallOption) (*CreateGameServerDeploymentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -294,7 +432,7 @@ func (c *GameServerDeploymentsClient) CreateGameServerDeployment(ctx context.Con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateGameServerDeployment[0:len(c.CallOptions.CreateGameServerDeployment):len(c.CallOptions.CreateGameServerDeployment)], opts...) + opts = append((*c.CallOptions).CreateGameServerDeployment[0:len((*c.CallOptions).CreateGameServerDeployment):len((*c.CallOptions).CreateGameServerDeployment)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -305,12 +443,11 @@ func (c *GameServerDeploymentsClient) CreateGameServerDeployment(ctx context.Con return nil, err } return &CreateGameServerDeploymentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteGameServerDeployment deletes a single game server deployment. -func (c *GameServerDeploymentsClient) DeleteGameServerDeployment(ctx context.Context, req *gamingpb.DeleteGameServerDeploymentRequest, opts ...gax.CallOption) (*DeleteGameServerDeploymentOperation, error) { +func (c *gameServerDeploymentsGRPCClient) DeleteGameServerDeployment(ctx context.Context, req *gamingpb.DeleteGameServerDeploymentRequest, opts ...gax.CallOption) (*DeleteGameServerDeploymentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -318,7 +455,7 @@ func (c *GameServerDeploymentsClient) DeleteGameServerDeployment(ctx context.Con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteGameServerDeployment[0:len(c.CallOptions.DeleteGameServerDeployment):len(c.CallOptions.DeleteGameServerDeployment)], opts...) + opts = append((*c.CallOptions).DeleteGameServerDeployment[0:len((*c.CallOptions).DeleteGameServerDeployment):len((*c.CallOptions).DeleteGameServerDeployment)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -329,12 +466,11 @@ func (c *GameServerDeploymentsClient) DeleteGameServerDeployment(ctx context.Con return nil, err } return &DeleteGameServerDeploymentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateGameServerDeployment patches a game server deployment. -func (c *GameServerDeploymentsClient) UpdateGameServerDeployment(ctx context.Context, req *gamingpb.UpdateGameServerDeploymentRequest, opts ...gax.CallOption) (*UpdateGameServerDeploymentOperation, error) { +func (c *gameServerDeploymentsGRPCClient) UpdateGameServerDeployment(ctx context.Context, req *gamingpb.UpdateGameServerDeploymentRequest, opts ...gax.CallOption) (*UpdateGameServerDeploymentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -342,7 +478,7 @@ func (c *GameServerDeploymentsClient) UpdateGameServerDeployment(ctx context.Con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "game_server_deployment.name", url.QueryEscape(req.GetGameServerDeployment().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateGameServerDeployment[0:len(c.CallOptions.UpdateGameServerDeployment):len(c.CallOptions.UpdateGameServerDeployment)], opts...) + opts = append((*c.CallOptions).UpdateGameServerDeployment[0:len((*c.CallOptions).UpdateGameServerDeployment):len((*c.CallOptions).UpdateGameServerDeployment)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -353,12 +489,11 @@ func (c *GameServerDeploymentsClient) UpdateGameServerDeployment(ctx context.Con return nil, err } return &UpdateGameServerDeploymentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetGameServerDeploymentRollout gets details a single game server deployment rollout. -func (c *GameServerDeploymentsClient) GetGameServerDeploymentRollout(ctx context.Context, req *gamingpb.GetGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*gamingpb.GameServerDeploymentRollout, error) { +func (c *gameServerDeploymentsGRPCClient) GetGameServerDeploymentRollout(ctx context.Context, req *gamingpb.GetGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*gamingpb.GameServerDeploymentRollout, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -366,7 +501,7 @@ func (c *GameServerDeploymentsClient) GetGameServerDeploymentRollout(ctx context } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetGameServerDeploymentRollout[0:len(c.CallOptions.GetGameServerDeploymentRollout):len(c.CallOptions.GetGameServerDeploymentRollout)], opts...) + opts = append((*c.CallOptions).GetGameServerDeploymentRollout[0:len((*c.CallOptions).GetGameServerDeploymentRollout):len((*c.CallOptions).GetGameServerDeploymentRollout)], opts...) var resp *gamingpb.GameServerDeploymentRollout err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -379,13 +514,7 @@ func (c *GameServerDeploymentsClient) GetGameServerDeploymentRollout(ctx context return resp, nil } -// UpdateGameServerDeploymentRollout patches a single game server deployment rollout. -// The method will not return an error if the update does not affect any -// existing realms. For example - if the default_game_server_config is changed -// but all existing realms use the override, that is valid. Similarly, if a -// non existing realm is explicitly called out in game_server_config_overrides -// field, that will also not result in an error. -func (c *GameServerDeploymentsClient) UpdateGameServerDeploymentRollout(ctx context.Context, req *gamingpb.UpdateGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*UpdateGameServerDeploymentRolloutOperation, error) { +func (c *gameServerDeploymentsGRPCClient) UpdateGameServerDeploymentRollout(ctx context.Context, req *gamingpb.UpdateGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*UpdateGameServerDeploymentRolloutOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -393,7 +522,7 @@ func (c *GameServerDeploymentsClient) UpdateGameServerDeploymentRollout(ctx cont } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "rollout.name", url.QueryEscape(req.GetRollout().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateGameServerDeploymentRollout[0:len(c.CallOptions.UpdateGameServerDeploymentRollout):len(c.CallOptions.UpdateGameServerDeploymentRollout)], opts...) + opts = append((*c.CallOptions).UpdateGameServerDeploymentRollout[0:len((*c.CallOptions).UpdateGameServerDeploymentRollout):len((*c.CallOptions).UpdateGameServerDeploymentRollout)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -404,13 +533,11 @@ func (c *GameServerDeploymentsClient) UpdateGameServerDeploymentRollout(ctx cont return nil, err } return &UpdateGameServerDeploymentRolloutOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// PreviewGameServerDeploymentRollout previews the game server deployment rollout. This API does not mutate the -// rollout resource. -func (c *GameServerDeploymentsClient) PreviewGameServerDeploymentRollout(ctx context.Context, req *gamingpb.PreviewGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*gamingpb.PreviewGameServerDeploymentRolloutResponse, error) { +func (c *gameServerDeploymentsGRPCClient) PreviewGameServerDeploymentRollout(ctx context.Context, req *gamingpb.PreviewGameServerDeploymentRolloutRequest, opts ...gax.CallOption) (*gamingpb.PreviewGameServerDeploymentRolloutResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -418,7 +545,7 @@ func (c *GameServerDeploymentsClient) PreviewGameServerDeploymentRollout(ctx con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "rollout.name", url.QueryEscape(req.GetRollout().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PreviewGameServerDeploymentRollout[0:len(c.CallOptions.PreviewGameServerDeploymentRollout):len(c.CallOptions.PreviewGameServerDeploymentRollout)], opts...) + opts = append((*c.CallOptions).PreviewGameServerDeploymentRollout[0:len((*c.CallOptions).PreviewGameServerDeploymentRollout):len((*c.CallOptions).PreviewGameServerDeploymentRollout)], opts...) var resp *gamingpb.PreviewGameServerDeploymentRolloutResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -431,10 +558,7 @@ func (c *GameServerDeploymentsClient) PreviewGameServerDeploymentRollout(ctx con return resp, nil } -// FetchDeploymentState retrieves information about the current state of the game server -// deployment. Gathers all the Agones fleets and Agones autoscalers, -// including fleets running an older version of the game server deployment. -func (c *GameServerDeploymentsClient) FetchDeploymentState(ctx context.Context, req *gamingpb.FetchDeploymentStateRequest, opts ...gax.CallOption) (*gamingpb.FetchDeploymentStateResponse, error) { +func (c *gameServerDeploymentsGRPCClient) FetchDeploymentState(ctx context.Context, req *gamingpb.FetchDeploymentStateRequest, opts ...gax.CallOption) (*gamingpb.FetchDeploymentStateResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -442,7 +566,7 @@ func (c *GameServerDeploymentsClient) FetchDeploymentState(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.FetchDeploymentState[0:len(c.CallOptions.FetchDeploymentState):len(c.CallOptions.FetchDeploymentState)], opts...) + opts = append((*c.CallOptions).FetchDeploymentState[0:len((*c.CallOptions).FetchDeploymentState):len((*c.CallOptions).FetchDeploymentState)], opts...) var resp *gamingpb.FetchDeploymentStateResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -462,9 +586,9 @@ type CreateGameServerDeploymentOperation struct { // CreateGameServerDeploymentOperation returns a new CreateGameServerDeploymentOperation from a given name. // The name must be that of a previously created CreateGameServerDeploymentOperation, possibly from a different process. -func (c *GameServerDeploymentsClient) CreateGameServerDeploymentOperation(name string) *CreateGameServerDeploymentOperation { +func (c *gameServerDeploymentsGRPCClient) CreateGameServerDeploymentOperation(name string) *CreateGameServerDeploymentOperation { return &CreateGameServerDeploymentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -531,9 +655,9 @@ type DeleteGameServerDeploymentOperation struct { // DeleteGameServerDeploymentOperation returns a new DeleteGameServerDeploymentOperation from a given name. // The name must be that of a previously created DeleteGameServerDeploymentOperation, possibly from a different process. -func (c *GameServerDeploymentsClient) DeleteGameServerDeploymentOperation(name string) *DeleteGameServerDeploymentOperation { +func (c *gameServerDeploymentsGRPCClient) DeleteGameServerDeploymentOperation(name string) *DeleteGameServerDeploymentOperation { return &DeleteGameServerDeploymentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -589,9 +713,9 @@ type UpdateGameServerDeploymentOperation struct { // UpdateGameServerDeploymentOperation returns a new UpdateGameServerDeploymentOperation from a given name. // The name must be that of a previously created UpdateGameServerDeploymentOperation, possibly from a different process. -func (c *GameServerDeploymentsClient) UpdateGameServerDeploymentOperation(name string) *UpdateGameServerDeploymentOperation { +func (c *gameServerDeploymentsGRPCClient) UpdateGameServerDeploymentOperation(name string) *UpdateGameServerDeploymentOperation { return &UpdateGameServerDeploymentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -658,9 +782,9 @@ type UpdateGameServerDeploymentRolloutOperation struct { // UpdateGameServerDeploymentRolloutOperation returns a new UpdateGameServerDeploymentRolloutOperation from a given name. // The name must be that of a previously created UpdateGameServerDeploymentRolloutOperation, possibly from a different process. -func (c *GameServerDeploymentsClient) UpdateGameServerDeploymentRolloutOperation(name string) *UpdateGameServerDeploymentRolloutOperation { +func (c *gameServerDeploymentsGRPCClient) UpdateGameServerDeploymentRolloutOperation(name string) *UpdateGameServerDeploymentRolloutOperation { return &UpdateGameServerDeploymentRolloutOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/gaming/apiv1beta/game_server_deployments_client_example_test.go b/gaming/apiv1beta/game_server_deployments_client_example_test.go index 71581942f08c..9e54f33474c8 100644 --- a/gaming/apiv1beta/game_server_deployments_client_example_test.go +++ b/gaming/apiv1beta/game_server_deployments_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewGameServerDeploymentsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleGameServerDeploymentsClient_ListGameServerDeployments() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.ListGameServerDeploymentsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleGameServerDeploymentsClient_ListGameServerDeployments() { } func ExampleGameServerDeploymentsClient_GetGameServerDeployment() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetGameServerDeploymentRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleGameServerDeploymentsClient_GetGameServerDeployment() { } func ExampleGameServerDeploymentsClient_CreateGameServerDeployment() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.CreateGameServerDeploymentRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleGameServerDeploymentsClient_CreateGameServerDeployment() { } func ExampleGameServerDeploymentsClient_DeleteGameServerDeployment() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.DeleteGameServerDeploymentRequest{ // TODO: Fill request struct fields. @@ -130,13 +127,12 @@ func ExampleGameServerDeploymentsClient_DeleteGameServerDeployment() { } func ExampleGameServerDeploymentsClient_UpdateGameServerDeployment() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.UpdateGameServerDeploymentRequest{ // TODO: Fill request struct fields. @@ -155,13 +151,12 @@ func ExampleGameServerDeploymentsClient_UpdateGameServerDeployment() { } func ExampleGameServerDeploymentsClient_GetGameServerDeploymentRollout() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetGameServerDeploymentRolloutRequest{ // TODO: Fill request struct fields. @@ -175,13 +170,12 @@ func ExampleGameServerDeploymentsClient_GetGameServerDeploymentRollout() { } func ExampleGameServerDeploymentsClient_UpdateGameServerDeploymentRollout() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.UpdateGameServerDeploymentRolloutRequest{ // TODO: Fill request struct fields. @@ -200,13 +194,12 @@ func ExampleGameServerDeploymentsClient_UpdateGameServerDeploymentRollout() { } func ExampleGameServerDeploymentsClient_PreviewGameServerDeploymentRollout() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewGameServerDeploymentRolloutRequest{ // TODO: Fill request struct fields. @@ -220,13 +213,12 @@ func ExampleGameServerDeploymentsClient_PreviewGameServerDeploymentRollout() { } func ExampleGameServerDeploymentsClient_FetchDeploymentState() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.FetchDeploymentStateRequest{ // TODO: Fill request struct fields. diff --git a/gaming/apiv1beta/realms_client.go b/gaming/apiv1beta/realms_client.go index 863c8285b1ac..7f37ad2cc313 100644 --- a/gaming/apiv1beta/realms_client.go +++ b/gaming/apiv1beta/realms_client.go @@ -50,7 +50,7 @@ type RealmsCallOptions struct { PreviewRealmUpdate []gax.CallOption } -func defaultRealmsClientOptions() []option.ClientOption { +func defaultRealmsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("gameservices.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("gameservices.mtls.googleapis.com:443"), @@ -103,38 +103,142 @@ func defaultRealmsCallOptions() *RealmsCallOptions { } } +// internalRealmsClient is an interface that defines the methods availaible from Game Services API. +type internalRealmsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListRealms(context.Context, *gamingpb.ListRealmsRequest, ...gax.CallOption) *RealmIterator + GetRealm(context.Context, *gamingpb.GetRealmRequest, ...gax.CallOption) (*gamingpb.Realm, error) + CreateRealm(context.Context, *gamingpb.CreateRealmRequest, ...gax.CallOption) (*CreateRealmOperation, error) + CreateRealmOperation(name string) *CreateRealmOperation + DeleteRealm(context.Context, *gamingpb.DeleteRealmRequest, ...gax.CallOption) (*DeleteRealmOperation, error) + DeleteRealmOperation(name string) *DeleteRealmOperation + UpdateRealm(context.Context, *gamingpb.UpdateRealmRequest, ...gax.CallOption) (*UpdateRealmOperation, error) + UpdateRealmOperation(name string) *UpdateRealmOperation + PreviewRealmUpdate(context.Context, *gamingpb.PreviewRealmUpdateRequest, ...gax.CallOption) (*gamingpb.PreviewRealmUpdateResponse, error) +} + // RealmsClient is a client for interacting with Game Services API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A realm is a grouping of game server clusters that are considered +// interchangeable. type RealmsClient struct { + // The internal transport-dependent client. + internalClient internalRealmsClient + + // The call options for this service. + CallOptions *RealmsCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *RealmsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *RealmsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *RealmsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListRealms lists realms in a given project and location. +func (c *RealmsClient) ListRealms(ctx context.Context, req *gamingpb.ListRealmsRequest, opts ...gax.CallOption) *RealmIterator { + return c.internalClient.ListRealms(ctx, req, opts...) +} + +// GetRealm gets details of a single realm. +func (c *RealmsClient) GetRealm(ctx context.Context, req *gamingpb.GetRealmRequest, opts ...gax.CallOption) (*gamingpb.Realm, error) { + return c.internalClient.GetRealm(ctx, req, opts...) +} + +// CreateRealm creates a new realm in a given project and location. +func (c *RealmsClient) CreateRealm(ctx context.Context, req *gamingpb.CreateRealmRequest, opts ...gax.CallOption) (*CreateRealmOperation, error) { + return c.internalClient.CreateRealm(ctx, req, opts...) +} + +// CreateRealmOperation returns a new CreateRealmOperation from a given name. +// The name must be that of a previously created CreateRealmOperation, possibly from a different process. +func (c *RealmsClient) CreateRealmOperation(name string) *CreateRealmOperation { + return c.internalClient.CreateRealmOperation(name) +} + +// DeleteRealm deletes a single realm. +func (c *RealmsClient) DeleteRealm(ctx context.Context, req *gamingpb.DeleteRealmRequest, opts ...gax.CallOption) (*DeleteRealmOperation, error) { + return c.internalClient.DeleteRealm(ctx, req, opts...) +} + +// DeleteRealmOperation returns a new DeleteRealmOperation from a given name. +// The name must be that of a previously created DeleteRealmOperation, possibly from a different process. +func (c *RealmsClient) DeleteRealmOperation(name string) *DeleteRealmOperation { + return c.internalClient.DeleteRealmOperation(name) +} + +// UpdateRealm patches a single realm. +func (c *RealmsClient) UpdateRealm(ctx context.Context, req *gamingpb.UpdateRealmRequest, opts ...gax.CallOption) (*UpdateRealmOperation, error) { + return c.internalClient.UpdateRealm(ctx, req, opts...) +} + +// UpdateRealmOperation returns a new UpdateRealmOperation from a given name. +// The name must be that of a previously created UpdateRealmOperation, possibly from a different process. +func (c *RealmsClient) UpdateRealmOperation(name string) *UpdateRealmOperation { + return c.internalClient.UpdateRealmOperation(name) +} + +// PreviewRealmUpdate previews patches to a single realm. +func (c *RealmsClient) PreviewRealmUpdate(ctx context.Context, req *gamingpb.PreviewRealmUpdateRequest, opts ...gax.CallOption) (*gamingpb.PreviewRealmUpdateResponse, error) { + return c.internalClient.PreviewRealmUpdate(ctx, req, opts...) +} + +// realmsGRPCClient is a client for interacting with Game Services API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type realmsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing RealmsClient + CallOptions **RealmsCallOptions + // The gRPC API client. realmsClient gamingpb.RealmsServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *RealmsCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewRealmsClient creates a new realms service client. +// NewRealmsClient creates a new realms service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A realm is a grouping of game server clusters that are considered // interchangeable. func NewRealmsClient(ctx context.Context, opts ...option.ClientOption) (*RealmsClient, error) { - clientOpts := defaultRealmsClientOptions() - + clientOpts := defaultRealmsGRPCClientOptions() if newRealmsClientHook != nil { hookOpts, err := newRealmsClientHook(ctx, clientHookParams{}) if err != nil { @@ -152,16 +256,19 @@ func NewRealmsClient(ctx context.Context, opts ...option.ClientOption) (*RealmsC if err != nil { return nil, err } - c := &RealmsClient{ + client := RealmsClient{CallOptions: defaultRealmsCallOptions()} + + c := &realmsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultRealmsCallOptions(), - - realmsClient: gamingpb.NewRealmsServiceClient(connPool), + realmsClient: gamingpb.NewRealmsServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -171,36 +278,36 @@ func NewRealmsClient(ctx context.Context, opts ...option.ClientOption) (*RealmsC // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *RealmsClient) Connection() *grpc.ClientConn { +func (c *realmsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *RealmsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *RealmsClient) setGoogleClientInfo(keyval ...string) { +func (c *realmsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListRealms lists realms in a given project and location. -func (c *RealmsClient) ListRealms(ctx context.Context, req *gamingpb.ListRealmsRequest, opts ...gax.CallOption) *RealmIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *realmsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *realmsGRPCClient) ListRealms(ctx context.Context, req *gamingpb.ListRealmsRequest, opts ...gax.CallOption) *RealmIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListRealms[0:len(c.CallOptions.ListRealms):len(c.CallOptions.ListRealms)], opts...) + opts = append((*c.CallOptions).ListRealms[0:len((*c.CallOptions).ListRealms):len((*c.CallOptions).ListRealms)], opts...) it := &RealmIterator{} req = proto.Clone(req).(*gamingpb.ListRealmsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*gamingpb.Realm, string, error) { @@ -237,8 +344,7 @@ func (c *RealmsClient) ListRealms(ctx context.Context, req *gamingpb.ListRealmsR return it } -// GetRealm gets details of a single realm. -func (c *RealmsClient) GetRealm(ctx context.Context, req *gamingpb.GetRealmRequest, opts ...gax.CallOption) (*gamingpb.Realm, error) { +func (c *realmsGRPCClient) GetRealm(ctx context.Context, req *gamingpb.GetRealmRequest, opts ...gax.CallOption) (*gamingpb.Realm, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -246,7 +352,7 @@ func (c *RealmsClient) GetRealm(ctx context.Context, req *gamingpb.GetRealmReque } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetRealm[0:len(c.CallOptions.GetRealm):len(c.CallOptions.GetRealm)], opts...) + opts = append((*c.CallOptions).GetRealm[0:len((*c.CallOptions).GetRealm):len((*c.CallOptions).GetRealm)], opts...) var resp *gamingpb.Realm err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -259,8 +365,7 @@ func (c *RealmsClient) GetRealm(ctx context.Context, req *gamingpb.GetRealmReque return resp, nil } -// CreateRealm creates a new realm in a given project and location. -func (c *RealmsClient) CreateRealm(ctx context.Context, req *gamingpb.CreateRealmRequest, opts ...gax.CallOption) (*CreateRealmOperation, error) { +func (c *realmsGRPCClient) CreateRealm(ctx context.Context, req *gamingpb.CreateRealmRequest, opts ...gax.CallOption) (*CreateRealmOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -268,7 +373,7 @@ func (c *RealmsClient) CreateRealm(ctx context.Context, req *gamingpb.CreateReal } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateRealm[0:len(c.CallOptions.CreateRealm):len(c.CallOptions.CreateRealm)], opts...) + opts = append((*c.CallOptions).CreateRealm[0:len((*c.CallOptions).CreateRealm):len((*c.CallOptions).CreateRealm)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -279,12 +384,11 @@ func (c *RealmsClient) CreateRealm(ctx context.Context, req *gamingpb.CreateReal return nil, err } return &CreateRealmOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteRealm deletes a single realm. -func (c *RealmsClient) DeleteRealm(ctx context.Context, req *gamingpb.DeleteRealmRequest, opts ...gax.CallOption) (*DeleteRealmOperation, error) { +func (c *realmsGRPCClient) DeleteRealm(ctx context.Context, req *gamingpb.DeleteRealmRequest, opts ...gax.CallOption) (*DeleteRealmOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -292,7 +396,7 @@ func (c *RealmsClient) DeleteRealm(ctx context.Context, req *gamingpb.DeleteReal } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteRealm[0:len(c.CallOptions.DeleteRealm):len(c.CallOptions.DeleteRealm)], opts...) + opts = append((*c.CallOptions).DeleteRealm[0:len((*c.CallOptions).DeleteRealm):len((*c.CallOptions).DeleteRealm)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -303,12 +407,11 @@ func (c *RealmsClient) DeleteRealm(ctx context.Context, req *gamingpb.DeleteReal return nil, err } return &DeleteRealmOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateRealm patches a single realm. -func (c *RealmsClient) UpdateRealm(ctx context.Context, req *gamingpb.UpdateRealmRequest, opts ...gax.CallOption) (*UpdateRealmOperation, error) { +func (c *realmsGRPCClient) UpdateRealm(ctx context.Context, req *gamingpb.UpdateRealmRequest, opts ...gax.CallOption) (*UpdateRealmOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -316,7 +419,7 @@ func (c *RealmsClient) UpdateRealm(ctx context.Context, req *gamingpb.UpdateReal } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "realm.name", url.QueryEscape(req.GetRealm().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateRealm[0:len(c.CallOptions.UpdateRealm):len(c.CallOptions.UpdateRealm)], opts...) + opts = append((*c.CallOptions).UpdateRealm[0:len((*c.CallOptions).UpdateRealm):len((*c.CallOptions).UpdateRealm)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -327,12 +430,11 @@ func (c *RealmsClient) UpdateRealm(ctx context.Context, req *gamingpb.UpdateReal return nil, err } return &UpdateRealmOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// PreviewRealmUpdate previews patches to a single realm. -func (c *RealmsClient) PreviewRealmUpdate(ctx context.Context, req *gamingpb.PreviewRealmUpdateRequest, opts ...gax.CallOption) (*gamingpb.PreviewRealmUpdateResponse, error) { +func (c *realmsGRPCClient) PreviewRealmUpdate(ctx context.Context, req *gamingpb.PreviewRealmUpdateRequest, opts ...gax.CallOption) (*gamingpb.PreviewRealmUpdateResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -340,7 +442,7 @@ func (c *RealmsClient) PreviewRealmUpdate(ctx context.Context, req *gamingpb.Pre } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "realm.name", url.QueryEscape(req.GetRealm().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PreviewRealmUpdate[0:len(c.CallOptions.PreviewRealmUpdate):len(c.CallOptions.PreviewRealmUpdate)], opts...) + opts = append((*c.CallOptions).PreviewRealmUpdate[0:len((*c.CallOptions).PreviewRealmUpdate):len((*c.CallOptions).PreviewRealmUpdate)], opts...) var resp *gamingpb.PreviewRealmUpdateResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -360,9 +462,9 @@ type CreateRealmOperation struct { // CreateRealmOperation returns a new CreateRealmOperation from a given name. // The name must be that of a previously created CreateRealmOperation, possibly from a different process. -func (c *RealmsClient) CreateRealmOperation(name string) *CreateRealmOperation { +func (c *realmsGRPCClient) CreateRealmOperation(name string) *CreateRealmOperation { return &CreateRealmOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -429,9 +531,9 @@ type DeleteRealmOperation struct { // DeleteRealmOperation returns a new DeleteRealmOperation from a given name. // The name must be that of a previously created DeleteRealmOperation, possibly from a different process. -func (c *RealmsClient) DeleteRealmOperation(name string) *DeleteRealmOperation { +func (c *realmsGRPCClient) DeleteRealmOperation(name string) *DeleteRealmOperation { return &DeleteRealmOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -487,9 +589,9 @@ type UpdateRealmOperation struct { // UpdateRealmOperation returns a new UpdateRealmOperation from a given name. // The name must be that of a previously created UpdateRealmOperation, possibly from a different process. -func (c *RealmsClient) UpdateRealmOperation(name string) *UpdateRealmOperation { +func (c *realmsGRPCClient) UpdateRealmOperation(name string) *UpdateRealmOperation { return &UpdateRealmOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/gaming/apiv1beta/realms_client_example_test.go b/gaming/apiv1beta/realms_client_example_test.go index 644f28037127..2a11ad18c6e5 100644 --- a/gaming/apiv1beta/realms_client_example_test.go +++ b/gaming/apiv1beta/realms_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewRealmsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleRealmsClient_ListRealms() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.ListRealmsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleRealmsClient_ListRealms() { } func ExampleRealmsClient_GetRealm() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetRealmRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleRealmsClient_GetRealm() { } func ExampleRealmsClient_CreateRealm() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.CreateRealmRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleRealmsClient_CreateRealm() { } func ExampleRealmsClient_DeleteRealm() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.DeleteRealmRequest{ // TODO: Fill request struct fields. @@ -130,13 +127,12 @@ func ExampleRealmsClient_DeleteRealm() { } func ExampleRealmsClient_UpdateRealm() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.UpdateRealmRequest{ // TODO: Fill request struct fields. @@ -155,13 +151,12 @@ func ExampleRealmsClient_UpdateRealm() { } func ExampleRealmsClient_PreviewRealmUpdate() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewRealmUpdateRequest{ // TODO: Fill request struct fields. diff --git a/gkehub/apiv1beta1/doc.go b/gkehub/apiv1beta1/doc.go index be63f94dfaca..8d3c4a6e29b3 100644 --- a/gkehub/apiv1beta1/doc.go +++ b/gkehub/apiv1beta1/doc.go @@ -17,6 +17,8 @@ // Package gkehub is an auto-generated package for the // GKE Hub. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -26,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package gkehub // import "cloud.google.com/go/gkehub/apiv1beta1" import ( @@ -46,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/gkehub/apiv1beta1/gke_hub_membership_client.go b/gkehub/apiv1beta1/gke_hub_membership_client.go index 80cc5613b53e..624a09d6109d 100644 --- a/gkehub/apiv1beta1/gke_hub_membership_client.go +++ b/gkehub/apiv1beta1/gke_hub_membership_client.go @@ -52,7 +52,7 @@ type GkeHubMembershipCallOptions struct { GenerateExclusivityManifest []gax.CallOption } -func defaultGkeHubMembershipClientOptions() []option.ClientOption { +func defaultGkeHubMembershipGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("gkehub.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("gkehub.mtls.googleapis.com:443"), @@ -157,38 +157,166 @@ func defaultGkeHubMembershipCallOptions() *GkeHubMembershipCallOptions { } } +// internalGkeHubMembershipClient is an interface that defines the methods availaible from GKE Hub. +type internalGkeHubMembershipClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListMemberships(context.Context, *gkehubpb.ListMembershipsRequest, ...gax.CallOption) *MembershipIterator + GetMembership(context.Context, *gkehubpb.GetMembershipRequest, ...gax.CallOption) (*gkehubpb.Membership, error) + CreateMembership(context.Context, *gkehubpb.CreateMembershipRequest, ...gax.CallOption) (*CreateMembershipOperation, error) + CreateMembershipOperation(name string) *CreateMembershipOperation + DeleteMembership(context.Context, *gkehubpb.DeleteMembershipRequest, ...gax.CallOption) (*DeleteMembershipOperation, error) + DeleteMembershipOperation(name string) *DeleteMembershipOperation + UpdateMembership(context.Context, *gkehubpb.UpdateMembershipRequest, ...gax.CallOption) (*UpdateMembershipOperation, error) + UpdateMembershipOperation(name string) *UpdateMembershipOperation + GenerateConnectManifest(context.Context, *gkehubpb.GenerateConnectManifestRequest, ...gax.CallOption) (*gkehubpb.GenerateConnectManifestResponse, error) + ValidateExclusivity(context.Context, *gkehubpb.ValidateExclusivityRequest, ...gax.CallOption) (*gkehubpb.ValidateExclusivityResponse, error) + GenerateExclusivityManifest(context.Context, *gkehubpb.GenerateExclusivityManifestRequest, ...gax.CallOption) (*gkehubpb.GenerateExclusivityManifestResponse, error) +} + // GkeHubMembershipClient is a client for interacting with GKE Hub. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// GKE Hub CRUD API for the Membership resource. +// The Membership service is currently only available in the global location. type GkeHubMembershipClient struct { + // The internal transport-dependent client. + internalClient internalGkeHubMembershipClient + + // The call options for this service. + CallOptions *GkeHubMembershipCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *GkeHubMembershipClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *GkeHubMembershipClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *GkeHubMembershipClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListMemberships lists Memberships in a given project and location. +func (c *GkeHubMembershipClient) ListMemberships(ctx context.Context, req *gkehubpb.ListMembershipsRequest, opts ...gax.CallOption) *MembershipIterator { + return c.internalClient.ListMemberships(ctx, req, opts...) +} + +// GetMembership gets the details of a Membership. +func (c *GkeHubMembershipClient) GetMembership(ctx context.Context, req *gkehubpb.GetMembershipRequest, opts ...gax.CallOption) (*gkehubpb.Membership, error) { + return c.internalClient.GetMembership(ctx, req, opts...) +} + +// CreateMembership adds a new Membership. +func (c *GkeHubMembershipClient) CreateMembership(ctx context.Context, req *gkehubpb.CreateMembershipRequest, opts ...gax.CallOption) (*CreateMembershipOperation, error) { + return c.internalClient.CreateMembership(ctx, req, opts...) +} + +// CreateMembershipOperation returns a new CreateMembershipOperation from a given name. +// The name must be that of a previously created CreateMembershipOperation, possibly from a different process. +func (c *GkeHubMembershipClient) CreateMembershipOperation(name string) *CreateMembershipOperation { + return c.internalClient.CreateMembershipOperation(name) +} + +// DeleteMembership removes a Membership. +func (c *GkeHubMembershipClient) DeleteMembership(ctx context.Context, req *gkehubpb.DeleteMembershipRequest, opts ...gax.CallOption) (*DeleteMembershipOperation, error) { + return c.internalClient.DeleteMembership(ctx, req, opts...) +} + +// DeleteMembershipOperation returns a new DeleteMembershipOperation from a given name. +// The name must be that of a previously created DeleteMembershipOperation, possibly from a different process. +func (c *GkeHubMembershipClient) DeleteMembershipOperation(name string) *DeleteMembershipOperation { + return c.internalClient.DeleteMembershipOperation(name) +} + +// UpdateMembership updates an existing Membership. +func (c *GkeHubMembershipClient) UpdateMembership(ctx context.Context, req *gkehubpb.UpdateMembershipRequest, opts ...gax.CallOption) (*UpdateMembershipOperation, error) { + return c.internalClient.UpdateMembership(ctx, req, opts...) +} + +// UpdateMembershipOperation returns a new UpdateMembershipOperation from a given name. +// The name must be that of a previously created UpdateMembershipOperation, possibly from a different process. +func (c *GkeHubMembershipClient) UpdateMembershipOperation(name string) *UpdateMembershipOperation { + return c.internalClient.UpdateMembershipOperation(name) +} + +// GenerateConnectManifest generates the manifest for deployment of the GKE connect agent. +func (c *GkeHubMembershipClient) GenerateConnectManifest(ctx context.Context, req *gkehubpb.GenerateConnectManifestRequest, opts ...gax.CallOption) (*gkehubpb.GenerateConnectManifestResponse, error) { + return c.internalClient.GenerateConnectManifest(ctx, req, opts...) +} + +// ValidateExclusivity validateExclusivity validates the state of exclusivity in the cluster. +// The validation does not depend on an existing Hub membership resource. +func (c *GkeHubMembershipClient) ValidateExclusivity(ctx context.Context, req *gkehubpb.ValidateExclusivityRequest, opts ...gax.CallOption) (*gkehubpb.ValidateExclusivityResponse, error) { + return c.internalClient.ValidateExclusivity(ctx, req, opts...) +} + +// GenerateExclusivityManifest generateExclusivityManifest generates the manifests to update the +// exclusivity artifacts in the cluster if needed. +// +// Exclusivity artifacts include the Membership custom resource definition +// (CRD) and the singleton Membership custom resource (CR). Combined with +// ValidateExclusivity, exclusivity artifacts guarantee that a Kubernetes +// cluster is only registered to a single GKE Hub. +// +// The Membership CRD is versioned, and may require conversion when the GKE +// Hub API server begins serving a newer version of the CRD and +// corresponding CR. The response will be the converted CRD and CR if there +// are any differences between the versions. +func (c *GkeHubMembershipClient) GenerateExclusivityManifest(ctx context.Context, req *gkehubpb.GenerateExclusivityManifestRequest, opts ...gax.CallOption) (*gkehubpb.GenerateExclusivityManifestResponse, error) { + return c.internalClient.GenerateExclusivityManifest(ctx, req, opts...) +} + +// gkeHubMembershipGRPCClient is a client for interacting with GKE Hub over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gkeHubMembershipGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing GkeHubMembershipClient + CallOptions **GkeHubMembershipCallOptions + // The gRPC API client. gkeHubMembershipClient gkehubpb.GkeHubMembershipServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *GkeHubMembershipCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewGkeHubMembershipClient creates a new gke hub membership service client. +// NewGkeHubMembershipClient creates a new gke hub membership service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // GKE Hub CRUD API for the Membership resource. // The Membership service is currently only available in the global location. func NewGkeHubMembershipClient(ctx context.Context, opts ...option.ClientOption) (*GkeHubMembershipClient, error) { - clientOpts := defaultGkeHubMembershipClientOptions() - + clientOpts := defaultGkeHubMembershipGRPCClientOptions() if newGkeHubMembershipClientHook != nil { hookOpts, err := newGkeHubMembershipClientHook(ctx, clientHookParams{}) if err != nil { @@ -206,16 +334,19 @@ func NewGkeHubMembershipClient(ctx context.Context, opts ...option.ClientOption) if err != nil { return nil, err } - c := &GkeHubMembershipClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultGkeHubMembershipCallOptions(), + client := GkeHubMembershipClient{CallOptions: defaultGkeHubMembershipCallOptions()} + c := &gkeHubMembershipGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, gkeHubMembershipClient: gkehubpb.NewGkeHubMembershipServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -225,36 +356,36 @@ func NewGkeHubMembershipClient(ctx context.Context, opts ...option.ClientOption) // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *GkeHubMembershipClient) Connection() *grpc.ClientConn { +func (c *gkeHubMembershipGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *GkeHubMembershipClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *GkeHubMembershipClient) setGoogleClientInfo(keyval ...string) { +func (c *gkeHubMembershipGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListMemberships lists Memberships in a given project and location. -func (c *GkeHubMembershipClient) ListMemberships(ctx context.Context, req *gkehubpb.ListMembershipsRequest, opts ...gax.CallOption) *MembershipIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gkeHubMembershipGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gkeHubMembershipGRPCClient) ListMemberships(ctx context.Context, req *gkehubpb.ListMembershipsRequest, opts ...gax.CallOption) *MembershipIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListMemberships[0:len(c.CallOptions.ListMemberships):len(c.CallOptions.ListMemberships)], opts...) + opts = append((*c.CallOptions).ListMemberships[0:len((*c.CallOptions).ListMemberships):len((*c.CallOptions).ListMemberships)], opts...) it := &MembershipIterator{} req = proto.Clone(req).(*gkehubpb.ListMembershipsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*gkehubpb.Membership, string, error) { @@ -291,8 +422,7 @@ func (c *GkeHubMembershipClient) ListMemberships(ctx context.Context, req *gkehu return it } -// GetMembership gets the details of a Membership. -func (c *GkeHubMembershipClient) GetMembership(ctx context.Context, req *gkehubpb.GetMembershipRequest, opts ...gax.CallOption) (*gkehubpb.Membership, error) { +func (c *gkeHubMembershipGRPCClient) GetMembership(ctx context.Context, req *gkehubpb.GetMembershipRequest, opts ...gax.CallOption) (*gkehubpb.Membership, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -300,7 +430,7 @@ func (c *GkeHubMembershipClient) GetMembership(ctx context.Context, req *gkehubp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetMembership[0:len(c.CallOptions.GetMembership):len(c.CallOptions.GetMembership)], opts...) + opts = append((*c.CallOptions).GetMembership[0:len((*c.CallOptions).GetMembership):len((*c.CallOptions).GetMembership)], opts...) var resp *gkehubpb.Membership err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -313,8 +443,7 @@ func (c *GkeHubMembershipClient) GetMembership(ctx context.Context, req *gkehubp return resp, nil } -// CreateMembership adds a new Membership. -func (c *GkeHubMembershipClient) CreateMembership(ctx context.Context, req *gkehubpb.CreateMembershipRequest, opts ...gax.CallOption) (*CreateMembershipOperation, error) { +func (c *gkeHubMembershipGRPCClient) CreateMembership(ctx context.Context, req *gkehubpb.CreateMembershipRequest, opts ...gax.CallOption) (*CreateMembershipOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -322,7 +451,7 @@ func (c *GkeHubMembershipClient) CreateMembership(ctx context.Context, req *gkeh } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateMembership[0:len(c.CallOptions.CreateMembership):len(c.CallOptions.CreateMembership)], opts...) + opts = append((*c.CallOptions).CreateMembership[0:len((*c.CallOptions).CreateMembership):len((*c.CallOptions).CreateMembership)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -333,12 +462,11 @@ func (c *GkeHubMembershipClient) CreateMembership(ctx context.Context, req *gkeh return nil, err } return &CreateMembershipOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteMembership removes a Membership. -func (c *GkeHubMembershipClient) DeleteMembership(ctx context.Context, req *gkehubpb.DeleteMembershipRequest, opts ...gax.CallOption) (*DeleteMembershipOperation, error) { +func (c *gkeHubMembershipGRPCClient) DeleteMembership(ctx context.Context, req *gkehubpb.DeleteMembershipRequest, opts ...gax.CallOption) (*DeleteMembershipOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -346,7 +474,7 @@ func (c *GkeHubMembershipClient) DeleteMembership(ctx context.Context, req *gkeh } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteMembership[0:len(c.CallOptions.DeleteMembership):len(c.CallOptions.DeleteMembership)], opts...) + opts = append((*c.CallOptions).DeleteMembership[0:len((*c.CallOptions).DeleteMembership):len((*c.CallOptions).DeleteMembership)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -357,12 +485,11 @@ func (c *GkeHubMembershipClient) DeleteMembership(ctx context.Context, req *gkeh return nil, err } return &DeleteMembershipOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateMembership updates an existing Membership. -func (c *GkeHubMembershipClient) UpdateMembership(ctx context.Context, req *gkehubpb.UpdateMembershipRequest, opts ...gax.CallOption) (*UpdateMembershipOperation, error) { +func (c *gkeHubMembershipGRPCClient) UpdateMembership(ctx context.Context, req *gkehubpb.UpdateMembershipRequest, opts ...gax.CallOption) (*UpdateMembershipOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -370,7 +497,7 @@ func (c *GkeHubMembershipClient) UpdateMembership(ctx context.Context, req *gkeh } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateMembership[0:len(c.CallOptions.UpdateMembership):len(c.CallOptions.UpdateMembership)], opts...) + opts = append((*c.CallOptions).UpdateMembership[0:len((*c.CallOptions).UpdateMembership):len((*c.CallOptions).UpdateMembership)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -381,12 +508,11 @@ func (c *GkeHubMembershipClient) UpdateMembership(ctx context.Context, req *gkeh return nil, err } return &UpdateMembershipOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GenerateConnectManifest generates the manifest for deployment of the GKE connect agent. -func (c *GkeHubMembershipClient) GenerateConnectManifest(ctx context.Context, req *gkehubpb.GenerateConnectManifestRequest, opts ...gax.CallOption) (*gkehubpb.GenerateConnectManifestResponse, error) { +func (c *gkeHubMembershipGRPCClient) GenerateConnectManifest(ctx context.Context, req *gkehubpb.GenerateConnectManifestRequest, opts ...gax.CallOption) (*gkehubpb.GenerateConnectManifestResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -394,7 +520,7 @@ func (c *GkeHubMembershipClient) GenerateConnectManifest(ctx context.Context, re } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GenerateConnectManifest[0:len(c.CallOptions.GenerateConnectManifest):len(c.CallOptions.GenerateConnectManifest)], opts...) + opts = append((*c.CallOptions).GenerateConnectManifest[0:len((*c.CallOptions).GenerateConnectManifest):len((*c.CallOptions).GenerateConnectManifest)], opts...) var resp *gkehubpb.GenerateConnectManifestResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -407,9 +533,7 @@ func (c *GkeHubMembershipClient) GenerateConnectManifest(ctx context.Context, re return resp, nil } -// ValidateExclusivity validateExclusivity validates the state of exclusivity in the cluster. -// The validation does not depend on an existing Hub membership resource. -func (c *GkeHubMembershipClient) ValidateExclusivity(ctx context.Context, req *gkehubpb.ValidateExclusivityRequest, opts ...gax.CallOption) (*gkehubpb.ValidateExclusivityResponse, error) { +func (c *gkeHubMembershipGRPCClient) ValidateExclusivity(ctx context.Context, req *gkehubpb.ValidateExclusivityRequest, opts ...gax.CallOption) (*gkehubpb.ValidateExclusivityResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -417,7 +541,7 @@ func (c *GkeHubMembershipClient) ValidateExclusivity(ctx context.Context, req *g } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ValidateExclusivity[0:len(c.CallOptions.ValidateExclusivity):len(c.CallOptions.ValidateExclusivity)], opts...) + opts = append((*c.CallOptions).ValidateExclusivity[0:len((*c.CallOptions).ValidateExclusivity):len((*c.CallOptions).ValidateExclusivity)], opts...) var resp *gkehubpb.ValidateExclusivityResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -430,19 +554,7 @@ func (c *GkeHubMembershipClient) ValidateExclusivity(ctx context.Context, req *g return resp, nil } -// GenerateExclusivityManifest generateExclusivityManifest generates the manifests to update the -// exclusivity artifacts in the cluster if needed. -// -// Exclusivity artifacts include the Membership custom resource definition -// (CRD) and the singleton Membership custom resource (CR). Combined with -// ValidateExclusivity, exclusivity artifacts guarantee that a Kubernetes -// cluster is only registered to a single GKE Hub. -// -// The Membership CRD is versioned, and may require conversion when the GKE -// Hub API server begins serving a newer version of the CRD and -// corresponding CR. The response will be the converted CRD and CR if there -// are any differences between the versions. -func (c *GkeHubMembershipClient) GenerateExclusivityManifest(ctx context.Context, req *gkehubpb.GenerateExclusivityManifestRequest, opts ...gax.CallOption) (*gkehubpb.GenerateExclusivityManifestResponse, error) { +func (c *gkeHubMembershipGRPCClient) GenerateExclusivityManifest(ctx context.Context, req *gkehubpb.GenerateExclusivityManifestRequest, opts ...gax.CallOption) (*gkehubpb.GenerateExclusivityManifestResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -450,7 +562,7 @@ func (c *GkeHubMembershipClient) GenerateExclusivityManifest(ctx context.Context } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GenerateExclusivityManifest[0:len(c.CallOptions.GenerateExclusivityManifest):len(c.CallOptions.GenerateExclusivityManifest)], opts...) + opts = append((*c.CallOptions).GenerateExclusivityManifest[0:len((*c.CallOptions).GenerateExclusivityManifest):len((*c.CallOptions).GenerateExclusivityManifest)], opts...) var resp *gkehubpb.GenerateExclusivityManifestResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -470,9 +582,9 @@ type CreateMembershipOperation struct { // CreateMembershipOperation returns a new CreateMembershipOperation from a given name. // The name must be that of a previously created CreateMembershipOperation, possibly from a different process. -func (c *GkeHubMembershipClient) CreateMembershipOperation(name string) *CreateMembershipOperation { +func (c *gkeHubMembershipGRPCClient) CreateMembershipOperation(name string) *CreateMembershipOperation { return &CreateMembershipOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -539,9 +651,9 @@ type DeleteMembershipOperation struct { // DeleteMembershipOperation returns a new DeleteMembershipOperation from a given name. // The name must be that of a previously created DeleteMembershipOperation, possibly from a different process. -func (c *GkeHubMembershipClient) DeleteMembershipOperation(name string) *DeleteMembershipOperation { +func (c *gkeHubMembershipGRPCClient) DeleteMembershipOperation(name string) *DeleteMembershipOperation { return &DeleteMembershipOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -597,9 +709,9 @@ type UpdateMembershipOperation struct { // UpdateMembershipOperation returns a new UpdateMembershipOperation from a given name. // The name must be that of a previously created UpdateMembershipOperation, possibly from a different process. -func (c *GkeHubMembershipClient) UpdateMembershipOperation(name string) *UpdateMembershipOperation { +func (c *gkeHubMembershipGRPCClient) UpdateMembershipOperation(name string) *UpdateMembershipOperation { return &UpdateMembershipOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/gkehub/apiv1beta1/gke_hub_membership_client_example_test.go b/gkehub/apiv1beta1/gke_hub_membership_client_example_test.go index 046f4e7e506a..07070569b6d4 100644 --- a/gkehub/apiv1beta1/gke_hub_membership_client_example_test.go +++ b/gkehub/apiv1beta1/gke_hub_membership_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewGkeHubMembershipClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleGkeHubMembershipClient_ListMemberships() { - // import gkehubpb "google.golang.org/genproto/googleapis/cloud/gkehub/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gkehub.NewGkeHubMembershipClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gkehubpb.ListMembershipsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleGkeHubMembershipClient_ListMemberships() { } func ExampleGkeHubMembershipClient_GetMembership() { - // import gkehubpb "google.golang.org/genproto/googleapis/cloud/gkehub/v1beta1" - ctx := context.Background() c, err := gkehub.NewGkeHubMembershipClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gkehubpb.GetMembershipRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleGkeHubMembershipClient_GetMembership() { } func ExampleGkeHubMembershipClient_CreateMembership() { - // import gkehubpb "google.golang.org/genproto/googleapis/cloud/gkehub/v1beta1" - ctx := context.Background() c, err := gkehub.NewGkeHubMembershipClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gkehubpb.CreateMembershipRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleGkeHubMembershipClient_CreateMembership() { } func ExampleGkeHubMembershipClient_DeleteMembership() { - // import gkehubpb "google.golang.org/genproto/googleapis/cloud/gkehub/v1beta1" - ctx := context.Background() c, err := gkehub.NewGkeHubMembershipClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gkehubpb.DeleteMembershipRequest{ // TODO: Fill request struct fields. @@ -130,13 +127,12 @@ func ExampleGkeHubMembershipClient_DeleteMembership() { } func ExampleGkeHubMembershipClient_UpdateMembership() { - // import gkehubpb "google.golang.org/genproto/googleapis/cloud/gkehub/v1beta1" - ctx := context.Background() c, err := gkehub.NewGkeHubMembershipClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gkehubpb.UpdateMembershipRequest{ // TODO: Fill request struct fields. @@ -155,13 +151,12 @@ func ExampleGkeHubMembershipClient_UpdateMembership() { } func ExampleGkeHubMembershipClient_GenerateConnectManifest() { - // import gkehubpb "google.golang.org/genproto/googleapis/cloud/gkehub/v1beta1" - ctx := context.Background() c, err := gkehub.NewGkeHubMembershipClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gkehubpb.GenerateConnectManifestRequest{ // TODO: Fill request struct fields. @@ -175,13 +170,12 @@ func ExampleGkeHubMembershipClient_GenerateConnectManifest() { } func ExampleGkeHubMembershipClient_ValidateExclusivity() { - // import gkehubpb "google.golang.org/genproto/googleapis/cloud/gkehub/v1beta1" - ctx := context.Background() c, err := gkehub.NewGkeHubMembershipClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gkehubpb.ValidateExclusivityRequest{ // TODO: Fill request struct fields. @@ -195,13 +189,12 @@ func ExampleGkeHubMembershipClient_ValidateExclusivity() { } func ExampleGkeHubMembershipClient_GenerateExclusivityManifest() { - // import gkehubpb "google.golang.org/genproto/googleapis/cloud/gkehub/v1beta1" - ctx := context.Background() c, err := gkehub.NewGkeHubMembershipClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gkehubpb.GenerateExclusivityManifestRequest{ // TODO: Fill request struct fields. diff --git a/go.mod b/go.mod index 3aa99ff67b3c..a4f5a250225f 100644 --- a/go.mod +++ b/go.mod @@ -16,7 +16,7 @@ require ( golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c golang.org/x/text v0.3.6 golang.org/x/tools v0.1.1 - google.golang.org/api v0.46.0 + google.golang.org/api v0.47.0 google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d google.golang.org/grpc v1.37.1 google.golang.org/protobuf v1.26.0 diff --git a/go.sum b/go.sum index 5eefad904f8d..a9e80ca27689 100644 --- a/go.sum +++ b/go.sum @@ -247,7 +247,6 @@ golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210427180440-81ed05c6b58c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c h1:pkQiBZBvdos9qq4wBAHqlzuZHEXo07pqV06ef90u1WI= golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -299,9 +298,9 @@ golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210503080704-8803ae5d1324/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210510120138-977fb7262007 h1:gG67DSER+11cZvqIMb8S8bt0vZtiN6xWYARwirrOSfE= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015 h1:hZR0X1kPW+nwyJ9xRxqZk1vx5RUObAPBdKVvXPDUH/E= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -389,8 +388,8 @@ google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34q google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= -google.golang.org/api v0.46.0 h1:jkDWHOBIoNSD0OQpq4rtBVu+Rh325MPjXG1rakAp8JU= -google.golang.org/api v0.46.0/go.mod h1:ceL4oozhkAiTID8XMmJBsIxID/9wMXJVVFXPg4ylg3I= +google.golang.org/api v0.47.0 h1:sQLWZQvP6jPGIP4JGPkJu4zHswrv81iobiyszr3b/0I= +google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -438,7 +437,7 @@ google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= -google.golang.org/genproto v0.0.0-20210429181445-86c259c2b4ab/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d h1:bRz6UmsZEz/CzoTjUDp4ZcdguhSWi6CyU299wMQBpZU= google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= @@ -459,7 +458,6 @@ google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA5 google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.37.1 h1:ARnQJNWxGyYJpdf/JXscNlQr/uv607ZPU9Z7ogHi+iI= google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= diff --git a/iam/credentials/apiv1/doc.go b/iam/credentials/apiv1/doc.go index a6f78237db0e..620b245e75ed 100644 --- a/iam/credentials/apiv1/doc.go +++ b/iam/credentials/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package credentials // import "cloud.google.com/go/iam/credentials/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/iam/credentials/apiv1/iam_credentials_client.go b/iam/credentials/apiv1/iam_credentials_client.go index 1ccaf0543e47..84d594ef4164 100644 --- a/iam/credentials/apiv1/iam_credentials_client.go +++ b/iam/credentials/apiv1/iam_credentials_client.go @@ -43,7 +43,7 @@ type IamCredentialsCallOptions struct { SignJwt []gax.CallOption } -func defaultIamCredentialsClientOptions() []option.ClientOption { +func defaultIamCredentialsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("iamcredentials.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("iamcredentials.mtls.googleapis.com:443"), @@ -108,27 +108,101 @@ func defaultIamCredentialsCallOptions() *IamCredentialsCallOptions { } } +// internalIamCredentialsClient is an interface that defines the methods availaible from IAM Service Account Credentials API. +type internalIamCredentialsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + GenerateAccessToken(context.Context, *credentialspb.GenerateAccessTokenRequest, ...gax.CallOption) (*credentialspb.GenerateAccessTokenResponse, error) + GenerateIdToken(context.Context, *credentialspb.GenerateIdTokenRequest, ...gax.CallOption) (*credentialspb.GenerateIdTokenResponse, error) + SignBlob(context.Context, *credentialspb.SignBlobRequest, ...gax.CallOption) (*credentialspb.SignBlobResponse, error) + SignJwt(context.Context, *credentialspb.SignJwtRequest, ...gax.CallOption) (*credentialspb.SignJwtResponse, error) +} + // IamCredentialsClient is a client for interacting with IAM Service Account Credentials API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A service account is a special type of Google account that belongs to your +// application or a virtual machine (VM), instead of to an individual end user. +// Your application assumes the identity of the service account to call Google +// APIs, so that the users aren’t directly involved. +// +// Service account credentials are used to temporarily assume the identity +// of the service account. Supported credential types include OAuth 2.0 access +// tokens, OpenID Connect ID tokens, self-signed JSON Web Tokens (JWTs), and +// more. type IamCredentialsClient struct { + // The internal transport-dependent client. + internalClient internalIamCredentialsClient + + // The call options for this service. + CallOptions *IamCredentialsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *IamCredentialsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *IamCredentialsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *IamCredentialsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// GenerateAccessToken generates an OAuth 2.0 access token for a service account. +func (c *IamCredentialsClient) GenerateAccessToken(ctx context.Context, req *credentialspb.GenerateAccessTokenRequest, opts ...gax.CallOption) (*credentialspb.GenerateAccessTokenResponse, error) { + return c.internalClient.GenerateAccessToken(ctx, req, opts...) +} + +// GenerateIdToken generates an OpenID Connect ID token for a service account. +func (c *IamCredentialsClient) GenerateIdToken(ctx context.Context, req *credentialspb.GenerateIdTokenRequest, opts ...gax.CallOption) (*credentialspb.GenerateIdTokenResponse, error) { + return c.internalClient.GenerateIdToken(ctx, req, opts...) +} + +// SignBlob signs a blob using a service account’s system-managed private key. +func (c *IamCredentialsClient) SignBlob(ctx context.Context, req *credentialspb.SignBlobRequest, opts ...gax.CallOption) (*credentialspb.SignBlobResponse, error) { + return c.internalClient.SignBlob(ctx, req, opts...) +} + +// SignJwt signs a JWT using a service account’s system-managed private key. +func (c *IamCredentialsClient) SignJwt(ctx context.Context, req *credentialspb.SignJwtRequest, opts ...gax.CallOption) (*credentialspb.SignJwtResponse, error) { + return c.internalClient.SignJwt(ctx, req, opts...) +} + +// iamCredentialsGRPCClient is a client for interacting with IAM Service Account Credentials API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type iamCredentialsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing IamCredentialsClient + CallOptions **IamCredentialsCallOptions + // The gRPC API client. iamCredentialsClient credentialspb.IAMCredentialsClient - // The call options for this service. - CallOptions *IamCredentialsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewIamCredentialsClient creates a new iam credentials client. +// NewIamCredentialsClient creates a new iam credentials client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A service account is a special type of Google account that belongs to your // application or a virtual machine (VM), instead of to an individual end user. @@ -140,8 +214,7 @@ type IamCredentialsClient struct { // tokens, OpenID Connect ID tokens, self-signed JSON Web Tokens (JWTs), and // more. func NewIamCredentialsClient(ctx context.Context, opts ...option.ClientOption) (*IamCredentialsClient, error) { - clientOpts := defaultIamCredentialsClientOptions() - + clientOpts := defaultIamCredentialsGRPCClientOptions() if newIamCredentialsClientHook != nil { hookOpts, err := newIamCredentialsClientHook(ctx, clientHookParams{}) if err != nil { @@ -159,42 +232,44 @@ func NewIamCredentialsClient(ctx context.Context, opts ...option.ClientOption) ( if err != nil { return nil, err } - c := &IamCredentialsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultIamCredentialsCallOptions(), + client := IamCredentialsClient{CallOptions: defaultIamCredentialsCallOptions()} + c := &iamCredentialsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, iamCredentialsClient: credentialspb.NewIAMCredentialsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *IamCredentialsClient) Connection() *grpc.ClientConn { +func (c *iamCredentialsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *IamCredentialsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *IamCredentialsClient) setGoogleClientInfo(keyval ...string) { +func (c *iamCredentialsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// GenerateAccessToken generates an OAuth 2.0 access token for a service account. -func (c *IamCredentialsClient) GenerateAccessToken(ctx context.Context, req *credentialspb.GenerateAccessTokenRequest, opts ...gax.CallOption) (*credentialspb.GenerateAccessTokenResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *iamCredentialsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *iamCredentialsGRPCClient) GenerateAccessToken(ctx context.Context, req *credentialspb.GenerateAccessTokenRequest, opts ...gax.CallOption) (*credentialspb.GenerateAccessTokenResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -202,7 +277,7 @@ func (c *IamCredentialsClient) GenerateAccessToken(ctx context.Context, req *cre } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GenerateAccessToken[0:len(c.CallOptions.GenerateAccessToken):len(c.CallOptions.GenerateAccessToken)], opts...) + opts = append((*c.CallOptions).GenerateAccessToken[0:len((*c.CallOptions).GenerateAccessToken):len((*c.CallOptions).GenerateAccessToken)], opts...) var resp *credentialspb.GenerateAccessTokenResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -215,8 +290,7 @@ func (c *IamCredentialsClient) GenerateAccessToken(ctx context.Context, req *cre return resp, nil } -// GenerateIdToken generates an OpenID Connect ID token for a service account. -func (c *IamCredentialsClient) GenerateIdToken(ctx context.Context, req *credentialspb.GenerateIdTokenRequest, opts ...gax.CallOption) (*credentialspb.GenerateIdTokenResponse, error) { +func (c *iamCredentialsGRPCClient) GenerateIdToken(ctx context.Context, req *credentialspb.GenerateIdTokenRequest, opts ...gax.CallOption) (*credentialspb.GenerateIdTokenResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -224,7 +298,7 @@ func (c *IamCredentialsClient) GenerateIdToken(ctx context.Context, req *credent } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GenerateIdToken[0:len(c.CallOptions.GenerateIdToken):len(c.CallOptions.GenerateIdToken)], opts...) + opts = append((*c.CallOptions).GenerateIdToken[0:len((*c.CallOptions).GenerateIdToken):len((*c.CallOptions).GenerateIdToken)], opts...) var resp *credentialspb.GenerateIdTokenResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -237,8 +311,7 @@ func (c *IamCredentialsClient) GenerateIdToken(ctx context.Context, req *credent return resp, nil } -// SignBlob signs a blob using a service account’s system-managed private key. -func (c *IamCredentialsClient) SignBlob(ctx context.Context, req *credentialspb.SignBlobRequest, opts ...gax.CallOption) (*credentialspb.SignBlobResponse, error) { +func (c *iamCredentialsGRPCClient) SignBlob(ctx context.Context, req *credentialspb.SignBlobRequest, opts ...gax.CallOption) (*credentialspb.SignBlobResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -246,7 +319,7 @@ func (c *IamCredentialsClient) SignBlob(ctx context.Context, req *credentialspb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SignBlob[0:len(c.CallOptions.SignBlob):len(c.CallOptions.SignBlob)], opts...) + opts = append((*c.CallOptions).SignBlob[0:len((*c.CallOptions).SignBlob):len((*c.CallOptions).SignBlob)], opts...) var resp *credentialspb.SignBlobResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -259,8 +332,7 @@ func (c *IamCredentialsClient) SignBlob(ctx context.Context, req *credentialspb. return resp, nil } -// SignJwt signs a JWT using a service account’s system-managed private key. -func (c *IamCredentialsClient) SignJwt(ctx context.Context, req *credentialspb.SignJwtRequest, opts ...gax.CallOption) (*credentialspb.SignJwtResponse, error) { +func (c *iamCredentialsGRPCClient) SignJwt(ctx context.Context, req *credentialspb.SignJwtRequest, opts ...gax.CallOption) (*credentialspb.SignJwtResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -268,7 +340,7 @@ func (c *IamCredentialsClient) SignJwt(ctx context.Context, req *credentialspb.S } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SignJwt[0:len(c.CallOptions.SignJwt):len(c.CallOptions.SignJwt)], opts...) + opts = append((*c.CallOptions).SignJwt[0:len((*c.CallOptions).SignJwt):len((*c.CallOptions).SignJwt)], opts...) var resp *credentialspb.SignJwtResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/iam/credentials/apiv1/iam_credentials_client_example_test.go b/iam/credentials/apiv1/iam_credentials_client_example_test.go index a72e432ccbf6..be5d942f89aa 100644 --- a/iam/credentials/apiv1/iam_credentials_client_example_test.go +++ b/iam/credentials/apiv1/iam_credentials_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewIamCredentialsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleIamCredentialsClient_GenerateAccessToken() { - // import credentialspb "google.golang.org/genproto/googleapis/iam/credentials/v1" - ctx := context.Background() c, err := credentials.NewIamCredentialsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &credentialspb.GenerateAccessTokenRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleIamCredentialsClient_GenerateAccessToken() { } func ExampleIamCredentialsClient_GenerateIdToken() { - // import credentialspb "google.golang.org/genproto/googleapis/iam/credentials/v1" - ctx := context.Background() c, err := credentials.NewIamCredentialsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &credentialspb.GenerateIdTokenRequest{ // TODO: Fill request struct fields. @@ -74,13 +74,12 @@ func ExampleIamCredentialsClient_GenerateIdToken() { } func ExampleIamCredentialsClient_SignBlob() { - // import credentialspb "google.golang.org/genproto/googleapis/iam/credentials/v1" - ctx := context.Background() c, err := credentials.NewIamCredentialsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &credentialspb.SignBlobRequest{ // TODO: Fill request struct fields. @@ -94,13 +93,12 @@ func ExampleIamCredentialsClient_SignBlob() { } func ExampleIamCredentialsClient_SignJwt() { - // import credentialspb "google.golang.org/genproto/googleapis/iam/credentials/v1" - ctx := context.Background() c, err := credentials.NewIamCredentialsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &credentialspb.SignJwtRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/accessapproval/apiv1/Client/ApproveApprovalRequest/main.go b/internal/generated/snippets/accessapproval/apiv1/Client/ApproveApprovalRequest/main.go index 700d479bc370..ed2d82ed0c39 100644 --- a/internal/generated/snippets/accessapproval/apiv1/Client/ApproveApprovalRequest/main.go +++ b/internal/generated/snippets/accessapproval/apiv1/Client/ApproveApprovalRequest/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import accessapprovalpb "google.golang.org/genproto/googleapis/cloud/accessapproval/v1" - ctx := context.Background() c, err := accessapproval.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &accessapprovalpb.ApproveApprovalRequestMessage{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/accessapproval/apiv1/Client/DeleteAccessApprovalSettings/main.go b/internal/generated/snippets/accessapproval/apiv1/Client/DeleteAccessApprovalSettings/main.go index c6a4eb2ce928..cba0cc2b79b7 100644 --- a/internal/generated/snippets/accessapproval/apiv1/Client/DeleteAccessApprovalSettings/main.go +++ b/internal/generated/snippets/accessapproval/apiv1/Client/DeleteAccessApprovalSettings/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &accessapprovalpb.DeleteAccessApprovalSettingsMessage{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/accessapproval/apiv1/Client/DismissApprovalRequest/main.go b/internal/generated/snippets/accessapproval/apiv1/Client/DismissApprovalRequest/main.go index eaf4d4fe9855..e83b728db42a 100644 --- a/internal/generated/snippets/accessapproval/apiv1/Client/DismissApprovalRequest/main.go +++ b/internal/generated/snippets/accessapproval/apiv1/Client/DismissApprovalRequest/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import accessapprovalpb "google.golang.org/genproto/googleapis/cloud/accessapproval/v1" - ctx := context.Background() c, err := accessapproval.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &accessapprovalpb.DismissApprovalRequestMessage{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/accessapproval/apiv1/Client/GetAccessApprovalSettings/main.go b/internal/generated/snippets/accessapproval/apiv1/Client/GetAccessApprovalSettings/main.go index 0c465c33541a..c12686057fb2 100644 --- a/internal/generated/snippets/accessapproval/apiv1/Client/GetAccessApprovalSettings/main.go +++ b/internal/generated/snippets/accessapproval/apiv1/Client/GetAccessApprovalSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import accessapprovalpb "google.golang.org/genproto/googleapis/cloud/accessapproval/v1" - ctx := context.Background() c, err := accessapproval.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &accessapprovalpb.GetAccessApprovalSettingsMessage{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/accessapproval/apiv1/Client/GetApprovalRequest/main.go b/internal/generated/snippets/accessapproval/apiv1/Client/GetApprovalRequest/main.go index 7837e316b7ed..e0cbe51fdc0d 100644 --- a/internal/generated/snippets/accessapproval/apiv1/Client/GetApprovalRequest/main.go +++ b/internal/generated/snippets/accessapproval/apiv1/Client/GetApprovalRequest/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import accessapprovalpb "google.golang.org/genproto/googleapis/cloud/accessapproval/v1" - ctx := context.Background() c, err := accessapproval.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &accessapprovalpb.GetApprovalRequestMessage{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/accessapproval/apiv1/Client/ListApprovalRequests/main.go b/internal/generated/snippets/accessapproval/apiv1/Client/ListApprovalRequests/main.go index 7b3804768139..86c93a1fede6 100644 --- a/internal/generated/snippets/accessapproval/apiv1/Client/ListApprovalRequests/main.go +++ b/internal/generated/snippets/accessapproval/apiv1/Client/ListApprovalRequests/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import accessapprovalpb "google.golang.org/genproto/googleapis/cloud/accessapproval/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := accessapproval.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &accessapprovalpb.ListApprovalRequestsMessage{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/accessapproval/apiv1/Client/UpdateAccessApprovalSettings/main.go b/internal/generated/snippets/accessapproval/apiv1/Client/UpdateAccessApprovalSettings/main.go index ac127432471b..4fd43ada0642 100644 --- a/internal/generated/snippets/accessapproval/apiv1/Client/UpdateAccessApprovalSettings/main.go +++ b/internal/generated/snippets/accessapproval/apiv1/Client/UpdateAccessApprovalSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import accessapprovalpb "google.golang.org/genproto/googleapis/cloud/accessapproval/v1" - ctx := context.Background() c, err := accessapproval.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &accessapprovalpb.UpdateAccessApprovalSettingsMessage{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/AuditUserLinks/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/AuditUserLinks/main.go index 0dfbb31c40a7..f9710c8ba775 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/AuditUserLinks/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/AuditUserLinks/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.AuditUserLinksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/BatchCreateUserLinks/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/BatchCreateUserLinks/main.go index 4eb88fab1a34..0e4189092c18 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/BatchCreateUserLinks/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/BatchCreateUserLinks/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.BatchCreateUserLinksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/BatchDeleteUserLinks/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/BatchDeleteUserLinks/main.go index bbedda6b63df..e524f00afa01 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/BatchDeleteUserLinks/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/BatchDeleteUserLinks/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.BatchDeleteUserLinksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/BatchGetUserLinks/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/BatchGetUserLinks/main.go index 531b2f145499..33411344808f 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/BatchGetUserLinks/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/BatchGetUserLinks/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.BatchGetUserLinksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/BatchUpdateUserLinks/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/BatchUpdateUserLinks/main.go index 17d4f416efe4..7cc03f4000cb 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/BatchUpdateUserLinks/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/BatchUpdateUserLinks/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.BatchUpdateUserLinksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateFirebaseLink/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateFirebaseLink/main.go index 4703aadb0877..c4adbcd357a7 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateFirebaseLink/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateFirebaseLink/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.CreateFirebaseLinkRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateGoogleAdsLink/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateGoogleAdsLink/main.go index e4a989b1cf9b..facb5476490f 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateGoogleAdsLink/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateGoogleAdsLink/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.CreateGoogleAdsLinkRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateProperty/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateProperty/main.go index e439775e0058..d7862e13ffdc 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateProperty/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateProperty/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.CreatePropertyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateUserLink/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateUserLink/main.go index e2ccf4683cb5..95de8299f8c2 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateUserLink/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateUserLink/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.CreateUserLinkRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateWebDataStream/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateWebDataStream/main.go index a87f951fadbe..a8877673309c 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateWebDataStream/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/CreateWebDataStream/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.CreateWebDataStreamRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteAccount/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteAccount/main.go index f8ca1a4ba524..d6c9814bedbd 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteAccount/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteAccount/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteAccountRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteAndroidAppDataStream/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteAndroidAppDataStream/main.go index c7f22dde7b44..a03f12c99e42 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteAndroidAppDataStream/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteAndroidAppDataStream/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteAndroidAppDataStreamRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteFirebaseLink/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteFirebaseLink/main.go index 366455cc92c5..f1678941fcf2 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteFirebaseLink/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteFirebaseLink/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteFirebaseLinkRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteGoogleAdsLink/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteGoogleAdsLink/main.go index 767ccb0a9f15..6acd2015e98b 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteGoogleAdsLink/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteGoogleAdsLink/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteGoogleAdsLinkRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteIosAppDataStream/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteIosAppDataStream/main.go index 0cb8fa12e6c1..fc9110eeaf36 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteIosAppDataStream/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteIosAppDataStream/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteIosAppDataStreamRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteProperty/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteProperty/main.go index 04a5bd345ad4..b49960420f9d 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteProperty/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteProperty/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeletePropertyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteUserLink/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteUserLink/main.go index abc4c0c7315f..d47d9c1509be 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteUserLink/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteUserLink/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteUserLinkRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteWebDataStream/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteWebDataStream/main.go index 56a2323d8de1..2a8489b4e5db 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteWebDataStream/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/DeleteWebDataStream/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteWebDataStreamRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetAccount/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetAccount/main.go index 18a5ade9ebf1..9212f362d141 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetAccount/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetAccount/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetAccountRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetAndroidAppDataStream/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetAndroidAppDataStream/main.go index 5fa9328c3bd1..5bb05379913b 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetAndroidAppDataStream/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetAndroidAppDataStream/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetAndroidAppDataStreamRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetDataSharingSettings/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetDataSharingSettings/main.go index e73a72cfbdff..5f6642a92b43 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetDataSharingSettings/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetDataSharingSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetDataSharingSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetEnhancedMeasurementSettings/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetEnhancedMeasurementSettings/main.go index d60b728c5898..b7c3fbe879ba 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetEnhancedMeasurementSettings/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetEnhancedMeasurementSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetEnhancedMeasurementSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetGlobalSiteTag/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetGlobalSiteTag/main.go index 24db48c0f5d2..3488e94e2f8f 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetGlobalSiteTag/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetGlobalSiteTag/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetGlobalSiteTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetIosAppDataStream/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetIosAppDataStream/main.go index f8bf20e9d19d..313307baa5b9 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetIosAppDataStream/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetIosAppDataStream/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetIosAppDataStreamRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetProperty/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetProperty/main.go index 88da2eab7ee8..960cde0e6dca 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetProperty/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetProperty/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetPropertyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetUserLink/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetUserLink/main.go index dbc52eb458c0..0416016e8158 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetUserLink/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetUserLink/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetUserLinkRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetWebDataStream/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetWebDataStream/main.go index a9b52be30fc6..bfd8121a3811 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetWebDataStream/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/GetWebDataStream/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetWebDataStreamRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListAccountSummaries/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListAccountSummaries/main.go index db691fe6f122..e77df50b9b26 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListAccountSummaries/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListAccountSummaries/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListAccountSummariesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListAccounts/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListAccounts/main.go index c3a7a6ff8a59..c93d6b022d0c 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListAccounts/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListAccounts/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListAccountsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListAndroidAppDataStreams/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListAndroidAppDataStreams/main.go index 7cfef21bd7de..f97b2bedc9a3 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListAndroidAppDataStreams/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListAndroidAppDataStreams/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListAndroidAppDataStreamsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListFirebaseLinks/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListFirebaseLinks/main.go index 12a069882dbe..0b034f49b437 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListFirebaseLinks/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListFirebaseLinks/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListFirebaseLinksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListGoogleAdsLinks/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListGoogleAdsLinks/main.go index 754ad7574def..72cc93d4ac0a 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListGoogleAdsLinks/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListGoogleAdsLinks/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListGoogleAdsLinksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListIosAppDataStreams/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListIosAppDataStreams/main.go index 1ad8b35de41c..b79bfeeb5b11 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListIosAppDataStreams/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListIosAppDataStreams/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListIosAppDataStreamsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListProperties/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListProperties/main.go index 389ef81589dc..e8b255ceee43 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListProperties/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListProperties/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListPropertiesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListUserLinks/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListUserLinks/main.go index 7213434bc47e..e7a525cfc532 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListUserLinks/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListUserLinks/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListUserLinksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListWebDataStreams/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListWebDataStreams/main.go index 9ce447b1e870..0c60c235b33f 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListWebDataStreams/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ListWebDataStreams/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListWebDataStreamsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ProvisionAccountTicket/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ProvisionAccountTicket/main.go index a8222ad81322..5574aa6cfe62 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ProvisionAccountTicket/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/ProvisionAccountTicket/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ProvisionAccountTicketRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/SearchChangeHistoryEvents/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/SearchChangeHistoryEvents/main.go index 9222a67cb62e..0705d329891f 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/SearchChangeHistoryEvents/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/SearchChangeHistoryEvents/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.SearchChangeHistoryEventsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateAccount/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateAccount/main.go index a79fe8250b35..1088a3042f2c 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateAccount/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateAccount/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateAccountRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateAndroidAppDataStream/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateAndroidAppDataStream/main.go index ce235fd862e5..7a27cd16cb56 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateAndroidAppDataStream/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateAndroidAppDataStream/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateAndroidAppDataStreamRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateEnhancedMeasurementSettings/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateEnhancedMeasurementSettings/main.go index dc0302f7a54f..fa1bf902d9f7 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateEnhancedMeasurementSettings/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateEnhancedMeasurementSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateEnhancedMeasurementSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateFirebaseLink/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateFirebaseLink/main.go index a140dabffc02..7650dd033702 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateFirebaseLink/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateFirebaseLink/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateFirebaseLinkRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateGoogleAdsLink/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateGoogleAdsLink/main.go index 3852b70978b6..2eaa738ffe58 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateGoogleAdsLink/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateGoogleAdsLink/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateGoogleAdsLinkRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateIosAppDataStream/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateIosAppDataStream/main.go index e93c55420406..e9d4317f2957 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateIosAppDataStream/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateIosAppDataStream/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateIosAppDataStreamRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateProperty/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateProperty/main.go index 81f90e50733b..1a36e93c96df 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateProperty/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateProperty/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdatePropertyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateUserLink/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateUserLink/main.go index 40d8e3cf8db8..52a88c31f362 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateUserLink/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateUserLink/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateUserLinkRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateWebDataStream/main.go b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateWebDataStream/main.go index 1690a0e82c8b..5168c25df8aa 100644 --- a/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateWebDataStream/main.go +++ b/internal/generated/snippets/analytics/admin/apiv1alpha/AnalyticsAdminClient/UpdateWebDataStream/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/analytics/admin/v1alpha" - ctx := context.Background() c, err := admin.NewAnalyticsAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateWebDataStreamRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/BatchRunPivotReports/main.go b/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/BatchRunPivotReports/main.go index 6e6064601590..6fa4bca0aaf3 100644 --- a/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/BatchRunPivotReports/main.go +++ b/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/BatchRunPivotReports/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datapb "google.golang.org/genproto/googleapis/analytics/data/v1alpha" - ctx := context.Background() c, err := data.NewAlphaAnalyticsDataClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datapb.BatchRunPivotReportsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/BatchRunReports/main.go b/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/BatchRunReports/main.go index 85ea10f21382..d8f222609460 100644 --- a/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/BatchRunReports/main.go +++ b/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/BatchRunReports/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datapb "google.golang.org/genproto/googleapis/analytics/data/v1alpha" - ctx := context.Background() c, err := data.NewAlphaAnalyticsDataClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datapb.BatchRunReportsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/GetMetadata/main.go b/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/GetMetadata/main.go index 535d44e24870..5a53e39f821f 100644 --- a/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/GetMetadata/main.go +++ b/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/GetMetadata/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datapb "google.golang.org/genproto/googleapis/analytics/data/v1alpha" - ctx := context.Background() c, err := data.NewAlphaAnalyticsDataClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datapb.GetMetadataRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/RunPivotReport/main.go b/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/RunPivotReport/main.go index 3a3d4de2a822..fc25f8f8132d 100644 --- a/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/RunPivotReport/main.go +++ b/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/RunPivotReport/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datapb "google.golang.org/genproto/googleapis/analytics/data/v1alpha" - ctx := context.Background() c, err := data.NewAlphaAnalyticsDataClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datapb.RunPivotReportRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/RunRealtimeReport/main.go b/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/RunRealtimeReport/main.go index 84bf26c2e06e..e667da9e278a 100644 --- a/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/RunRealtimeReport/main.go +++ b/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/RunRealtimeReport/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datapb "google.golang.org/genproto/googleapis/analytics/data/v1alpha" - ctx := context.Background() c, err := data.NewAlphaAnalyticsDataClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datapb.RunRealtimeReportRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/RunReport/main.go b/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/RunReport/main.go index c89540697379..9484c5b5dac6 100644 --- a/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/RunReport/main.go +++ b/internal/generated/snippets/analytics/data/apiv1alpha/AlphaAnalyticsDataClient/RunReport/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datapb "google.golang.org/genproto/googleapis/analytics/data/v1alpha" - ctx := context.Background() c, err := data.NewAlphaAnalyticsDataClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datapb.RunReportRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/apigateway/apiv1/Client/CreateApi/main.go b/internal/generated/snippets/apigateway/apiv1/Client/CreateApi/main.go index 080684469db9..a1ef75336bd4 100644 --- a/internal/generated/snippets/apigateway/apiv1/Client/CreateApi/main.go +++ b/internal/generated/snippets/apigateway/apiv1/Client/CreateApi/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.CreateApiRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/apigateway/apiv1/Client/CreateApiConfig/main.go b/internal/generated/snippets/apigateway/apiv1/Client/CreateApiConfig/main.go index 96784e11d7de..fe00b4bdcacb 100644 --- a/internal/generated/snippets/apigateway/apiv1/Client/CreateApiConfig/main.go +++ b/internal/generated/snippets/apigateway/apiv1/Client/CreateApiConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.CreateApiConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/apigateway/apiv1/Client/CreateGateway/main.go b/internal/generated/snippets/apigateway/apiv1/Client/CreateGateway/main.go index 864ea9f7a030..9d19ec5540fb 100644 --- a/internal/generated/snippets/apigateway/apiv1/Client/CreateGateway/main.go +++ b/internal/generated/snippets/apigateway/apiv1/Client/CreateGateway/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.CreateGatewayRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/apigateway/apiv1/Client/DeleteApi/main.go b/internal/generated/snippets/apigateway/apiv1/Client/DeleteApi/main.go index bcdf822c8f08..bfb1bf0628c4 100644 --- a/internal/generated/snippets/apigateway/apiv1/Client/DeleteApi/main.go +++ b/internal/generated/snippets/apigateway/apiv1/Client/DeleteApi/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.DeleteApiRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/apigateway/apiv1/Client/DeleteApiConfig/main.go b/internal/generated/snippets/apigateway/apiv1/Client/DeleteApiConfig/main.go index 3e842fd0b58a..1df1f101160a 100644 --- a/internal/generated/snippets/apigateway/apiv1/Client/DeleteApiConfig/main.go +++ b/internal/generated/snippets/apigateway/apiv1/Client/DeleteApiConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.DeleteApiConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/apigateway/apiv1/Client/DeleteGateway/main.go b/internal/generated/snippets/apigateway/apiv1/Client/DeleteGateway/main.go index 09225e7a993d..ac3d8161b614 100644 --- a/internal/generated/snippets/apigateway/apiv1/Client/DeleteGateway/main.go +++ b/internal/generated/snippets/apigateway/apiv1/Client/DeleteGateway/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.DeleteGatewayRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/apigateway/apiv1/Client/GetApi/main.go b/internal/generated/snippets/apigateway/apiv1/Client/GetApi/main.go index 50a3fce31945..c7985c3a6e60 100644 --- a/internal/generated/snippets/apigateway/apiv1/Client/GetApi/main.go +++ b/internal/generated/snippets/apigateway/apiv1/Client/GetApi/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.GetApiRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/apigateway/apiv1/Client/GetApiConfig/main.go b/internal/generated/snippets/apigateway/apiv1/Client/GetApiConfig/main.go index 7d29c98e9484..f8b2fa298fee 100644 --- a/internal/generated/snippets/apigateway/apiv1/Client/GetApiConfig/main.go +++ b/internal/generated/snippets/apigateway/apiv1/Client/GetApiConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.GetApiConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/apigateway/apiv1/Client/GetGateway/main.go b/internal/generated/snippets/apigateway/apiv1/Client/GetGateway/main.go index de30defb2f0e..860ba0633cde 100644 --- a/internal/generated/snippets/apigateway/apiv1/Client/GetGateway/main.go +++ b/internal/generated/snippets/apigateway/apiv1/Client/GetGateway/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.GetGatewayRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/apigateway/apiv1/Client/ListApiConfigs/main.go b/internal/generated/snippets/apigateway/apiv1/Client/ListApiConfigs/main.go index 217a5c2f85e6..c3d4dbaba11c 100644 --- a/internal/generated/snippets/apigateway/apiv1/Client/ListApiConfigs/main.go +++ b/internal/generated/snippets/apigateway/apiv1/Client/ListApiConfigs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.ListApiConfigsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/apigateway/apiv1/Client/ListApis/main.go b/internal/generated/snippets/apigateway/apiv1/Client/ListApis/main.go index 23de14cb9b17..79622a2aa630 100644 --- a/internal/generated/snippets/apigateway/apiv1/Client/ListApis/main.go +++ b/internal/generated/snippets/apigateway/apiv1/Client/ListApis/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.ListApisRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/apigateway/apiv1/Client/ListGateways/main.go b/internal/generated/snippets/apigateway/apiv1/Client/ListGateways/main.go index fc5ed723d76d..6f6f5cf0f5f9 100644 --- a/internal/generated/snippets/apigateway/apiv1/Client/ListGateways/main.go +++ b/internal/generated/snippets/apigateway/apiv1/Client/ListGateways/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.ListGatewaysRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/apigateway/apiv1/Client/UpdateApi/main.go b/internal/generated/snippets/apigateway/apiv1/Client/UpdateApi/main.go index 62fcd941bde4..64204ec8022d 100644 --- a/internal/generated/snippets/apigateway/apiv1/Client/UpdateApi/main.go +++ b/internal/generated/snippets/apigateway/apiv1/Client/UpdateApi/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.UpdateApiRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/apigateway/apiv1/Client/UpdateApiConfig/main.go b/internal/generated/snippets/apigateway/apiv1/Client/UpdateApiConfig/main.go index a47d5ae8acdc..571266ea3990 100644 --- a/internal/generated/snippets/apigateway/apiv1/Client/UpdateApiConfig/main.go +++ b/internal/generated/snippets/apigateway/apiv1/Client/UpdateApiConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.UpdateApiConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/apigateway/apiv1/Client/UpdateGateway/main.go b/internal/generated/snippets/apigateway/apiv1/Client/UpdateGateway/main.go index f2ba8396d44a..45390b09fd00 100644 --- a/internal/generated/snippets/apigateway/apiv1/Client/UpdateGateway/main.go +++ b/internal/generated/snippets/apigateway/apiv1/Client/UpdateGateway/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import apigatewaypb "google.golang.org/genproto/googleapis/cloud/apigateway/v1" - ctx := context.Background() c, err := apigateway.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &apigatewaypb.UpdateGatewayRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/ApplicationsClient/CreateApplication/main.go b/internal/generated/snippets/appengine/apiv1/ApplicationsClient/CreateApplication/main.go index 8160e2240f42..48185ae7f11a 100644 --- a/internal/generated/snippets/appengine/apiv1/ApplicationsClient/CreateApplication/main.go +++ b/internal/generated/snippets/appengine/apiv1/ApplicationsClient/CreateApplication/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewApplicationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.CreateApplicationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/ApplicationsClient/GetApplication/main.go b/internal/generated/snippets/appengine/apiv1/ApplicationsClient/GetApplication/main.go index f7c5c177d1d5..f317c3f00695 100644 --- a/internal/generated/snippets/appengine/apiv1/ApplicationsClient/GetApplication/main.go +++ b/internal/generated/snippets/appengine/apiv1/ApplicationsClient/GetApplication/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewApplicationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.GetApplicationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/ApplicationsClient/RepairApplication/main.go b/internal/generated/snippets/appengine/apiv1/ApplicationsClient/RepairApplication/main.go index 4e5c66305d2c..21e45c529e15 100644 --- a/internal/generated/snippets/appengine/apiv1/ApplicationsClient/RepairApplication/main.go +++ b/internal/generated/snippets/appengine/apiv1/ApplicationsClient/RepairApplication/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewApplicationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.RepairApplicationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/ApplicationsClient/UpdateApplication/main.go b/internal/generated/snippets/appengine/apiv1/ApplicationsClient/UpdateApplication/main.go index 40cea204966d..ef873c820759 100644 --- a/internal/generated/snippets/appengine/apiv1/ApplicationsClient/UpdateApplication/main.go +++ b/internal/generated/snippets/appengine/apiv1/ApplicationsClient/UpdateApplication/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewApplicationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.UpdateApplicationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/CreateAuthorizedCertificate/main.go b/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/CreateAuthorizedCertificate/main.go index c0fb4be77573..f41c2df43850 100644 --- a/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/CreateAuthorizedCertificate/main.go +++ b/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/CreateAuthorizedCertificate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewAuthorizedCertificatesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.CreateAuthorizedCertificateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/DeleteAuthorizedCertificate/main.go b/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/DeleteAuthorizedCertificate/main.go index 17a44bbc5681..984c193bee0b 100644 --- a/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/DeleteAuthorizedCertificate/main.go +++ b/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/DeleteAuthorizedCertificate/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.DeleteAuthorizedCertificateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/GetAuthorizedCertificate/main.go b/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/GetAuthorizedCertificate/main.go index 7d13cf33c4b9..d71000749118 100644 --- a/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/GetAuthorizedCertificate/main.go +++ b/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/GetAuthorizedCertificate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewAuthorizedCertificatesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.GetAuthorizedCertificateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/ListAuthorizedCertificates/main.go b/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/ListAuthorizedCertificates/main.go index 56427b5a6759..1eaa19fa4582 100644 --- a/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/ListAuthorizedCertificates/main.go +++ b/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/ListAuthorizedCertificates/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := appengine.NewAuthorizedCertificatesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.ListAuthorizedCertificatesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/UpdateAuthorizedCertificate/main.go b/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/UpdateAuthorizedCertificate/main.go index dc641a5eed82..5ca93c590075 100644 --- a/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/UpdateAuthorizedCertificate/main.go +++ b/internal/generated/snippets/appengine/apiv1/AuthorizedCertificatesClient/UpdateAuthorizedCertificate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewAuthorizedCertificatesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.UpdateAuthorizedCertificateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/AuthorizedDomainsClient/ListAuthorizedDomains/main.go b/internal/generated/snippets/appengine/apiv1/AuthorizedDomainsClient/ListAuthorizedDomains/main.go index c6e1f8253a8d..27d0feaf3d2c 100644 --- a/internal/generated/snippets/appengine/apiv1/AuthorizedDomainsClient/ListAuthorizedDomains/main.go +++ b/internal/generated/snippets/appengine/apiv1/AuthorizedDomainsClient/ListAuthorizedDomains/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := appengine.NewAuthorizedDomainsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.ListAuthorizedDomainsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/CreateDomainMapping/main.go b/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/CreateDomainMapping/main.go index 101dce45b2f8..183984743c8f 100644 --- a/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/CreateDomainMapping/main.go +++ b/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/CreateDomainMapping/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewDomainMappingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.CreateDomainMappingRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/DeleteDomainMapping/main.go b/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/DeleteDomainMapping/main.go index 74d7d7b4f0f4..d2e13638f644 100644 --- a/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/DeleteDomainMapping/main.go +++ b/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/DeleteDomainMapping/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewDomainMappingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.DeleteDomainMappingRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/GetDomainMapping/main.go b/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/GetDomainMapping/main.go index ab0156fa9e1a..2cb8708862fc 100644 --- a/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/GetDomainMapping/main.go +++ b/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/GetDomainMapping/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewDomainMappingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.GetDomainMappingRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/ListDomainMappings/main.go b/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/ListDomainMappings/main.go index 85d7ffec7a4f..fc6b63226341 100644 --- a/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/ListDomainMappings/main.go +++ b/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/ListDomainMappings/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := appengine.NewDomainMappingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.ListDomainMappingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/UpdateDomainMapping/main.go b/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/UpdateDomainMapping/main.go index 5a645f9ab0ad..d4bfb83b6269 100644 --- a/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/UpdateDomainMapping/main.go +++ b/internal/generated/snippets/appengine/apiv1/DomainMappingsClient/UpdateDomainMapping/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewDomainMappingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.UpdateDomainMappingRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/FirewallClient/BatchUpdateIngressRules/main.go b/internal/generated/snippets/appengine/apiv1/FirewallClient/BatchUpdateIngressRules/main.go index fcef3ff65ccc..682361f167c2 100644 --- a/internal/generated/snippets/appengine/apiv1/FirewallClient/BatchUpdateIngressRules/main.go +++ b/internal/generated/snippets/appengine/apiv1/FirewallClient/BatchUpdateIngressRules/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewFirewallClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.BatchUpdateIngressRulesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/FirewallClient/CreateIngressRule/main.go b/internal/generated/snippets/appengine/apiv1/FirewallClient/CreateIngressRule/main.go index 7f0e6bd1b75e..97334e1ddd2e 100644 --- a/internal/generated/snippets/appengine/apiv1/FirewallClient/CreateIngressRule/main.go +++ b/internal/generated/snippets/appengine/apiv1/FirewallClient/CreateIngressRule/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewFirewallClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.CreateIngressRuleRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/FirewallClient/DeleteIngressRule/main.go b/internal/generated/snippets/appengine/apiv1/FirewallClient/DeleteIngressRule/main.go index acf11621a352..4523f49184b9 100644 --- a/internal/generated/snippets/appengine/apiv1/FirewallClient/DeleteIngressRule/main.go +++ b/internal/generated/snippets/appengine/apiv1/FirewallClient/DeleteIngressRule/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.DeleteIngressRuleRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/FirewallClient/GetIngressRule/main.go b/internal/generated/snippets/appengine/apiv1/FirewallClient/GetIngressRule/main.go index 8bb987a2f71e..0d4cd3dabea1 100644 --- a/internal/generated/snippets/appengine/apiv1/FirewallClient/GetIngressRule/main.go +++ b/internal/generated/snippets/appengine/apiv1/FirewallClient/GetIngressRule/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewFirewallClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.GetIngressRuleRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/FirewallClient/ListIngressRules/main.go b/internal/generated/snippets/appengine/apiv1/FirewallClient/ListIngressRules/main.go index d1010773111a..7b8ba485fe39 100644 --- a/internal/generated/snippets/appengine/apiv1/FirewallClient/ListIngressRules/main.go +++ b/internal/generated/snippets/appengine/apiv1/FirewallClient/ListIngressRules/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := appengine.NewFirewallClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.ListIngressRulesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/FirewallClient/UpdateIngressRule/main.go b/internal/generated/snippets/appengine/apiv1/FirewallClient/UpdateIngressRule/main.go index f1e08d8f37a9..40d6ed372ed9 100644 --- a/internal/generated/snippets/appengine/apiv1/FirewallClient/UpdateIngressRule/main.go +++ b/internal/generated/snippets/appengine/apiv1/FirewallClient/UpdateIngressRule/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewFirewallClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.UpdateIngressRuleRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/InstancesClient/DebugInstance/main.go b/internal/generated/snippets/appengine/apiv1/InstancesClient/DebugInstance/main.go index d96a2f2d200a..61a961a18eef 100644 --- a/internal/generated/snippets/appengine/apiv1/InstancesClient/DebugInstance/main.go +++ b/internal/generated/snippets/appengine/apiv1/InstancesClient/DebugInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewInstancesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.DebugInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/InstancesClient/DeleteInstance/main.go b/internal/generated/snippets/appengine/apiv1/InstancesClient/DeleteInstance/main.go index 1384152b406f..c505e6eafeb3 100644 --- a/internal/generated/snippets/appengine/apiv1/InstancesClient/DeleteInstance/main.go +++ b/internal/generated/snippets/appengine/apiv1/InstancesClient/DeleteInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewInstancesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.DeleteInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/InstancesClient/GetInstance/main.go b/internal/generated/snippets/appengine/apiv1/InstancesClient/GetInstance/main.go index 789c30b81df2..0da8b84289d3 100644 --- a/internal/generated/snippets/appengine/apiv1/InstancesClient/GetInstance/main.go +++ b/internal/generated/snippets/appengine/apiv1/InstancesClient/GetInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewInstancesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.GetInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/InstancesClient/ListInstances/main.go b/internal/generated/snippets/appengine/apiv1/InstancesClient/ListInstances/main.go index 564af05b91ce..418ff9183154 100644 --- a/internal/generated/snippets/appengine/apiv1/InstancesClient/ListInstances/main.go +++ b/internal/generated/snippets/appengine/apiv1/InstancesClient/ListInstances/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := appengine.NewInstancesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.ListInstancesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/ServicesClient/DeleteService/main.go b/internal/generated/snippets/appengine/apiv1/ServicesClient/DeleteService/main.go index cb25fffb6dfc..9856b133d296 100644 --- a/internal/generated/snippets/appengine/apiv1/ServicesClient/DeleteService/main.go +++ b/internal/generated/snippets/appengine/apiv1/ServicesClient/DeleteService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewServicesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.DeleteServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/ServicesClient/GetService/main.go b/internal/generated/snippets/appengine/apiv1/ServicesClient/GetService/main.go index 8aab7bc54074..62e8da9d5dda 100644 --- a/internal/generated/snippets/appengine/apiv1/ServicesClient/GetService/main.go +++ b/internal/generated/snippets/appengine/apiv1/ServicesClient/GetService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewServicesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.GetServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/ServicesClient/ListServices/main.go b/internal/generated/snippets/appengine/apiv1/ServicesClient/ListServices/main.go index 4a97a61ad4b1..216318b14528 100644 --- a/internal/generated/snippets/appengine/apiv1/ServicesClient/ListServices/main.go +++ b/internal/generated/snippets/appengine/apiv1/ServicesClient/ListServices/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := appengine.NewServicesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.ListServicesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/ServicesClient/UpdateService/main.go b/internal/generated/snippets/appengine/apiv1/ServicesClient/UpdateService/main.go index 9f60ffef2739..24c2b261a961 100644 --- a/internal/generated/snippets/appengine/apiv1/ServicesClient/UpdateService/main.go +++ b/internal/generated/snippets/appengine/apiv1/ServicesClient/UpdateService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewServicesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.UpdateServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/VersionsClient/CreateVersion/main.go b/internal/generated/snippets/appengine/apiv1/VersionsClient/CreateVersion/main.go index dcc4759010bc..5201f72a6391 100644 --- a/internal/generated/snippets/appengine/apiv1/VersionsClient/CreateVersion/main.go +++ b/internal/generated/snippets/appengine/apiv1/VersionsClient/CreateVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.CreateVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/VersionsClient/DeleteVersion/main.go b/internal/generated/snippets/appengine/apiv1/VersionsClient/DeleteVersion/main.go index d1eb55a24a28..5ba85c5a9f6f 100644 --- a/internal/generated/snippets/appengine/apiv1/VersionsClient/DeleteVersion/main.go +++ b/internal/generated/snippets/appengine/apiv1/VersionsClient/DeleteVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.DeleteVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/VersionsClient/GetVersion/main.go b/internal/generated/snippets/appengine/apiv1/VersionsClient/GetVersion/main.go index f9564703133c..cecc1209e9a7 100644 --- a/internal/generated/snippets/appengine/apiv1/VersionsClient/GetVersion/main.go +++ b/internal/generated/snippets/appengine/apiv1/VersionsClient/GetVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.GetVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/VersionsClient/ListVersions/main.go b/internal/generated/snippets/appengine/apiv1/VersionsClient/ListVersions/main.go index 7240821b0b43..48774f3c05f5 100644 --- a/internal/generated/snippets/appengine/apiv1/VersionsClient/ListVersions/main.go +++ b/internal/generated/snippets/appengine/apiv1/VersionsClient/ListVersions/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := appengine.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.ListVersionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/appengine/apiv1/VersionsClient/UpdateVersion/main.go b/internal/generated/snippets/appengine/apiv1/VersionsClient/UpdateVersion/main.go index b3bfd97bde80..5669a21aabf7 100644 --- a/internal/generated/snippets/appengine/apiv1/VersionsClient/UpdateVersion/main.go +++ b/internal/generated/snippets/appengine/apiv1/VersionsClient/UpdateVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import appenginepb "google.golang.org/genproto/googleapis/appengine/v1" - ctx := context.Background() c, err := appengine.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &appenginepb.UpdateVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/BatchCreateRows/main.go b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/BatchCreateRows/main.go index abfab3b85af9..b209d4ef8df3 100644 --- a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/BatchCreateRows/main.go +++ b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/BatchCreateRows/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.BatchCreateRowsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/BatchDeleteRows/main.go b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/BatchDeleteRows/main.go index 03b8622ebe60..43ff74f76e75 100644 --- a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/BatchDeleteRows/main.go +++ b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/BatchDeleteRows/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.BatchDeleteRowsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/BatchUpdateRows/main.go b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/BatchUpdateRows/main.go index 70c6a7e72e91..996b406db673 100644 --- a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/BatchUpdateRows/main.go +++ b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/BatchUpdateRows/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.BatchUpdateRowsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/CreateRow/main.go b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/CreateRow/main.go index e0652dcb5d13..cfb6145df0c6 100644 --- a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/CreateRow/main.go +++ b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/CreateRow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.CreateRowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/DeleteRow/main.go b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/DeleteRow/main.go index 23a4bf956c1e..400eef2ccb43 100644 --- a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/DeleteRow/main.go +++ b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/DeleteRow/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.DeleteRowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/GetRow/main.go b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/GetRow/main.go index 92eb875c5b2d..683ca2fc95c9 100644 --- a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/GetRow/main.go +++ b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/GetRow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.GetRowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/GetTable/main.go b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/GetTable/main.go index f2a2e26c50f6..67f759b1019d 100644 --- a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/GetTable/main.go +++ b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/GetTable/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.GetTableRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/GetWorkspace/main.go b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/GetWorkspace/main.go index cdfa0d495548..a49b87d22ae2 100644 --- a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/GetWorkspace/main.go +++ b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/GetWorkspace/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.GetWorkspaceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/ListRows/main.go b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/ListRows/main.go index d8f76834914e..4460650be69a 100644 --- a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/ListRows/main.go +++ b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/ListRows/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.ListRowsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/ListTables/main.go b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/ListTables/main.go index 45e24f0ff146..ff0eb34ff816 100644 --- a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/ListTables/main.go +++ b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/ListTables/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.ListTablesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/ListWorkspaces/main.go b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/ListWorkspaces/main.go index 68a974f722fd..49385882df70 100644 --- a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/ListWorkspaces/main.go +++ b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/ListWorkspaces/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.ListWorkspacesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/UpdateRow/main.go b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/UpdateRow/main.go index f543aced256e..15951120685b 100644 --- a/internal/generated/snippets/area120/tables/apiv1alpha1/Client/UpdateRow/main.go +++ b/internal/generated/snippets/area120/tables/apiv1alpha1/Client/UpdateRow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import tablespb "google.golang.org/genproto/googleapis/area120/tables/v1alpha1" - ctx := context.Background() c, err := tables.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &tablespb.UpdateRowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/CreateRepository/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/CreateRepository/main.go index 64a8c67631ca..c7e06dd7a889 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/CreateRepository/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/CreateRepository/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.CreateRepositoryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/CreateTag/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/CreateTag/main.go index b84738f18df2..a6308b811c5f 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/CreateTag/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/CreateTag/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.CreateTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/DeletePackage/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/DeletePackage/main.go index da31ea8b0c46..5442cf93ec1a 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/DeletePackage/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/DeletePackage/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.DeletePackageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/DeleteRepository/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/DeleteRepository/main.go index 621a207f02e5..892d6c37e73b 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/DeleteRepository/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/DeleteRepository/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.DeleteRepositoryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/DeleteTag/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/DeleteTag/main.go index 09bb1c3daced..0a8f0ff9381a 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/DeleteTag/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/DeleteTag/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.DeleteTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/DeleteVersion/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/DeleteVersion/main.go index 713e97186aa7..5fde85703394 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/DeleteVersion/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/DeleteVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.DeleteVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetFile/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetFile/main.go index ec4ed52d1365..818f6e6db314 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetFile/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetFile/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.GetFileRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetIamPolicy/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetIamPolicy/main.go index 27acdd9aa38e..0ad02cd34118 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetIamPolicy/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetPackage/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetPackage/main.go index 8951a8b00dda..cfdb0575cbad 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetPackage/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetPackage/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.GetPackageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetRepository/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetRepository/main.go index c49f70666336..180d240e76b0 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetRepository/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetRepository/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.GetRepositoryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetTag/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetTag/main.go index 7ddeb06fb3c2..b6c113a4c76a 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetTag/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetTag/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.GetTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetVersion/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetVersion/main.go index d85f6ed782d8..df93e164e3d6 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetVersion/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/GetVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.GetVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListFiles/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListFiles/main.go index 6ef020909f38..8bdfb7c8e35c 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListFiles/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListFiles/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.ListFilesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListPackages/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListPackages/main.go index dd826dcd9b7b..385484d057b1 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListPackages/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListPackages/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.ListPackagesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListRepositories/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListRepositories/main.go index a0dca71c6b98..5b2e8f39843a 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListRepositories/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListRepositories/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.ListRepositoriesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListTags/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListTags/main.go index 0ae334b56b7b..67f0d6051567 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListTags/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListTags/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.ListTagsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListVersions/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListVersions/main.go index 309d5e9eadcb..7d9a8d7ff044 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListVersions/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/ListVersions/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.ListVersionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/SetIamPolicy/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/SetIamPolicy/main.go index b2f01105fa5f..b3076eb87ec3 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/SetIamPolicy/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/TestIamPermissions/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/TestIamPermissions/main.go index 9110afa0969b..4499b2dc0e50 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/TestIamPermissions/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/UpdateRepository/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/UpdateRepository/main.go index 3a0acb37dd4c..01deae18bfd3 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/UpdateRepository/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/UpdateRepository/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.UpdateRepositoryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/UpdateTag/main.go b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/UpdateTag/main.go index 0c6b1953bdbe..ae285cf2ea28 100644 --- a/internal/generated/snippets/artifactregistry/apiv1beta2/Client/UpdateTag/main.go +++ b/internal/generated/snippets/artifactregistry/apiv1beta2/Client/UpdateTag/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import artifactregistrypb "google.golang.org/genproto/googleapis/devtools/artifactregistry/v1beta2" - ctx := context.Background() c, err := artifactregistry.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &artifactregistrypb.UpdateTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/asset/apiv1/Client/AnalyzeIamPolicy/main.go b/internal/generated/snippets/asset/apiv1/Client/AnalyzeIamPolicy/main.go index f6a2caaa1643..cfc15a9c4d56 100644 --- a/internal/generated/snippets/asset/apiv1/Client/AnalyzeIamPolicy/main.go +++ b/internal/generated/snippets/asset/apiv1/Client/AnalyzeIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.AnalyzeIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/asset/apiv1/Client/AnalyzeIamPolicyLongrunning/main.go b/internal/generated/snippets/asset/apiv1/Client/AnalyzeIamPolicyLongrunning/main.go index 9d5868c88a7d..ce256cfec2ea 100644 --- a/internal/generated/snippets/asset/apiv1/Client/AnalyzeIamPolicyLongrunning/main.go +++ b/internal/generated/snippets/asset/apiv1/Client/AnalyzeIamPolicyLongrunning/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.AnalyzeIamPolicyLongrunningRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/asset/apiv1/Client/BatchGetAssetsHistory/main.go b/internal/generated/snippets/asset/apiv1/Client/BatchGetAssetsHistory/main.go index cfd80a2e10e8..b674acc36e5e 100644 --- a/internal/generated/snippets/asset/apiv1/Client/BatchGetAssetsHistory/main.go +++ b/internal/generated/snippets/asset/apiv1/Client/BatchGetAssetsHistory/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.BatchGetAssetsHistoryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/asset/apiv1/Client/CreateFeed/main.go b/internal/generated/snippets/asset/apiv1/Client/CreateFeed/main.go index 69d19093a62c..05a8881c48ab 100644 --- a/internal/generated/snippets/asset/apiv1/Client/CreateFeed/main.go +++ b/internal/generated/snippets/asset/apiv1/Client/CreateFeed/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.CreateFeedRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/asset/apiv1/Client/DeleteFeed/main.go b/internal/generated/snippets/asset/apiv1/Client/DeleteFeed/main.go index f93f72c5175f..5ff176f70765 100644 --- a/internal/generated/snippets/asset/apiv1/Client/DeleteFeed/main.go +++ b/internal/generated/snippets/asset/apiv1/Client/DeleteFeed/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.DeleteFeedRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/asset/apiv1/Client/ExportAssets/main.go b/internal/generated/snippets/asset/apiv1/Client/ExportAssets/main.go index 66ac2cda9df3..e142aa28e003 100644 --- a/internal/generated/snippets/asset/apiv1/Client/ExportAssets/main.go +++ b/internal/generated/snippets/asset/apiv1/Client/ExportAssets/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.ExportAssetsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/asset/apiv1/Client/GetFeed/main.go b/internal/generated/snippets/asset/apiv1/Client/GetFeed/main.go index fcc299bbcc9d..7cd49f646916 100644 --- a/internal/generated/snippets/asset/apiv1/Client/GetFeed/main.go +++ b/internal/generated/snippets/asset/apiv1/Client/GetFeed/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.GetFeedRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/asset/apiv1/Client/ListFeeds/main.go b/internal/generated/snippets/asset/apiv1/Client/ListFeeds/main.go index 6b7d959d54ac..7f30f6d8dd87 100644 --- a/internal/generated/snippets/asset/apiv1/Client/ListFeeds/main.go +++ b/internal/generated/snippets/asset/apiv1/Client/ListFeeds/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.ListFeedsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/asset/apiv1/Client/SearchAllIamPolicies/main.go b/internal/generated/snippets/asset/apiv1/Client/SearchAllIamPolicies/main.go index b4c57a5d773c..57c1f2f49e80 100644 --- a/internal/generated/snippets/asset/apiv1/Client/SearchAllIamPolicies/main.go +++ b/internal/generated/snippets/asset/apiv1/Client/SearchAllIamPolicies/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.SearchAllIamPoliciesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/asset/apiv1/Client/SearchAllResources/main.go b/internal/generated/snippets/asset/apiv1/Client/SearchAllResources/main.go index 22392285b697..c0f2af3a1ebc 100644 --- a/internal/generated/snippets/asset/apiv1/Client/SearchAllResources/main.go +++ b/internal/generated/snippets/asset/apiv1/Client/SearchAllResources/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.SearchAllResourcesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/asset/apiv1/Client/UpdateFeed/main.go b/internal/generated/snippets/asset/apiv1/Client/UpdateFeed/main.go index 869c02aafd17..073f66581e37 100644 --- a/internal/generated/snippets/asset/apiv1/Client/UpdateFeed/main.go +++ b/internal/generated/snippets/asset/apiv1/Client/UpdateFeed/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.UpdateFeedRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/asset/apiv1p2beta1/Client/CreateFeed/main.go b/internal/generated/snippets/asset/apiv1p2beta1/Client/CreateFeed/main.go index b6a504f483c2..3a5b0f993d2a 100644 --- a/internal/generated/snippets/asset/apiv1p2beta1/Client/CreateFeed/main.go +++ b/internal/generated/snippets/asset/apiv1p2beta1/Client/CreateFeed/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1p2beta1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.CreateFeedRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/asset/apiv1p2beta1/Client/DeleteFeed/main.go b/internal/generated/snippets/asset/apiv1p2beta1/Client/DeleteFeed/main.go index 04d14e162797..4378dcc72e43 100644 --- a/internal/generated/snippets/asset/apiv1p2beta1/Client/DeleteFeed/main.go +++ b/internal/generated/snippets/asset/apiv1p2beta1/Client/DeleteFeed/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.DeleteFeedRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/asset/apiv1p2beta1/Client/GetFeed/main.go b/internal/generated/snippets/asset/apiv1p2beta1/Client/GetFeed/main.go index 1a22853fbd94..7df5b31b799f 100644 --- a/internal/generated/snippets/asset/apiv1p2beta1/Client/GetFeed/main.go +++ b/internal/generated/snippets/asset/apiv1p2beta1/Client/GetFeed/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1p2beta1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.GetFeedRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/asset/apiv1p2beta1/Client/ListFeeds/main.go b/internal/generated/snippets/asset/apiv1p2beta1/Client/ListFeeds/main.go index d33428ba5fb3..66c9ee07cfe5 100644 --- a/internal/generated/snippets/asset/apiv1p2beta1/Client/ListFeeds/main.go +++ b/internal/generated/snippets/asset/apiv1p2beta1/Client/ListFeeds/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1p2beta1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.ListFeedsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/asset/apiv1p2beta1/Client/UpdateFeed/main.go b/internal/generated/snippets/asset/apiv1p2beta1/Client/UpdateFeed/main.go index 281b749c23e0..c1b563cc9930 100644 --- a/internal/generated/snippets/asset/apiv1p2beta1/Client/UpdateFeed/main.go +++ b/internal/generated/snippets/asset/apiv1p2beta1/Client/UpdateFeed/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1p2beta1" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.UpdateFeedRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/asset/apiv1p5beta1/Client/ListAssets/main.go b/internal/generated/snippets/asset/apiv1p5beta1/Client/ListAssets/main.go index 181e68b7af23..0779aff46f10 100644 --- a/internal/generated/snippets/asset/apiv1p5beta1/Client/ListAssets/main.go +++ b/internal/generated/snippets/asset/apiv1p5beta1/Client/ListAssets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1p5beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := asset.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assetpb.ListAssetsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/CreateWorkload/main.go b/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/CreateWorkload/main.go index b31f90054a5e..4e6824251139 100644 --- a/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/CreateWorkload/main.go +++ b/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/CreateWorkload/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import assuredworkloadspb "google.golang.org/genproto/googleapis/cloud/assuredworkloads/v1beta1" - ctx := context.Background() c, err := assuredworkloads.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assuredworkloadspb.CreateWorkloadRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/DeleteWorkload/main.go b/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/DeleteWorkload/main.go index 37b9280f3866..448add490ef7 100644 --- a/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/DeleteWorkload/main.go +++ b/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/DeleteWorkload/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &assuredworkloadspb.DeleteWorkloadRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/GetWorkload/main.go b/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/GetWorkload/main.go index f059f210d444..0498e51e711f 100644 --- a/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/GetWorkload/main.go +++ b/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/GetWorkload/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import assuredworkloadspb "google.golang.org/genproto/googleapis/cloud/assuredworkloads/v1beta1" - ctx := context.Background() c, err := assuredworkloads.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assuredworkloadspb.GetWorkloadRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/ListWorkloads/main.go b/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/ListWorkloads/main.go index c575454e54cb..e0f97444334d 100644 --- a/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/ListWorkloads/main.go +++ b/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/ListWorkloads/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import assuredworkloadspb "google.golang.org/genproto/googleapis/cloud/assuredworkloads/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := assuredworkloads.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assuredworkloadspb.ListWorkloadsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/UpdateWorkload/main.go b/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/UpdateWorkload/main.go index b56ed034326d..5a9573eca61f 100644 --- a/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/UpdateWorkload/main.go +++ b/internal/generated/snippets/assuredworkloads/apiv1beta1/Client/UpdateWorkload/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import assuredworkloadspb "google.golang.org/genproto/googleapis/cloud/assuredworkloads/v1beta1" - ctx := context.Background() c, err := assuredworkloads.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &assuredworkloadspb.UpdateWorkloadRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/CreateDataset/main.go b/internal/generated/snippets/automl/apiv1/Client/CreateDataset/main.go index f09ffa3bcfb2..73b790feeb9c 100644 --- a/internal/generated/snippets/automl/apiv1/Client/CreateDataset/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/CreateDataset/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.CreateDatasetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/CreateModel/main.go b/internal/generated/snippets/automl/apiv1/Client/CreateModel/main.go index e1b0b60e7a29..cf168bfa249f 100644 --- a/internal/generated/snippets/automl/apiv1/Client/CreateModel/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/CreateModel/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.CreateModelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/DeleteDataset/main.go b/internal/generated/snippets/automl/apiv1/Client/DeleteDataset/main.go index cc0e5fe22f10..8e573e0a3599 100644 --- a/internal/generated/snippets/automl/apiv1/Client/DeleteDataset/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/DeleteDataset/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.DeleteDatasetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/DeleteModel/main.go b/internal/generated/snippets/automl/apiv1/Client/DeleteModel/main.go index 83bf2817df9f..b664aa63c450 100644 --- a/internal/generated/snippets/automl/apiv1/Client/DeleteModel/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/DeleteModel/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.DeleteModelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/DeployModel/main.go b/internal/generated/snippets/automl/apiv1/Client/DeployModel/main.go index 65d57339be7e..42695da4926f 100644 --- a/internal/generated/snippets/automl/apiv1/Client/DeployModel/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/DeployModel/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.DeployModelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/ExportData/main.go b/internal/generated/snippets/automl/apiv1/Client/ExportData/main.go index c779d8157b60..dfbb2c6f02c1 100644 --- a/internal/generated/snippets/automl/apiv1/Client/ExportData/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/ExportData/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ExportDataRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/ExportModel/main.go b/internal/generated/snippets/automl/apiv1/Client/ExportModel/main.go index 38c6fe86b773..6ad953730ee1 100644 --- a/internal/generated/snippets/automl/apiv1/Client/ExportModel/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/ExportModel/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ExportModelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/GetAnnotationSpec/main.go b/internal/generated/snippets/automl/apiv1/Client/GetAnnotationSpec/main.go index e30a58845610..c804f115aef7 100644 --- a/internal/generated/snippets/automl/apiv1/Client/GetAnnotationSpec/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/GetAnnotationSpec/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetAnnotationSpecRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/GetDataset/main.go b/internal/generated/snippets/automl/apiv1/Client/GetDataset/main.go index 44ad32fa35b2..481ba683f5c0 100644 --- a/internal/generated/snippets/automl/apiv1/Client/GetDataset/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/GetDataset/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetDatasetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/GetModel/main.go b/internal/generated/snippets/automl/apiv1/Client/GetModel/main.go index 7e595086f08c..433df6c1714f 100644 --- a/internal/generated/snippets/automl/apiv1/Client/GetModel/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/GetModel/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetModelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/GetModelEvaluation/main.go b/internal/generated/snippets/automl/apiv1/Client/GetModelEvaluation/main.go index 252e287dd374..39a3dffab5b5 100644 --- a/internal/generated/snippets/automl/apiv1/Client/GetModelEvaluation/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/GetModelEvaluation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetModelEvaluationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/ImportData/main.go b/internal/generated/snippets/automl/apiv1/Client/ImportData/main.go index d7f4a7d0157f..b5170447786d 100644 --- a/internal/generated/snippets/automl/apiv1/Client/ImportData/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/ImportData/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ImportDataRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/ListDatasets/main.go b/internal/generated/snippets/automl/apiv1/Client/ListDatasets/main.go index 43f4b0b74368..73c39ca21f3f 100644 --- a/internal/generated/snippets/automl/apiv1/Client/ListDatasets/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/ListDatasets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ListDatasetsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/ListModelEvaluations/main.go b/internal/generated/snippets/automl/apiv1/Client/ListModelEvaluations/main.go index c4ea216f97c6..b27b7277ecb6 100644 --- a/internal/generated/snippets/automl/apiv1/Client/ListModelEvaluations/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/ListModelEvaluations/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ListModelEvaluationsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/ListModels/main.go b/internal/generated/snippets/automl/apiv1/Client/ListModels/main.go index 142a744da0d7..933ae303a9c5 100644 --- a/internal/generated/snippets/automl/apiv1/Client/ListModels/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/ListModels/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ListModelsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/UndeployModel/main.go b/internal/generated/snippets/automl/apiv1/Client/UndeployModel/main.go index f5410aed46f7..db646ea60079 100644 --- a/internal/generated/snippets/automl/apiv1/Client/UndeployModel/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/UndeployModel/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.UndeployModelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/UpdateDataset/main.go b/internal/generated/snippets/automl/apiv1/Client/UpdateDataset/main.go index 39ff4ee4dd82..8a078d19a0f8 100644 --- a/internal/generated/snippets/automl/apiv1/Client/UpdateDataset/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/UpdateDataset/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.UpdateDatasetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/Client/UpdateModel/main.go b/internal/generated/snippets/automl/apiv1/Client/UpdateModel/main.go index 8fd95806f419..9f04b9a75d2a 100644 --- a/internal/generated/snippets/automl/apiv1/Client/UpdateModel/main.go +++ b/internal/generated/snippets/automl/apiv1/Client/UpdateModel/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.UpdateModelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/PredictionClient/BatchPredict/main.go b/internal/generated/snippets/automl/apiv1/PredictionClient/BatchPredict/main.go index 06851d128038..8d760c8306fa 100644 --- a/internal/generated/snippets/automl/apiv1/PredictionClient/BatchPredict/main.go +++ b/internal/generated/snippets/automl/apiv1/PredictionClient/BatchPredict/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewPredictionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.BatchPredictRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1/PredictionClient/Predict/main.go b/internal/generated/snippets/automl/apiv1/PredictionClient/Predict/main.go index 77cb3c60d70a..7e9d485efc7e 100644 --- a/internal/generated/snippets/automl/apiv1/PredictionClient/Predict/main.go +++ b/internal/generated/snippets/automl/apiv1/PredictionClient/Predict/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1" - ctx := context.Background() c, err := automl.NewPredictionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.PredictRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/CreateDataset/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/CreateDataset/main.go index 43245c40c085..52d13bab21c6 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/CreateDataset/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/CreateDataset/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.CreateDatasetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/CreateModel/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/CreateModel/main.go index 2a228ba936f3..2d850692fc88 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/CreateModel/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/CreateModel/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.CreateModelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/DeleteDataset/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/DeleteDataset/main.go index 2ddaef2c04d6..4a55daf29986 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/DeleteDataset/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/DeleteDataset/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.DeleteDatasetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/DeleteModel/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/DeleteModel/main.go index 882a22c113da..8328cd272e6a 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/DeleteModel/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/DeleteModel/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.DeleteModelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/DeployModel/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/DeployModel/main.go index 5656a8ac01e6..5ce030a5949b 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/DeployModel/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/DeployModel/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.DeployModelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/ExportData/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/ExportData/main.go index f36bbc9a4d35..9c63c415101d 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/ExportData/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/ExportData/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ExportDataRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/ExportEvaluatedExamples/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/ExportEvaluatedExamples/main.go index adabc7c4c269..71945c5a66e6 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/ExportEvaluatedExamples/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/ExportEvaluatedExamples/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ExportEvaluatedExamplesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/ExportModel/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/ExportModel/main.go index 44ec29c94ff4..f717abd4963d 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/ExportModel/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/ExportModel/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ExportModelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/GetAnnotationSpec/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/GetAnnotationSpec/main.go index 652cf588e30b..a5e1525e4cb9 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/GetAnnotationSpec/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/GetAnnotationSpec/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetAnnotationSpecRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/GetColumnSpec/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/GetColumnSpec/main.go index 6cca054b1a61..2e88e782401b 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/GetColumnSpec/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/GetColumnSpec/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetColumnSpecRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/GetDataset/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/GetDataset/main.go index e011cbb755b3..b3d12a4d92eb 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/GetDataset/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/GetDataset/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetDatasetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/GetModel/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/GetModel/main.go index a52311ee0651..2dc2871becf0 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/GetModel/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/GetModel/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetModelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/GetModelEvaluation/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/GetModelEvaluation/main.go index 847dd359410a..157f2db770c0 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/GetModelEvaluation/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/GetModelEvaluation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetModelEvaluationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/GetTableSpec/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/GetTableSpec/main.go index 18f6fb615cce..cb97f56a2a23 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/GetTableSpec/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/GetTableSpec/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.GetTableSpecRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/ImportData/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/ImportData/main.go index ca44622e3a1e..519853867030 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/ImportData/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/ImportData/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ImportDataRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/ListColumnSpecs/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/ListColumnSpecs/main.go index 0bd4cceb6d25..6e4b63f7dfd8 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/ListColumnSpecs/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/ListColumnSpecs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ListColumnSpecsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/ListDatasets/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/ListDatasets/main.go index 1182ae501828..a43660064044 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/ListDatasets/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/ListDatasets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ListDatasetsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/ListModelEvaluations/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/ListModelEvaluations/main.go index ab3800875755..5cd912f374ec 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/ListModelEvaluations/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/ListModelEvaluations/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ListModelEvaluationsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/ListModels/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/ListModels/main.go index e278ec5fbc8a..5efc9de665cd 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/ListModels/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/ListModels/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ListModelsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/ListTableSpecs/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/ListTableSpecs/main.go index e411c4b5b50c..9e1370c375db 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/ListTableSpecs/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/ListTableSpecs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.ListTableSpecsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/UndeployModel/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/UndeployModel/main.go index 6b05a2de234f..5494495a18ad 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/UndeployModel/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/UndeployModel/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.UndeployModelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/UpdateColumnSpec/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/UpdateColumnSpec/main.go index 23b3d58d5ef5..db7c33dc042f 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/UpdateColumnSpec/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/UpdateColumnSpec/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.UpdateColumnSpecRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/UpdateDataset/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/UpdateDataset/main.go index cd16a2fd86ba..48c92b3b8099 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/UpdateDataset/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/UpdateDataset/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.UpdateDatasetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/Client/UpdateTableSpec/main.go b/internal/generated/snippets/automl/apiv1beta1/Client/UpdateTableSpec/main.go index 0720723469b0..e6349bd431ce 100644 --- a/internal/generated/snippets/automl/apiv1beta1/Client/UpdateTableSpec/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/Client/UpdateTableSpec/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.UpdateTableSpecRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/PredictionClient/BatchPredict/main.go b/internal/generated/snippets/automl/apiv1beta1/PredictionClient/BatchPredict/main.go index cc1eb6d8c1d9..8fe8cc753174 100644 --- a/internal/generated/snippets/automl/apiv1beta1/PredictionClient/BatchPredict/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/PredictionClient/BatchPredict/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewPredictionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.BatchPredictRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/automl/apiv1beta1/PredictionClient/Predict/main.go b/internal/generated/snippets/automl/apiv1beta1/PredictionClient/Predict/main.go index 466d4da3a006..374c5f3e8b7c 100644 --- a/internal/generated/snippets/automl/apiv1beta1/PredictionClient/Predict/main.go +++ b/internal/generated/snippets/automl/apiv1beta1/PredictionClient/Predict/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import automlpb "google.golang.org/genproto/googleapis/cloud/automl/v1beta1" - ctx := context.Background() c, err := automl.NewPredictionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &automlpb.PredictRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/connection/apiv1/Client/CreateConnection/main.go b/internal/generated/snippets/bigquery/connection/apiv1/Client/CreateConnection/main.go index 6d8dec9e075e..d843f021ec70 100644 --- a/internal/generated/snippets/bigquery/connection/apiv1/Client/CreateConnection/main.go +++ b/internal/generated/snippets/bigquery/connection/apiv1/Client/CreateConnection/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import connectionpb "google.golang.org/genproto/googleapis/cloud/bigquery/connection/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.CreateConnectionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/connection/apiv1/Client/DeleteConnection/main.go b/internal/generated/snippets/bigquery/connection/apiv1/Client/DeleteConnection/main.go index e220f530da82..93a47d568888 100644 --- a/internal/generated/snippets/bigquery/connection/apiv1/Client/DeleteConnection/main.go +++ b/internal/generated/snippets/bigquery/connection/apiv1/Client/DeleteConnection/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.DeleteConnectionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/connection/apiv1/Client/GetConnection/main.go b/internal/generated/snippets/bigquery/connection/apiv1/Client/GetConnection/main.go index 8322041e2177..642ddb3feae8 100644 --- a/internal/generated/snippets/bigquery/connection/apiv1/Client/GetConnection/main.go +++ b/internal/generated/snippets/bigquery/connection/apiv1/Client/GetConnection/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import connectionpb "google.golang.org/genproto/googleapis/cloud/bigquery/connection/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.GetConnectionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/connection/apiv1/Client/GetIamPolicy/main.go b/internal/generated/snippets/bigquery/connection/apiv1/Client/GetIamPolicy/main.go index fd5c940d759e..ec0f34936282 100644 --- a/internal/generated/snippets/bigquery/connection/apiv1/Client/GetIamPolicy/main.go +++ b/internal/generated/snippets/bigquery/connection/apiv1/Client/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/connection/apiv1/Client/ListConnections/main.go b/internal/generated/snippets/bigquery/connection/apiv1/Client/ListConnections/main.go index 4a4e2d537f5a..85f00f4d8ff4 100644 --- a/internal/generated/snippets/bigquery/connection/apiv1/Client/ListConnections/main.go +++ b/internal/generated/snippets/bigquery/connection/apiv1/Client/ListConnections/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import connectionpb "google.golang.org/genproto/googleapis/cloud/bigquery/connection/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.ListConnectionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/connection/apiv1/Client/SetIamPolicy/main.go b/internal/generated/snippets/bigquery/connection/apiv1/Client/SetIamPolicy/main.go index e3e1acb41fb4..bc85b6d94c4d 100644 --- a/internal/generated/snippets/bigquery/connection/apiv1/Client/SetIamPolicy/main.go +++ b/internal/generated/snippets/bigquery/connection/apiv1/Client/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/connection/apiv1/Client/TestIamPermissions/main.go b/internal/generated/snippets/bigquery/connection/apiv1/Client/TestIamPermissions/main.go index a0ad4f894db2..fd207d835d11 100644 --- a/internal/generated/snippets/bigquery/connection/apiv1/Client/TestIamPermissions/main.go +++ b/internal/generated/snippets/bigquery/connection/apiv1/Client/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/connection/apiv1/Client/UpdateConnection/main.go b/internal/generated/snippets/bigquery/connection/apiv1/Client/UpdateConnection/main.go index d03c2364f73a..72436aaf4644 100644 --- a/internal/generated/snippets/bigquery/connection/apiv1/Client/UpdateConnection/main.go +++ b/internal/generated/snippets/bigquery/connection/apiv1/Client/UpdateConnection/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import connectionpb "google.golang.org/genproto/googleapis/cloud/bigquery/connection/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.UpdateConnectionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/CreateConnection/main.go b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/CreateConnection/main.go index df7fcc4c0b95..d18fff8b2cb7 100644 --- a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/CreateConnection/main.go +++ b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/CreateConnection/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import connectionpb "google.golang.org/genproto/googleapis/cloud/bigquery/connection/v1beta1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.CreateConnectionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/DeleteConnection/main.go b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/DeleteConnection/main.go index 11f353672427..e348518f8280 100644 --- a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/DeleteConnection/main.go +++ b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/DeleteConnection/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.DeleteConnectionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/GetConnection/main.go b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/GetConnection/main.go index 94d9ee0a1bc2..0c8a61580ca9 100644 --- a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/GetConnection/main.go +++ b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/GetConnection/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import connectionpb "google.golang.org/genproto/googleapis/cloud/bigquery/connection/v1beta1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.GetConnectionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/GetIamPolicy/main.go b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/GetIamPolicy/main.go index b5cdb879f9a4..d69c78fecdcb 100644 --- a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/GetIamPolicy/main.go +++ b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/ListConnections/main.go b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/ListConnections/main.go index 80ddcb6a99d3..d853c3a0cc5d 100644 --- a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/ListConnections/main.go +++ b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/ListConnections/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import connectionpb "google.golang.org/genproto/googleapis/cloud/bigquery/connection/v1beta1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.ListConnectionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/SetIamPolicy/main.go b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/SetIamPolicy/main.go index 2e6cdd070b68..d0e3bbf2bfde 100644 --- a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/SetIamPolicy/main.go +++ b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/TestIamPermissions/main.go b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/TestIamPermissions/main.go index 48325facbddb..fa4f8d4c25e3 100644 --- a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/TestIamPermissions/main.go +++ b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/UpdateConnection/main.go b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/UpdateConnection/main.go index c7274905ca81..346cc55aba41 100644 --- a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/UpdateConnection/main.go +++ b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/UpdateConnection/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import connectionpb "google.golang.org/genproto/googleapis/cloud/bigquery/connection/v1beta1" - ctx := context.Background() c, err := connection.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.UpdateConnectionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/UpdateConnectionCredential/main.go b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/UpdateConnectionCredential/main.go index 142e0cf32ad9..83f73132c7e4 100644 --- a/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/UpdateConnectionCredential/main.go +++ b/internal/generated/snippets/bigquery/connection/apiv1beta1/Client/UpdateConnectionCredential/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &connectionpb.UpdateConnectionCredentialRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/CheckValidCreds/main.go b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/CheckValidCreds/main.go index 0e94d06ba724..f15b8d726189 100644 --- a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/CheckValidCreds/main.go +++ b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/CheckValidCreds/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.CheckValidCredsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/CreateTransferConfig/main.go b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/CreateTransferConfig/main.go index 3e4fcfbe8a82..820ff338925e 100644 --- a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/CreateTransferConfig/main.go +++ b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/CreateTransferConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.CreateTransferConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/DeleteTransferConfig/main.go b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/DeleteTransferConfig/main.go index 1ef786286ae6..73b84d9aca6c 100644 --- a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/DeleteTransferConfig/main.go +++ b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/DeleteTransferConfig/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.DeleteTransferConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/DeleteTransferRun/main.go b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/DeleteTransferRun/main.go index 65c2a97a3bab..9409178682e4 100644 --- a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/DeleteTransferRun/main.go +++ b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/DeleteTransferRun/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.DeleteTransferRunRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/GetDataSource/main.go b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/GetDataSource/main.go index a63aa1368d62..0c3ad99592d7 100644 --- a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/GetDataSource/main.go +++ b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/GetDataSource/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.GetDataSourceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/GetTransferConfig/main.go b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/GetTransferConfig/main.go index df9f1b96f196..056fd272c342 100644 --- a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/GetTransferConfig/main.go +++ b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/GetTransferConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.GetTransferConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/GetTransferRun/main.go b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/GetTransferRun/main.go index 3b29f19bd2c5..9b0d8e5e088b 100644 --- a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/GetTransferRun/main.go +++ b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/GetTransferRun/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.GetTransferRunRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ListDataSources/main.go b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ListDataSources/main.go index cf19e5876efb..4583c82674d7 100644 --- a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ListDataSources/main.go +++ b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ListDataSources/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.ListDataSourcesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ListTransferConfigs/main.go b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ListTransferConfigs/main.go index c278216f8407..fcd85b4b1bed 100644 --- a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ListTransferConfigs/main.go +++ b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ListTransferConfigs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.ListTransferConfigsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ListTransferLogs/main.go b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ListTransferLogs/main.go index 02aa57397980..6d0c73527e85 100644 --- a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ListTransferLogs/main.go +++ b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ListTransferLogs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.ListTransferLogsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ListTransferRuns/main.go b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ListTransferRuns/main.go index 9d0eed155b08..02c69ed98d54 100644 --- a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ListTransferRuns/main.go +++ b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ListTransferRuns/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.ListTransferRunsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ScheduleTransferRuns/main.go b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ScheduleTransferRuns/main.go index 5f0dfcb09912..39d80603b4cd 100644 --- a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ScheduleTransferRuns/main.go +++ b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/ScheduleTransferRuns/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.ScheduleTransferRunsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/StartManualTransferRuns/main.go b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/StartManualTransferRuns/main.go index 324b76652bbe..01595ce406d5 100644 --- a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/StartManualTransferRuns/main.go +++ b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/StartManualTransferRuns/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.StartManualTransferRunsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/UpdateTransferConfig/main.go b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/UpdateTransferConfig/main.go index dee3639664cf..4f31dc8e6ba1 100644 --- a/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/UpdateTransferConfig/main.go +++ b/internal/generated/snippets/bigquery/datatransfer/apiv1/Client/UpdateTransferConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datatransferpb "google.golang.org/genproto/googleapis/cloud/bigquery/datatransfer/v1" - ctx := context.Background() c, err := datatransfer.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datatransferpb.UpdateTransferConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/CreateAssignment/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/CreateAssignment/main.go index 16a515a72827..0f1130e79762 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/CreateAssignment/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/CreateAssignment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.CreateAssignmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/CreateCapacityCommitment/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/CreateCapacityCommitment/main.go index cf88d1ec7b04..1895f6417161 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/CreateCapacityCommitment/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/CreateCapacityCommitment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.CreateCapacityCommitmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/CreateReservation/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/CreateReservation/main.go index 137bfeee57c6..5a417b2ac872 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/CreateReservation/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/CreateReservation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.CreateReservationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/DeleteAssignment/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/DeleteAssignment/main.go index 18acdbcabd79..69ee986d00aa 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/DeleteAssignment/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/DeleteAssignment/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.DeleteAssignmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/DeleteCapacityCommitment/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/DeleteCapacityCommitment/main.go index 5981be6e8b73..665eb3d91a26 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/DeleteCapacityCommitment/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/DeleteCapacityCommitment/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.DeleteCapacityCommitmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/DeleteReservation/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/DeleteReservation/main.go index 7b403d61f043..37649b8586f3 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/DeleteReservation/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/DeleteReservation/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.DeleteReservationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/GetBiReservation/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/GetBiReservation/main.go index 4c44f2afd6e0..40a7512843c8 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/GetBiReservation/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/GetBiReservation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.GetBiReservationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/GetCapacityCommitment/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/GetCapacityCommitment/main.go index 496e19724708..37c0d422f675 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/GetCapacityCommitment/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/GetCapacityCommitment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.GetCapacityCommitmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/GetReservation/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/GetReservation/main.go index 20992142f5e7..2b96b817174c 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/GetReservation/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/GetReservation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.GetReservationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/ListAssignments/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/ListAssignments/main.go index b83710492fa2..21d810120694 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/ListAssignments/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/ListAssignments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.ListAssignmentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/ListCapacityCommitments/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/ListCapacityCommitments/main.go index 54b93777a41a..0feb8d79e58c 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/ListCapacityCommitments/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/ListCapacityCommitments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.ListCapacityCommitmentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/ListReservations/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/ListReservations/main.go index 1bb04875bdf8..f2009d319eae 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/ListReservations/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/ListReservations/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.ListReservationsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/MergeCapacityCommitments/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/MergeCapacityCommitments/main.go index 9bc18c96905e..6a79956d4772 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/MergeCapacityCommitments/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/MergeCapacityCommitments/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.MergeCapacityCommitmentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/MoveAssignment/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/MoveAssignment/main.go index d7347f2b17d3..db30e693443a 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/MoveAssignment/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/MoveAssignment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.MoveAssignmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/SearchAssignments/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/SearchAssignments/main.go index f6469cda1a4d..80ccb243094d 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/SearchAssignments/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/SearchAssignments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.SearchAssignmentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/SplitCapacityCommitment/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/SplitCapacityCommitment/main.go index 98cfa6acb350..7684294d96da 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/SplitCapacityCommitment/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/SplitCapacityCommitment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.SplitCapacityCommitmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/UpdateBiReservation/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/UpdateBiReservation/main.go index 3f5bb205dce0..1d608b8dd00b 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/UpdateBiReservation/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/UpdateBiReservation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.UpdateBiReservationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/UpdateCapacityCommitment/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/UpdateCapacityCommitment/main.go index 7f361382b80d..e7148d3dc4b9 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/UpdateCapacityCommitment/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/UpdateCapacityCommitment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.UpdateCapacityCommitmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1/Client/UpdateReservation/main.go b/internal/generated/snippets/bigquery/reservation/apiv1/Client/UpdateReservation/main.go index c64c8c104e61..023a76a687b6 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1/Client/UpdateReservation/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1/Client/UpdateReservation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.UpdateReservationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/CreateAssignment/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/CreateAssignment/main.go index 719c32bdb1fb..1986652d1610 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/CreateAssignment/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/CreateAssignment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.CreateAssignmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/CreateCapacityCommitment/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/CreateCapacityCommitment/main.go index b7b11b548cc8..74341227c9c8 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/CreateCapacityCommitment/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/CreateCapacityCommitment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.CreateCapacityCommitmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/CreateReservation/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/CreateReservation/main.go index f547ffa09324..fe93f13f12a4 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/CreateReservation/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/CreateReservation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.CreateReservationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/DeleteAssignment/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/DeleteAssignment/main.go index d94957cfb002..ebd6b522154b 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/DeleteAssignment/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/DeleteAssignment/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.DeleteAssignmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/DeleteCapacityCommitment/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/DeleteCapacityCommitment/main.go index f4f6f32bf0ad..28ac132f85a2 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/DeleteCapacityCommitment/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/DeleteCapacityCommitment/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.DeleteCapacityCommitmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/DeleteReservation/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/DeleteReservation/main.go index 306cae1526a6..bb6b7739db9b 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/DeleteReservation/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/DeleteReservation/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.DeleteReservationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/GetBiReservation/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/GetBiReservation/main.go index 6be1b8efc81a..6370b1db9e96 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/GetBiReservation/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/GetBiReservation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.GetBiReservationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/GetCapacityCommitment/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/GetCapacityCommitment/main.go index 4a7e540ed2b1..8f5466fb0293 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/GetCapacityCommitment/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/GetCapacityCommitment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.GetCapacityCommitmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/GetReservation/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/GetReservation/main.go index 4b5cc42aa666..3686b24cd206 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/GetReservation/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/GetReservation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.GetReservationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/ListAssignments/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/ListAssignments/main.go index 2ad627ae6848..03dacc7d067b 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/ListAssignments/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/ListAssignments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.ListAssignmentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/ListCapacityCommitments/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/ListCapacityCommitments/main.go index b650a402f803..8411efd9651f 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/ListCapacityCommitments/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/ListCapacityCommitments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.ListCapacityCommitmentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/ListReservations/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/ListReservations/main.go index dd8ed48a63dd..044344d2a32e 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/ListReservations/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/ListReservations/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.ListReservationsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/MergeCapacityCommitments/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/MergeCapacityCommitments/main.go index e0e317078f8e..a705b2871546 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/MergeCapacityCommitments/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/MergeCapacityCommitments/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.MergeCapacityCommitmentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/MoveAssignment/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/MoveAssignment/main.go index e1d684e999ea..965efec89d6a 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/MoveAssignment/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/MoveAssignment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.MoveAssignmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/SearchAssignments/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/SearchAssignments/main.go index 82a466a1c667..6bf113442a69 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/SearchAssignments/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/SearchAssignments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.SearchAssignmentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/SplitCapacityCommitment/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/SplitCapacityCommitment/main.go index a73018e1d44f..b29e05ccb023 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/SplitCapacityCommitment/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/SplitCapacityCommitment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.SplitCapacityCommitmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/UpdateBiReservation/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/UpdateBiReservation/main.go index a36a19dc7a20..3df18f201da5 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/UpdateBiReservation/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/UpdateBiReservation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.UpdateBiReservationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/UpdateCapacityCommitment/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/UpdateCapacityCommitment/main.go index 67e64bda57e6..5dcf7be2a500 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/UpdateCapacityCommitment/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/UpdateCapacityCommitment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.UpdateCapacityCommitmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/UpdateReservation/main.go b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/UpdateReservation/main.go index da03446966a1..ef95f6b42ef5 100644 --- a/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/UpdateReservation/main.go +++ b/internal/generated/snippets/bigquery/reservation/apiv1beta1/Client/UpdateReservation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import reservationpb "google.golang.org/genproto/googleapis/cloud/bigquery/reservation/v1beta1" - ctx := context.Background() c, err := reservation.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &reservationpb.UpdateReservationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/storage/apiv1/BigQueryReadClient/CreateReadSession/main.go b/internal/generated/snippets/bigquery/storage/apiv1/BigQueryReadClient/CreateReadSession/main.go index 874c24d4201f..53f4780e2ae2 100644 --- a/internal/generated/snippets/bigquery/storage/apiv1/BigQueryReadClient/CreateReadSession/main.go +++ b/internal/generated/snippets/bigquery/storage/apiv1/BigQueryReadClient/CreateReadSession/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1" - ctx := context.Background() c, err := storage.NewBigQueryReadClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.CreateReadSessionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/storage/apiv1/BigQueryReadClient/SplitReadStream/main.go b/internal/generated/snippets/bigquery/storage/apiv1/BigQueryReadClient/SplitReadStream/main.go index a21835851be3..6239efa0e38e 100644 --- a/internal/generated/snippets/bigquery/storage/apiv1/BigQueryReadClient/SplitReadStream/main.go +++ b/internal/generated/snippets/bigquery/storage/apiv1/BigQueryReadClient/SplitReadStream/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1" - ctx := context.Background() c, err := storage.NewBigQueryReadClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.SplitReadStreamRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/storage/apiv1beta1/BigQueryStorageClient/BatchCreateReadSessionStreams/main.go b/internal/generated/snippets/bigquery/storage/apiv1beta1/BigQueryStorageClient/BatchCreateReadSessionStreams/main.go index 6e9ef43aae9d..019bbb0f476a 100644 --- a/internal/generated/snippets/bigquery/storage/apiv1beta1/BigQueryStorageClient/BatchCreateReadSessionStreams/main.go +++ b/internal/generated/snippets/bigquery/storage/apiv1beta1/BigQueryStorageClient/BatchCreateReadSessionStreams/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta1" - ctx := context.Background() c, err := storage.NewBigQueryStorageClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.BatchCreateReadSessionStreamsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/storage/apiv1beta1/BigQueryStorageClient/CreateReadSession/main.go b/internal/generated/snippets/bigquery/storage/apiv1beta1/BigQueryStorageClient/CreateReadSession/main.go index 0264799daf57..76a9ba43b0ba 100644 --- a/internal/generated/snippets/bigquery/storage/apiv1beta1/BigQueryStorageClient/CreateReadSession/main.go +++ b/internal/generated/snippets/bigquery/storage/apiv1beta1/BigQueryStorageClient/CreateReadSession/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta1" - ctx := context.Background() c, err := storage.NewBigQueryStorageClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.CreateReadSessionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/storage/apiv1beta1/BigQueryStorageClient/FinalizeStream/main.go b/internal/generated/snippets/bigquery/storage/apiv1beta1/BigQueryStorageClient/FinalizeStream/main.go index 1fff731fe46c..dd6115b54b1a 100644 --- a/internal/generated/snippets/bigquery/storage/apiv1beta1/BigQueryStorageClient/FinalizeStream/main.go +++ b/internal/generated/snippets/bigquery/storage/apiv1beta1/BigQueryStorageClient/FinalizeStream/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.FinalizeStreamRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/storage/apiv1beta1/BigQueryStorageClient/SplitReadStream/main.go b/internal/generated/snippets/bigquery/storage/apiv1beta1/BigQueryStorageClient/SplitReadStream/main.go index 1029bd4d9bcd..30ee92091393 100644 --- a/internal/generated/snippets/bigquery/storage/apiv1beta1/BigQueryStorageClient/SplitReadStream/main.go +++ b/internal/generated/snippets/bigquery/storage/apiv1beta1/BigQueryStorageClient/SplitReadStream/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta1" - ctx := context.Background() c, err := storage.NewBigQueryStorageClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.SplitReadStreamRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryReadClient/CreateReadSession/main.go b/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryReadClient/CreateReadSession/main.go index 53dac5ce0209..0a60fff39fd5 100644 --- a/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryReadClient/CreateReadSession/main.go +++ b/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryReadClient/CreateReadSession/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta2" - ctx := context.Background() c, err := storage.NewBigQueryReadClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.CreateReadSessionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryReadClient/SplitReadStream/main.go b/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryReadClient/SplitReadStream/main.go index f7dd5513a19b..9ac681556610 100644 --- a/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryReadClient/SplitReadStream/main.go +++ b/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryReadClient/SplitReadStream/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta2" - ctx := context.Background() c, err := storage.NewBigQueryReadClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.SplitReadStreamRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/AppendRows/main.go b/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/AppendRows/main.go index 2d1b25d44e60..606cfe25d439 100644 --- a/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/AppendRows/main.go +++ b/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/AppendRows/main.go @@ -25,13 +25,12 @@ import ( ) func main() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta2" - ctx := context.Background() c, err := storage.NewBigQueryWriteClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.AppendRows(ctx) if err != nil { // TODO: Handle error. diff --git a/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/BatchCommitWriteStreams/main.go b/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/BatchCommitWriteStreams/main.go index 5c81857e5c6a..0560a1a9fa5f 100644 --- a/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/BatchCommitWriteStreams/main.go +++ b/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/BatchCommitWriteStreams/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta2" - ctx := context.Background() c, err := storage.NewBigQueryWriteClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.BatchCommitWriteStreamsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/CreateWriteStream/main.go b/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/CreateWriteStream/main.go index f76bf5dfd8e8..0e263f452d32 100644 --- a/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/CreateWriteStream/main.go +++ b/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/CreateWriteStream/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta2" - ctx := context.Background() c, err := storage.NewBigQueryWriteClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.CreateWriteStreamRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/FinalizeWriteStream/main.go b/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/FinalizeWriteStream/main.go index 465bf16672fc..783623445012 100644 --- a/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/FinalizeWriteStream/main.go +++ b/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/FinalizeWriteStream/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta2" - ctx := context.Background() c, err := storage.NewBigQueryWriteClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.FinalizeWriteStreamRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/FlushRows/main.go b/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/FlushRows/main.go index 7f1191494594..c1814cda3c75 100644 --- a/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/FlushRows/main.go +++ b/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/FlushRows/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta2" - ctx := context.Background() c, err := storage.NewBigQueryWriteClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.FlushRowsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/GetWriteStream/main.go b/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/GetWriteStream/main.go index a7c55e68a54f..ad416246bfc7 100644 --- a/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/GetWriteStream/main.go +++ b/internal/generated/snippets/bigquery/storage/apiv1beta2/BigQueryWriteClient/GetWriteStream/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import storagepb "google.golang.org/genproto/googleapis/cloud/bigquery/storage/v1beta2" - ctx := context.Background() c, err := storage.NewBigQueryWriteClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &storagepb.GetWriteStreamRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/apiv1/CloudBillingClient/CreateBillingAccount/main.go b/internal/generated/snippets/billing/apiv1/CloudBillingClient/CreateBillingAccount/main.go index 3f0b3b0e9490..b9bdba7f0494 100644 --- a/internal/generated/snippets/billing/apiv1/CloudBillingClient/CreateBillingAccount/main.go +++ b/internal/generated/snippets/billing/apiv1/CloudBillingClient/CreateBillingAccount/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.CreateBillingAccountRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/apiv1/CloudBillingClient/GetBillingAccount/main.go b/internal/generated/snippets/billing/apiv1/CloudBillingClient/GetBillingAccount/main.go index bdc31e403ca2..c9b2f9e08be6 100644 --- a/internal/generated/snippets/billing/apiv1/CloudBillingClient/GetBillingAccount/main.go +++ b/internal/generated/snippets/billing/apiv1/CloudBillingClient/GetBillingAccount/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.GetBillingAccountRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/apiv1/CloudBillingClient/GetIamPolicy/main.go b/internal/generated/snippets/billing/apiv1/CloudBillingClient/GetIamPolicy/main.go index ce01cfa86286..d514ee69d908 100644 --- a/internal/generated/snippets/billing/apiv1/CloudBillingClient/GetIamPolicy/main.go +++ b/internal/generated/snippets/billing/apiv1/CloudBillingClient/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/apiv1/CloudBillingClient/GetProjectBillingInfo/main.go b/internal/generated/snippets/billing/apiv1/CloudBillingClient/GetProjectBillingInfo/main.go index b83a7cebcd23..956ee05e5f65 100644 --- a/internal/generated/snippets/billing/apiv1/CloudBillingClient/GetProjectBillingInfo/main.go +++ b/internal/generated/snippets/billing/apiv1/CloudBillingClient/GetProjectBillingInfo/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.GetProjectBillingInfoRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/apiv1/CloudBillingClient/ListBillingAccounts/main.go b/internal/generated/snippets/billing/apiv1/CloudBillingClient/ListBillingAccounts/main.go index 7f817b2b8491..a95292c6e80d 100644 --- a/internal/generated/snippets/billing/apiv1/CloudBillingClient/ListBillingAccounts/main.go +++ b/internal/generated/snippets/billing/apiv1/CloudBillingClient/ListBillingAccounts/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.ListBillingAccountsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/apiv1/CloudBillingClient/ListProjectBillingInfo/main.go b/internal/generated/snippets/billing/apiv1/CloudBillingClient/ListProjectBillingInfo/main.go index 5bdb9e893be4..97883de212a4 100644 --- a/internal/generated/snippets/billing/apiv1/CloudBillingClient/ListProjectBillingInfo/main.go +++ b/internal/generated/snippets/billing/apiv1/CloudBillingClient/ListProjectBillingInfo/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.ListProjectBillingInfoRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/apiv1/CloudBillingClient/SetIamPolicy/main.go b/internal/generated/snippets/billing/apiv1/CloudBillingClient/SetIamPolicy/main.go index 6cf77ce44d98..399ddef7206a 100644 --- a/internal/generated/snippets/billing/apiv1/CloudBillingClient/SetIamPolicy/main.go +++ b/internal/generated/snippets/billing/apiv1/CloudBillingClient/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/apiv1/CloudBillingClient/TestIamPermissions/main.go b/internal/generated/snippets/billing/apiv1/CloudBillingClient/TestIamPermissions/main.go index eb53cfe5e82c..08fabd53c03e 100644 --- a/internal/generated/snippets/billing/apiv1/CloudBillingClient/TestIamPermissions/main.go +++ b/internal/generated/snippets/billing/apiv1/CloudBillingClient/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/apiv1/CloudBillingClient/UpdateBillingAccount/main.go b/internal/generated/snippets/billing/apiv1/CloudBillingClient/UpdateBillingAccount/main.go index 68576dcdaf8c..d9192a14c7f8 100644 --- a/internal/generated/snippets/billing/apiv1/CloudBillingClient/UpdateBillingAccount/main.go +++ b/internal/generated/snippets/billing/apiv1/CloudBillingClient/UpdateBillingAccount/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.UpdateBillingAccountRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/apiv1/CloudBillingClient/UpdateProjectBillingInfo/main.go b/internal/generated/snippets/billing/apiv1/CloudBillingClient/UpdateProjectBillingInfo/main.go index ddbfdcef8913..ff26e2bd4957 100644 --- a/internal/generated/snippets/billing/apiv1/CloudBillingClient/UpdateProjectBillingInfo/main.go +++ b/internal/generated/snippets/billing/apiv1/CloudBillingClient/UpdateProjectBillingInfo/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - ctx := context.Background() c, err := billing.NewCloudBillingClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.UpdateProjectBillingInfoRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/apiv1/CloudCatalogClient/ListServices/main.go b/internal/generated/snippets/billing/apiv1/CloudCatalogClient/ListServices/main.go index 9aeaef1c842f..143b1461b5f6 100644 --- a/internal/generated/snippets/billing/apiv1/CloudCatalogClient/ListServices/main.go +++ b/internal/generated/snippets/billing/apiv1/CloudCatalogClient/ListServices/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := billing.NewCloudCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.ListServicesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/apiv1/CloudCatalogClient/ListSkus/main.go b/internal/generated/snippets/billing/apiv1/CloudCatalogClient/ListSkus/main.go index 89bb0d99baee..1c2b56c5a17e 100644 --- a/internal/generated/snippets/billing/apiv1/CloudCatalogClient/ListSkus/main.go +++ b/internal/generated/snippets/billing/apiv1/CloudCatalogClient/ListSkus/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import billingpb "google.golang.org/genproto/googleapis/cloud/billing/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := billing.NewCloudCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &billingpb.ListSkusRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/CreateBudget/main.go b/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/CreateBudget/main.go index 309e73ab56ea..86ca3bd382c6 100644 --- a/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/CreateBudget/main.go +++ b/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/CreateBudget/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import budgetspb "google.golang.org/genproto/googleapis/cloud/billing/budgets/v1" - ctx := context.Background() c, err := budgets.NewBudgetClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.CreateBudgetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/DeleteBudget/main.go b/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/DeleteBudget/main.go index 86cffc22bdd0..89ee24d1c4d2 100644 --- a/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/DeleteBudget/main.go +++ b/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/DeleteBudget/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.DeleteBudgetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/GetBudget/main.go b/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/GetBudget/main.go index bdaa1f0f7e3f..d1e330e67a0c 100644 --- a/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/GetBudget/main.go +++ b/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/GetBudget/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import budgetspb "google.golang.org/genproto/googleapis/cloud/billing/budgets/v1" - ctx := context.Background() c, err := budgets.NewBudgetClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.GetBudgetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/ListBudgets/main.go b/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/ListBudgets/main.go index 649781cdb86e..9a082e8920dc 100644 --- a/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/ListBudgets/main.go +++ b/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/ListBudgets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import budgetspb "google.golang.org/genproto/googleapis/cloud/billing/budgets/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := budgets.NewBudgetClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.ListBudgetsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/UpdateBudget/main.go b/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/UpdateBudget/main.go index 3d996b8cfc3d..175cd2919ac8 100644 --- a/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/UpdateBudget/main.go +++ b/internal/generated/snippets/billing/budgets/apiv1/BudgetClient/UpdateBudget/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import budgetspb "google.golang.org/genproto/googleapis/cloud/billing/budgets/v1" - ctx := context.Background() c, err := budgets.NewBudgetClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.UpdateBudgetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/CreateBudget/main.go b/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/CreateBudget/main.go index b28380bd0e89..c927140748b3 100644 --- a/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/CreateBudget/main.go +++ b/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/CreateBudget/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import budgetspb "google.golang.org/genproto/googleapis/cloud/billing/budgets/v1beta1" - ctx := context.Background() c, err := budgets.NewBudgetClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.CreateBudgetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/DeleteBudget/main.go b/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/DeleteBudget/main.go index 722e82ab1e0b..34225e5c819d 100644 --- a/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/DeleteBudget/main.go +++ b/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/DeleteBudget/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.DeleteBudgetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/GetBudget/main.go b/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/GetBudget/main.go index 02d6ecb1a6dc..d9f83d1e1c73 100644 --- a/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/GetBudget/main.go +++ b/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/GetBudget/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import budgetspb "google.golang.org/genproto/googleapis/cloud/billing/budgets/v1beta1" - ctx := context.Background() c, err := budgets.NewBudgetClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.GetBudgetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/ListBudgets/main.go b/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/ListBudgets/main.go index 9e2cf21db6d8..396199d2c7f1 100644 --- a/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/ListBudgets/main.go +++ b/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/ListBudgets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import budgetspb "google.golang.org/genproto/googleapis/cloud/billing/budgets/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := budgets.NewBudgetClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.ListBudgetsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/UpdateBudget/main.go b/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/UpdateBudget/main.go index ebd8ed28d106..89b8a8cd7a34 100644 --- a/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/UpdateBudget/main.go +++ b/internal/generated/snippets/billing/budgets/apiv1beta1/BudgetClient/UpdateBudget/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import budgetspb "google.golang.org/genproto/googleapis/cloud/billing/budgets/v1beta1" - ctx := context.Background() c, err := budgets.NewBudgetClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &budgetspb.UpdateBudgetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/CreateAttestor/main.go b/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/CreateAttestor/main.go index 7105b35f8892..07609c406c97 100644 --- a/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/CreateAttestor/main.go +++ b/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/CreateAttestor/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import binaryauthorizationpb "google.golang.org/genproto/googleapis/cloud/binaryauthorization/v1beta1" - ctx := context.Background() c, err := binaryauthorization.NewBinauthzManagementServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &binaryauthorizationpb.CreateAttestorRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/DeleteAttestor/main.go b/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/DeleteAttestor/main.go index 7df05a4e396b..2ea7d7974129 100644 --- a/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/DeleteAttestor/main.go +++ b/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/DeleteAttestor/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &binaryauthorizationpb.DeleteAttestorRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/GetAttestor/main.go b/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/GetAttestor/main.go index 97466646c80a..558c91124713 100644 --- a/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/GetAttestor/main.go +++ b/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/GetAttestor/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import binaryauthorizationpb "google.golang.org/genproto/googleapis/cloud/binaryauthorization/v1beta1" - ctx := context.Background() c, err := binaryauthorization.NewBinauthzManagementServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &binaryauthorizationpb.GetAttestorRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/GetPolicy/main.go b/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/GetPolicy/main.go index 6e2bcac41972..a91d7c032e36 100644 --- a/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/GetPolicy/main.go +++ b/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/GetPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import binaryauthorizationpb "google.golang.org/genproto/googleapis/cloud/binaryauthorization/v1beta1" - ctx := context.Background() c, err := binaryauthorization.NewBinauthzManagementServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &binaryauthorizationpb.GetPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/ListAttestors/main.go b/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/ListAttestors/main.go index 00310b06c6fa..afab0aa9f282 100644 --- a/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/ListAttestors/main.go +++ b/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/ListAttestors/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import binaryauthorizationpb "google.golang.org/genproto/googleapis/cloud/binaryauthorization/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := binaryauthorization.NewBinauthzManagementServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &binaryauthorizationpb.ListAttestorsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/UpdateAttestor/main.go b/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/UpdateAttestor/main.go index ad0bb07dc8a0..d223c58018e2 100644 --- a/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/UpdateAttestor/main.go +++ b/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/UpdateAttestor/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import binaryauthorizationpb "google.golang.org/genproto/googleapis/cloud/binaryauthorization/v1beta1" - ctx := context.Background() c, err := binaryauthorization.NewBinauthzManagementServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &binaryauthorizationpb.UpdateAttestorRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/UpdatePolicy/main.go b/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/UpdatePolicy/main.go index c3519b3fc0e4..33a5c84e93ef 100644 --- a/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/UpdatePolicy/main.go +++ b/internal/generated/snippets/binaryauthorization/apiv1beta1/BinauthzManagementServiceV1Beta1Client/UpdatePolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import binaryauthorizationpb "google.golang.org/genproto/googleapis/cloud/binaryauthorization/v1beta1" - ctx := context.Background() c, err := binaryauthorization.NewBinauthzManagementServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &binaryauthorizationpb.UpdatePolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ActivateEntitlement/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ActivateEntitlement/main.go index dab3548535a5..70e4e996eb13 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ActivateEntitlement/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ActivateEntitlement/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ActivateEntitlementRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/CancelEntitlement/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/CancelEntitlement/main.go index 2670c200a992..60ff708ed370 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/CancelEntitlement/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/CancelEntitlement/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.CancelEntitlementRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ChangeOffer/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ChangeOffer/main.go index 82f86fcdb90a..03d5cb28c3d4 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ChangeOffer/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ChangeOffer/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ChangeOfferRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ChangeParameters/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ChangeParameters/main.go index ceda0c91316d..bf2d3b6c6d8b 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ChangeParameters/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ChangeParameters/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ChangeParametersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ChangeRenewalSettings/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ChangeRenewalSettings/main.go index d6b14dd4461c..954a7662dd83 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ChangeRenewalSettings/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ChangeRenewalSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ChangeRenewalSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/CheckCloudIdentityAccountsExist/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/CheckCloudIdentityAccountsExist/main.go index 9a5684211419..24ab1fc88586 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/CheckCloudIdentityAccountsExist/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/CheckCloudIdentityAccountsExist/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.CheckCloudIdentityAccountsExistRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/CreateChannelPartnerLink/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/CreateChannelPartnerLink/main.go index 6f0b3d0ffbb6..c6880ae70425 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/CreateChannelPartnerLink/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/CreateChannelPartnerLink/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.CreateChannelPartnerLinkRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/CreateCustomer/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/CreateCustomer/main.go index ba3cdd14328a..0cbb9e872830 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/CreateCustomer/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/CreateCustomer/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.CreateCustomerRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/CreateEntitlement/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/CreateEntitlement/main.go index a5ba134f08ad..e933bc7b1452 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/CreateEntitlement/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/CreateEntitlement/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.CreateEntitlementRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/DeleteCustomer/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/DeleteCustomer/main.go index 198a15db350e..744d7fc2ba5e 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/DeleteCustomer/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/DeleteCustomer/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.DeleteCustomerRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/GetChannelPartnerLink/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/GetChannelPartnerLink/main.go index 2c2582c15240..28813a3ad1b5 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/GetChannelPartnerLink/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/GetChannelPartnerLink/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.GetChannelPartnerLinkRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/GetCustomer/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/GetCustomer/main.go index bdbebeba0f26..6f6574a0b0b8 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/GetCustomer/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/GetCustomer/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.GetCustomerRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/GetEntitlement/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/GetEntitlement/main.go index fad0a3b46e4e..bf9235aa205b 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/GetEntitlement/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/GetEntitlement/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.GetEntitlementRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListChannelPartnerLinks/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListChannelPartnerLinks/main.go index 3e2c5e9114cd..a3c64f6e8b47 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListChannelPartnerLinks/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListChannelPartnerLinks/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListChannelPartnerLinksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListCustomers/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListCustomers/main.go index 3988a08f4bb7..c255cb5e665c 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListCustomers/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListCustomers/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListCustomersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListEntitlements/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListEntitlements/main.go index a799250ac97d..908298f1fd32 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListEntitlements/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListEntitlements/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListEntitlementsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListOffers/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListOffers/main.go index 2dd513023cb1..2169b7e63cae 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListOffers/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListOffers/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListOffersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListProducts/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListProducts/main.go index 753f0e93c762..ff853962c624 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListProducts/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListProducts/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListProductsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListPurchasableOffers/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListPurchasableOffers/main.go index 2c1b2b5cb126..516d3790b6c0 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListPurchasableOffers/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListPurchasableOffers/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListPurchasableOffersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListPurchasableSkus/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListPurchasableSkus/main.go index f3741d378d81..a8ca2cdd825f 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListPurchasableSkus/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListPurchasableSkus/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListPurchasableSkusRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListSkus/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListSkus/main.go index 226ae5b05212..6e2c3801c7e6 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListSkus/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListSkus/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListSkusRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListSubscribers/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListSubscribers/main.go index 236dcada726a..efa0a856844d 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListSubscribers/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListSubscribers/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListSubscribersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListTransferableOffers/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListTransferableOffers/main.go index 6f0d61000dfe..c236012560c6 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListTransferableOffers/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListTransferableOffers/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListTransferableOffersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListTransferableSkus/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListTransferableSkus/main.go index 587cdc4af5b1..755db5386a11 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListTransferableSkus/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ListTransferableSkus/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ListTransferableSkusRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ProvisionCloudIdentity/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ProvisionCloudIdentity/main.go index 526dd88599ee..b32b667b6729 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/ProvisionCloudIdentity/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/ProvisionCloudIdentity/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.ProvisionCloudIdentityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/RegisterSubscriber/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/RegisterSubscriber/main.go index a148d20acd53..e6fdaa87fdcb 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/RegisterSubscriber/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/RegisterSubscriber/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.RegisterSubscriberRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/StartPaidService/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/StartPaidService/main.go index 262bf5bf70d6..28d5b64d4b70 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/StartPaidService/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/StartPaidService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.StartPaidServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/SuspendEntitlement/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/SuspendEntitlement/main.go index b996e83b4473..c7614c8710e9 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/SuspendEntitlement/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/SuspendEntitlement/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.SuspendEntitlementRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/TransferEntitlements/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/TransferEntitlements/main.go index 8a95a4df888c..bd9b9ed6eaad 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/TransferEntitlements/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/TransferEntitlements/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.TransferEntitlementsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/TransferEntitlementsToGoogle/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/TransferEntitlementsToGoogle/main.go index e412482a8ac9..c250a96398e5 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/TransferEntitlementsToGoogle/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/TransferEntitlementsToGoogle/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.TransferEntitlementsToGoogleRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/UnregisterSubscriber/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/UnregisterSubscriber/main.go index 0dc375c1808a..80a62a790cba 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/UnregisterSubscriber/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/UnregisterSubscriber/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.UnregisterSubscriberRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/UpdateChannelPartnerLink/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/UpdateChannelPartnerLink/main.go index 16cd778d0c40..c6d2c856b482 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/UpdateChannelPartnerLink/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/UpdateChannelPartnerLink/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.UpdateChannelPartnerLinkRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/channel/apiv1/CloudChannelClient/UpdateCustomer/main.go b/internal/generated/snippets/channel/apiv1/CloudChannelClient/UpdateCustomer/main.go index 41a68cc5097c..1388a8a2ea75 100644 --- a/internal/generated/snippets/channel/apiv1/CloudChannelClient/UpdateCustomer/main.go +++ b/internal/generated/snippets/channel/apiv1/CloudChannelClient/UpdateCustomer/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import channelpb "google.golang.org/genproto/googleapis/cloud/channel/v1" - ctx := context.Background() c, err := channel.NewCloudChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &channelpb.UpdateCustomerRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/CancelBuild/main.go b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/CancelBuild/main.go index c3c233ef07ab..7e9549f9e50f 100644 --- a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/CancelBuild/main.go +++ b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/CancelBuild/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.CancelBuildRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/CreateBuild/main.go b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/CreateBuild/main.go index 5976abf4ff63..734d241c95ca 100644 --- a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/CreateBuild/main.go +++ b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/CreateBuild/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.CreateBuildRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/CreateBuildTrigger/main.go b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/CreateBuildTrigger/main.go index 601b4266162c..cb064c30a4c2 100644 --- a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/CreateBuildTrigger/main.go +++ b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/CreateBuildTrigger/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.CreateBuildTriggerRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/CreateWorkerPool/main.go b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/CreateWorkerPool/main.go index 1e707beb2322..b1689e0a9e71 100644 --- a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/CreateWorkerPool/main.go +++ b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/CreateWorkerPool/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.CreateWorkerPoolRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/DeleteBuildTrigger/main.go b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/DeleteBuildTrigger/main.go index db9657b706ea..2e1b32b1ba90 100644 --- a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/DeleteBuildTrigger/main.go +++ b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/DeleteBuildTrigger/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.DeleteBuildTriggerRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/DeleteWorkerPool/main.go b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/DeleteWorkerPool/main.go index e1499f252ad4..ea08f5496855 100644 --- a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/DeleteWorkerPool/main.go +++ b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/DeleteWorkerPool/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.DeleteWorkerPoolRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/GetBuild/main.go b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/GetBuild/main.go index ca1dedd15456..4ea7c89219bb 100644 --- a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/GetBuild/main.go +++ b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/GetBuild/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.GetBuildRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/GetBuildTrigger/main.go b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/GetBuildTrigger/main.go index 665d89c88061..08ed8ab8fa58 100644 --- a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/GetBuildTrigger/main.go +++ b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/GetBuildTrigger/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.GetBuildTriggerRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/GetWorkerPool/main.go b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/GetWorkerPool/main.go index bc61c3cde3ca..ea97d907abb3 100644 --- a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/GetWorkerPool/main.go +++ b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/GetWorkerPool/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.GetWorkerPoolRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/ListBuildTriggers/main.go b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/ListBuildTriggers/main.go index f6d4c9a28715..f99195d7b06e 100644 --- a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/ListBuildTriggers/main.go +++ b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/ListBuildTriggers/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.ListBuildTriggersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/ListBuilds/main.go b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/ListBuilds/main.go index 42ac2e14e60f..10526f02f74b 100644 --- a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/ListBuilds/main.go +++ b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/ListBuilds/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.ListBuildsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/ListWorkerPools/main.go b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/ListWorkerPools/main.go index 0a24c3fdc53a..665d8bb171a2 100644 --- a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/ListWorkerPools/main.go +++ b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/ListWorkerPools/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.ListWorkerPoolsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/ReceiveTriggerWebhook/main.go b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/ReceiveTriggerWebhook/main.go index 59e1388eb773..865c0bddad88 100644 --- a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/ReceiveTriggerWebhook/main.go +++ b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/ReceiveTriggerWebhook/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.ReceiveTriggerWebhookRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/RetryBuild/main.go b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/RetryBuild/main.go index 0c9663c9e2dc..15f3c9162889 100644 --- a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/RetryBuild/main.go +++ b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/RetryBuild/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.RetryBuildRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/RunBuildTrigger/main.go b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/RunBuildTrigger/main.go index 2a685c8e07eb..151ed2357438 100644 --- a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/RunBuildTrigger/main.go +++ b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/RunBuildTrigger/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.RunBuildTriggerRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/UpdateBuildTrigger/main.go b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/UpdateBuildTrigger/main.go index ebb63b61b28c..f5bebcee4e42 100644 --- a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/UpdateBuildTrigger/main.go +++ b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/UpdateBuildTrigger/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.UpdateBuildTriggerRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/UpdateWorkerPool/main.go b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/UpdateWorkerPool/main.go index 2c20a16252c5..9617cf9379cc 100644 --- a/internal/generated/snippets/cloudbuild/apiv1/v2/Client/UpdateWorkerPool/main.go +++ b/internal/generated/snippets/cloudbuild/apiv1/v2/Client/UpdateWorkerPool/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" - ctx := context.Background() c, err := cloudbuild.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudbuildpb.UpdateWorkerPoolRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/CreateConnectionProfile/main.go b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/CreateConnectionProfile/main.go index cdfa70f327c5..c11458ceb9a6 100644 --- a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/CreateConnectionProfile/main.go +++ b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/CreateConnectionProfile/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.CreateConnectionProfileRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/CreateMigrationJob/main.go b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/CreateMigrationJob/main.go index 286cb6b0efdb..2fdfda217550 100644 --- a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/CreateMigrationJob/main.go +++ b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/CreateMigrationJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.CreateMigrationJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/DeleteConnectionProfile/main.go b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/DeleteConnectionProfile/main.go index ee752045eefd..f916d53595fa 100644 --- a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/DeleteConnectionProfile/main.go +++ b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/DeleteConnectionProfile/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.DeleteConnectionProfileRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/DeleteMigrationJob/main.go b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/DeleteMigrationJob/main.go index ddbbed203f46..1b7f613d45b2 100644 --- a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/DeleteMigrationJob/main.go +++ b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/DeleteMigrationJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.DeleteMigrationJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/GenerateSshScript/main.go b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/GenerateSshScript/main.go index 0cd2126d4a36..bb8ee4b79d64 100644 --- a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/GenerateSshScript/main.go +++ b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/GenerateSshScript/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.GenerateSshScriptRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/GetConnectionProfile/main.go b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/GetConnectionProfile/main.go index b25c2c7406dd..bd0899704c46 100644 --- a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/GetConnectionProfile/main.go +++ b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/GetConnectionProfile/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.GetConnectionProfileRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/GetMigrationJob/main.go b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/GetMigrationJob/main.go index 5f3185f7b926..93bdfef85178 100644 --- a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/GetMigrationJob/main.go +++ b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/GetMigrationJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.GetMigrationJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/ListConnectionProfiles/main.go b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/ListConnectionProfiles/main.go index 292b3ebd8c37..7eb3fbd99602 100644 --- a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/ListConnectionProfiles/main.go +++ b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/ListConnectionProfiles/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.ListConnectionProfilesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/ListMigrationJobs/main.go b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/ListMigrationJobs/main.go index b6efdf91828f..1c68dd3fdfda 100644 --- a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/ListMigrationJobs/main.go +++ b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/ListMigrationJobs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.ListMigrationJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/PromoteMigrationJob/main.go b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/PromoteMigrationJob/main.go index 2e640a3df83d..bfba4812d545 100644 --- a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/PromoteMigrationJob/main.go +++ b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/PromoteMigrationJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.PromoteMigrationJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/RestartMigrationJob/main.go b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/RestartMigrationJob/main.go index b785363528c4..484af8c87bf9 100644 --- a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/RestartMigrationJob/main.go +++ b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/RestartMigrationJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.RestartMigrationJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/ResumeMigrationJob/main.go b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/ResumeMigrationJob/main.go index d2715cdafd02..899f28736787 100644 --- a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/ResumeMigrationJob/main.go +++ b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/ResumeMigrationJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.ResumeMigrationJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/StartMigrationJob/main.go b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/StartMigrationJob/main.go index 25b7209be906..d68b87afccac 100644 --- a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/StartMigrationJob/main.go +++ b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/StartMigrationJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.StartMigrationJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/StopMigrationJob/main.go b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/StopMigrationJob/main.go index 4fbc969e3c09..e5b4f0153c57 100644 --- a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/StopMigrationJob/main.go +++ b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/StopMigrationJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.StopMigrationJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/UpdateConnectionProfile/main.go b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/UpdateConnectionProfile/main.go index 3e5e4e554e53..36fe55716d1b 100644 --- a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/UpdateConnectionProfile/main.go +++ b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/UpdateConnectionProfile/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.UpdateConnectionProfileRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/UpdateMigrationJob/main.go b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/UpdateMigrationJob/main.go index 69a5d9f79301..6a2f4de50c38 100644 --- a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/UpdateMigrationJob/main.go +++ b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/UpdateMigrationJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.UpdateMigrationJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/VerifyMigrationJob/main.go b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/VerifyMigrationJob/main.go index f7f7d67da3ec..815c417bd369 100644 --- a/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/VerifyMigrationJob/main.go +++ b/internal/generated/snippets/clouddms/apiv1/DataMigrationClient/VerifyMigrationJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddmspb "google.golang.org/genproto/googleapis/cloud/clouddms/v1" - ctx := context.Background() c, err := clouddms.NewDataMigrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddmspb.VerifyMigrationJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2/Client/CreateQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2/Client/CreateQueue/main.go index a4437152a11f..da721cb725e7 100644 --- a/internal/generated/snippets/cloudtasks/apiv2/Client/CreateQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2/Client/CreateQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.CreateQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2/Client/CreateTask/main.go b/internal/generated/snippets/cloudtasks/apiv2/Client/CreateTask/main.go index 0a642dddffd8..23e683e7f25e 100644 --- a/internal/generated/snippets/cloudtasks/apiv2/Client/CreateTask/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2/Client/CreateTask/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.CreateTaskRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2/Client/DeleteQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2/Client/DeleteQueue/main.go index a4fbf8157aa8..1a173c96a991 100644 --- a/internal/generated/snippets/cloudtasks/apiv2/Client/DeleteQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2/Client/DeleteQueue/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.DeleteQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2/Client/DeleteTask/main.go b/internal/generated/snippets/cloudtasks/apiv2/Client/DeleteTask/main.go index f6555c58f6d4..ca2526adb66d 100644 --- a/internal/generated/snippets/cloudtasks/apiv2/Client/DeleteTask/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2/Client/DeleteTask/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.DeleteTaskRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2/Client/GetIamPolicy/main.go b/internal/generated/snippets/cloudtasks/apiv2/Client/GetIamPolicy/main.go index 3d348b16f110..217171e99005 100644 --- a/internal/generated/snippets/cloudtasks/apiv2/Client/GetIamPolicy/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2/Client/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2/Client/GetQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2/Client/GetQueue/main.go index 689e9c8a9257..9a8c7533a518 100644 --- a/internal/generated/snippets/cloudtasks/apiv2/Client/GetQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2/Client/GetQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.GetQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2/Client/GetTask/main.go b/internal/generated/snippets/cloudtasks/apiv2/Client/GetTask/main.go index 35cabd28fc69..b34bc11743bc 100644 --- a/internal/generated/snippets/cloudtasks/apiv2/Client/GetTask/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2/Client/GetTask/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.GetTaskRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2/Client/ListQueues/main.go b/internal/generated/snippets/cloudtasks/apiv2/Client/ListQueues/main.go index 560fc3194e09..bbcadffed6e8 100644 --- a/internal/generated/snippets/cloudtasks/apiv2/Client/ListQueues/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2/Client/ListQueues/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ListQueuesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2/Client/ListTasks/main.go b/internal/generated/snippets/cloudtasks/apiv2/Client/ListTasks/main.go index f6570a6ea205..64145c4ba720 100644 --- a/internal/generated/snippets/cloudtasks/apiv2/Client/ListTasks/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2/Client/ListTasks/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ListTasksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2/Client/PauseQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2/Client/PauseQueue/main.go index cfaa7297c15b..da55f4a73dfc 100644 --- a/internal/generated/snippets/cloudtasks/apiv2/Client/PauseQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2/Client/PauseQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.PauseQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2/Client/PurgeQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2/Client/PurgeQueue/main.go index a6ae1503a50e..ecfa3577a84b 100644 --- a/internal/generated/snippets/cloudtasks/apiv2/Client/PurgeQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2/Client/PurgeQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.PurgeQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2/Client/ResumeQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2/Client/ResumeQueue/main.go index 5dff3597057f..3e66b8eb62f9 100644 --- a/internal/generated/snippets/cloudtasks/apiv2/Client/ResumeQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2/Client/ResumeQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ResumeQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2/Client/RunTask/main.go b/internal/generated/snippets/cloudtasks/apiv2/Client/RunTask/main.go index 8b0c788821e4..b8b23e2b63aa 100644 --- a/internal/generated/snippets/cloudtasks/apiv2/Client/RunTask/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2/Client/RunTask/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.RunTaskRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2/Client/SetIamPolicy/main.go b/internal/generated/snippets/cloudtasks/apiv2/Client/SetIamPolicy/main.go index c979bee6f9ce..59187b98a24f 100644 --- a/internal/generated/snippets/cloudtasks/apiv2/Client/SetIamPolicy/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2/Client/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2/Client/TestIamPermissions/main.go b/internal/generated/snippets/cloudtasks/apiv2/Client/TestIamPermissions/main.go index 3fb675bedb5a..44327b65cb10 100644 --- a/internal/generated/snippets/cloudtasks/apiv2/Client/TestIamPermissions/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2/Client/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2/Client/UpdateQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2/Client/UpdateQueue/main.go index 3585aefa0e03..9a15ec5b818c 100644 --- a/internal/generated/snippets/cloudtasks/apiv2/Client/UpdateQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2/Client/UpdateQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.UpdateQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/AcknowledgeTask/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/AcknowledgeTask/main.go index 49e03f4eb819..5bc0490b55e3 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/AcknowledgeTask/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/AcknowledgeTask/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.AcknowledgeTaskRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/CancelLease/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/CancelLease/main.go index ff870ca86017..58a700889d44 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/CancelLease/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/CancelLease/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.CancelLeaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/CreateQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/CreateQueue/main.go index 2ecf65cc15cf..29390419cab8 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/CreateQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/CreateQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.CreateQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/CreateTask/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/CreateTask/main.go index c35eb2dbf4b2..962ba9ad2fd9 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/CreateTask/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/CreateTask/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.CreateTaskRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/DeleteQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/DeleteQueue/main.go index 93b076e98f28..a4089b19ffdd 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/DeleteQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/DeleteQueue/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.DeleteQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/DeleteTask/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/DeleteTask/main.go index eb155084e36e..b7b5f37392fb 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/DeleteTask/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/DeleteTask/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.DeleteTaskRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/GetIamPolicy/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/GetIamPolicy/main.go index e2d62d85fdcc..38252026439c 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/GetIamPolicy/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/GetQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/GetQueue/main.go index 4a8466ae7799..4bed203254a2 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/GetQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/GetQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.GetQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/GetTask/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/GetTask/main.go index 7cbd2de9e1b6..9a5adc37a3a6 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/GetTask/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/GetTask/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.GetTaskRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/LeaseTasks/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/LeaseTasks/main.go index 32a7f8076652..db1a775b4c62 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/LeaseTasks/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/LeaseTasks/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.LeaseTasksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/ListQueues/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/ListQueues/main.go index ee25ba0d1e2a..abc998740a79 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/ListQueues/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/ListQueues/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ListQueuesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/ListTasks/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/ListTasks/main.go index 7942089f2795..537efd8036e6 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/ListTasks/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/ListTasks/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ListTasksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/PauseQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/PauseQueue/main.go index 6f94730f1694..7b3aa2c5b8c5 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/PauseQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/PauseQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.PauseQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/PurgeQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/PurgeQueue/main.go index 9d4083a618f3..d01b0f183171 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/PurgeQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/PurgeQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.PurgeQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/RenewLease/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/RenewLease/main.go index 0a79856ced87..baed52c32092 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/RenewLease/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/RenewLease/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.RenewLeaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/ResumeQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/ResumeQueue/main.go index f8298c6459eb..7e96bbd0046a 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/ResumeQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/ResumeQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ResumeQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/RunTask/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/RunTask/main.go index b51c7d43eeb9..5b644fbab481 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/RunTask/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/RunTask/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.RunTaskRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/SetIamPolicy/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/SetIamPolicy/main.go index b521dbd8cc8f..d9763e8a8633 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/SetIamPolicy/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/TestIamPermissions/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/TestIamPermissions/main.go index 4b5a8cd8a446..e76215303582 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/TestIamPermissions/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/UpdateQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/UpdateQueue/main.go index f774dd42e269..752618334eda 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta2/Client/UpdateQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta2/Client/UpdateQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta2" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.UpdateQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/CreateQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/CreateQueue/main.go index 8220d15fdd36..a5b043c56b87 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/CreateQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/CreateQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.CreateQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/CreateTask/main.go b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/CreateTask/main.go index c67f7f448de3..e876e7fc3b41 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/CreateTask/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/CreateTask/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.CreateTaskRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/DeleteQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/DeleteQueue/main.go index 5098d291af87..7c603b5b168b 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/DeleteQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/DeleteQueue/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.DeleteQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/DeleteTask/main.go b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/DeleteTask/main.go index b0477a85973c..2e43d5c089f3 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/DeleteTask/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/DeleteTask/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.DeleteTaskRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/GetIamPolicy/main.go b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/GetIamPolicy/main.go index 8d358fddcd6e..dcfb7ed7d828 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/GetIamPolicy/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/GetQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/GetQueue/main.go index 4e7268d87eb7..e2655967cecc 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/GetQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/GetQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.GetQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/GetTask/main.go b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/GetTask/main.go index 5265a7fde231..ce73d9687648 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/GetTask/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/GetTask/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.GetTaskRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/ListQueues/main.go b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/ListQueues/main.go index 58bcd00bc9f0..8fb2aa727b6e 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/ListQueues/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/ListQueues/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ListQueuesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/ListTasks/main.go b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/ListTasks/main.go index cf4b9f6a5c6b..8809e39dd1bf 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/ListTasks/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/ListTasks/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ListTasksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/PauseQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/PauseQueue/main.go index 2b67116d85d0..669702e84df9 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/PauseQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/PauseQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.PauseQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/PurgeQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/PurgeQueue/main.go index 2d1f279800e3..b334f841fc26 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/PurgeQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/PurgeQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.PurgeQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/ResumeQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/ResumeQueue/main.go index 90ccfab354d2..f8fbeb41c1cf 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/ResumeQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/ResumeQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.ResumeQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/RunTask/main.go b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/RunTask/main.go index dcac56dd9e72..9d517f2582e2 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/RunTask/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/RunTask/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.RunTaskRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/SetIamPolicy/main.go b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/SetIamPolicy/main.go index 192a3b4d9a1d..242afe0e30be 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/SetIamPolicy/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/TestIamPermissions/main.go b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/TestIamPermissions/main.go index dd7d0ca3c94d..7143c2b670d7 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/TestIamPermissions/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/UpdateQueue/main.go b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/UpdateQueue/main.go index 5576ff2b98a0..378f7f534c22 100644 --- a/internal/generated/snippets/cloudtasks/apiv2beta3/Client/UpdateQueue/main.go +++ b/internal/generated/snippets/cloudtasks/apiv2beta3/Client/UpdateQueue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2beta3" - ctx := context.Background() c, err := cloudtasks.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &taskspb.UpdateQueueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/CancelOperation/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/CancelOperation/main.go index f70b5899b74b..4e0c020dfa15 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/CancelOperation/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/CancelOperation/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.CancelOperationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/CompleteIPRotation/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/CompleteIPRotation/main.go index 739bcaa0d53b..61565819978e 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/CompleteIPRotation/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/CompleteIPRotation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.CompleteIPRotationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/CreateCluster/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/CreateCluster/main.go index da4bf9963478..f3abc0d8a0ed 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/CreateCluster/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/CreateCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.CreateClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/CreateNodePool/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/CreateNodePool/main.go index fbd474d3412e..928df9028875 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/CreateNodePool/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/CreateNodePool/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.CreateNodePoolRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/DeleteCluster/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/DeleteCluster/main.go index bf0bf5682bbb..1f5aaca3da86 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/DeleteCluster/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/DeleteCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.DeleteClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/DeleteNodePool/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/DeleteNodePool/main.go index 19b628fd6b50..e7a5097ff313 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/DeleteNodePool/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/DeleteNodePool/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.DeleteNodePoolRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetCluster/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetCluster/main.go index 2790c01b9534..b88bef543064 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetCluster/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.GetClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetJSONWebKeys/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetJSONWebKeys/main.go index 03ff2ebc0812..0b2d8cfde9d5 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetJSONWebKeys/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetJSONWebKeys/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.GetJSONWebKeysRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetNodePool/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetNodePool/main.go index 8d8e7a4264ae..bc1430dd040b 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetNodePool/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetNodePool/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.GetNodePoolRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetOperation/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetOperation/main.go index efcf2464275c..c987581e1c1c 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetOperation/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetOperation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.GetOperationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetServerConfig/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetServerConfig/main.go index a2fe4ad5200e..92e6fbfcc5d8 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetServerConfig/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/GetServerConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.GetServerConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/ListClusters/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/ListClusters/main.go index 599364cdd2e8..ff902ab0c9b9 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/ListClusters/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/ListClusters/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.ListClustersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/ListNodePools/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/ListNodePools/main.go index 05fe77730b5c..4536098c7a71 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/ListNodePools/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/ListNodePools/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.ListNodePoolsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/ListOperations/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/ListOperations/main.go index ea1807646754..882df8aa18ca 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/ListOperations/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/ListOperations/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.ListOperationsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/ListUsableSubnetworks/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/ListUsableSubnetworks/main.go index bf071f641ee6..513d5b59fd6c 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/ListUsableSubnetworks/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/ListUsableSubnetworks/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.ListUsableSubnetworksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/RollbackNodePoolUpgrade/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/RollbackNodePoolUpgrade/main.go index 6113829a4de0..4e6e1b0858e4 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/RollbackNodePoolUpgrade/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/RollbackNodePoolUpgrade/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.RollbackNodePoolUpgradeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetAddonsConfig/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetAddonsConfig/main.go index 5b7457ec7bb4..f78febdbd606 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetAddonsConfig/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetAddonsConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetAddonsConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetLabels/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetLabels/main.go index d882b7d8f910..ec12384d10b1 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetLabels/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetLabels/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetLabelsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetLegacyAbac/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetLegacyAbac/main.go index b377cee7fba6..5b54da31b3d5 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetLegacyAbac/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetLegacyAbac/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetLegacyAbacRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetLocations/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetLocations/main.go index 52cdfa144785..e0b09d03543f 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetLocations/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetLocations/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetLocationsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetLoggingService/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetLoggingService/main.go index 23ba0b76a12d..5890b318541d 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetLoggingService/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetLoggingService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetLoggingServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetMaintenancePolicy/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetMaintenancePolicy/main.go index c62a980e25df..b4f045435dd9 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetMaintenancePolicy/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetMaintenancePolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetMaintenancePolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetMasterAuth/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetMasterAuth/main.go index b48163b27574..fd681e872540 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetMasterAuth/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetMasterAuth/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetMasterAuthRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetMonitoringService/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetMonitoringService/main.go index 28a52fa38624..49888917c79e 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetMonitoringService/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetMonitoringService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetMonitoringServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetNetworkPolicy/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetNetworkPolicy/main.go index 5d22c09425ba..29f96b2e1004 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetNetworkPolicy/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetNetworkPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetNetworkPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetNodePoolAutoscaling/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetNodePoolAutoscaling/main.go index be6f930bb88c..9aa5dc386670 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetNodePoolAutoscaling/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetNodePoolAutoscaling/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetNodePoolAutoscalingRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetNodePoolManagement/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetNodePoolManagement/main.go index 78fb775a1473..4426db48d8d8 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetNodePoolManagement/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetNodePoolManagement/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetNodePoolManagementRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetNodePoolSize/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetNodePoolSize/main.go index fe35ba8b2931..753ae81a1f95 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetNodePoolSize/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/SetNodePoolSize/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.SetNodePoolSizeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/StartIPRotation/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/StartIPRotation/main.go index a2538e489e9e..2db3c13f4493 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/StartIPRotation/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/StartIPRotation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.StartIPRotationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/UpdateCluster/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/UpdateCluster/main.go index 885f24402fec..3aad12e68e8b 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/UpdateCluster/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/UpdateCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.UpdateClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/UpdateMaster/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/UpdateMaster/main.go index 5e2fdb56524f..fe5443976f0a 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/UpdateMaster/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/UpdateMaster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.UpdateMasterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/container/apiv1/ClusterManagerClient/UpdateNodePool/main.go b/internal/generated/snippets/container/apiv1/ClusterManagerClient/UpdateNodePool/main.go index f16896730515..e1d3cc9603ab 100644 --- a/internal/generated/snippets/container/apiv1/ClusterManagerClient/UpdateNodePool/main.go +++ b/internal/generated/snippets/container/apiv1/ClusterManagerClient/UpdateNodePool/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import containerpb "google.golang.org/genproto/googleapis/container/v1" - ctx := context.Background() c, err := container.NewClusterManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &containerpb.UpdateNodePoolRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/BatchCreateNotes/main.go b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/BatchCreateNotes/main.go index 91c656b84d10..758a9f2be815 100644 --- a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/BatchCreateNotes/main.go +++ b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/BatchCreateNotes/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.BatchCreateNotesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/BatchCreateOccurrences/main.go b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/BatchCreateOccurrences/main.go index 88b10fedd495..0576adf3a547 100644 --- a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/BatchCreateOccurrences/main.go +++ b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/BatchCreateOccurrences/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.BatchCreateOccurrencesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/CreateNote/main.go b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/CreateNote/main.go index 79d192229427..7008d0b2eb66 100644 --- a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/CreateNote/main.go +++ b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/CreateNote/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.CreateNoteRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/CreateOccurrence/main.go b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/CreateOccurrence/main.go index 2237a54d2843..1d1f6a912ac7 100644 --- a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/CreateOccurrence/main.go +++ b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/CreateOccurrence/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.CreateOccurrenceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/DeleteNote/main.go b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/DeleteNote/main.go index d4af6d512a1c..80f69e1b359f 100644 --- a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/DeleteNote/main.go +++ b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/DeleteNote/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.DeleteNoteRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/DeleteOccurrence/main.go b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/DeleteOccurrence/main.go index bb6faf7a25fb..d59eb1d516b6 100644 --- a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/DeleteOccurrence/main.go +++ b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/DeleteOccurrence/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.DeleteOccurrenceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/GetNote/main.go b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/GetNote/main.go index 6b974219c3e7..33247620d9c2 100644 --- a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/GetNote/main.go +++ b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/GetNote/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.GetNoteRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/GetOccurrence/main.go b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/GetOccurrence/main.go index 1bdfb9244b2b..cab1b245cf91 100644 --- a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/GetOccurrence/main.go +++ b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/GetOccurrence/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.GetOccurrenceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/GetOccurrenceNote/main.go b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/GetOccurrenceNote/main.go index b2a213ce0c69..af3d46be657e 100644 --- a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/GetOccurrenceNote/main.go +++ b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/GetOccurrenceNote/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.GetOccurrenceNoteRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/GetVulnerabilityOccurrencesSummary/main.go b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/GetVulnerabilityOccurrencesSummary/main.go index 4e1b37480bda..e1e86bd35df6 100644 --- a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/GetVulnerabilityOccurrencesSummary/main.go +++ b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/GetVulnerabilityOccurrencesSummary/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.GetVulnerabilityOccurrencesSummaryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/ListNoteOccurrences/main.go b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/ListNoteOccurrences/main.go index d9dfbf0457cf..75c2c43dd512 100644 --- a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/ListNoteOccurrences/main.go +++ b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/ListNoteOccurrences/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.ListNoteOccurrencesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/ListNotes/main.go b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/ListNotes/main.go index d4be57eaf757..7dc395a481b8 100644 --- a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/ListNotes/main.go +++ b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/ListNotes/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.ListNotesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/ListOccurrences/main.go b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/ListOccurrences/main.go index c4a6c6aaf266..d07ab2b05aad 100644 --- a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/ListOccurrences/main.go +++ b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/ListOccurrences/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.ListOccurrencesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/UpdateNote/main.go b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/UpdateNote/main.go index 271ddbaab54b..a58961f28f24 100644 --- a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/UpdateNote/main.go +++ b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/UpdateNote/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.UpdateNoteRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/UpdateOccurrence/main.go b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/UpdateOccurrence/main.go index ac1e5518b531..7ad09dfcbdfd 100644 --- a/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/UpdateOccurrence/main.go +++ b/internal/generated/snippets/containeranalysis/apiv1beta1/GrafeasV1Beta1Client/UpdateOccurrence/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import grafeaspb "google.golang.org/genproto/googleapis/devtools/containeranalysis/v1beta1/grafeas" - ctx := context.Background() c, err := containeranalysis.NewGrafeasV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &grafeaspb.UpdateOccurrenceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/CreateEntry/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/CreateEntry/main.go index a3c1dc906c64..5c87ba7e5154 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/CreateEntry/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/CreateEntry/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateEntryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/CreateEntryGroup/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/CreateEntryGroup/main.go index a5e4ffaba8c5..3052eda8429f 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/CreateEntryGroup/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/CreateEntryGroup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateEntryGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/CreateTag/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/CreateTag/main.go index e4365efdbdb7..7722e2d47ddd 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/CreateTag/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/CreateTag/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/CreateTagTemplate/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/CreateTagTemplate/main.go index 5ce2a175ec3d..f0fa72cd78f1 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/CreateTagTemplate/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/CreateTagTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateTagTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/CreateTagTemplateField/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/CreateTagTemplateField/main.go index 176c1b0763f5..1f3b5da43d3c 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/CreateTagTemplateField/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/CreateTagTemplateField/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateTagTemplateFieldRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/DeleteEntry/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/DeleteEntry/main.go index f2c8b0dc0733..dc2383bdbe1f 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/DeleteEntry/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/DeleteEntry/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteEntryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/DeleteEntryGroup/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/DeleteEntryGroup/main.go index 797c6018a6c5..dd4abfe0ebf2 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/DeleteEntryGroup/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/DeleteEntryGroup/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteEntryGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/DeleteTag/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/DeleteTag/main.go index fe794d32d9e4..549a1cb01ab8 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/DeleteTag/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/DeleteTag/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/DeleteTagTemplate/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/DeleteTagTemplate/main.go index b2c7b20eb763..fbdbff043b10 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/DeleteTagTemplate/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/DeleteTagTemplate/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteTagTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/DeleteTagTemplateField/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/DeleteTagTemplateField/main.go index 765f0174ed9a..a44f5e11aa47 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/DeleteTagTemplateField/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/DeleteTagTemplateField/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteTagTemplateFieldRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/GetEntry/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/GetEntry/main.go index 19115e76e13c..68c5f5ce640a 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/GetEntry/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/GetEntry/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetEntryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/GetEntryGroup/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/GetEntryGroup/main.go index 574aded9e4d1..93e2cfd05b50 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/GetEntryGroup/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/GetEntryGroup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetEntryGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/GetIamPolicy/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/GetIamPolicy/main.go index 52d337d0fc7c..6034c75896ba 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/GetIamPolicy/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/GetTagTemplate/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/GetTagTemplate/main.go index cb8e53630c72..268ff91f56fa 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/GetTagTemplate/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/GetTagTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetTagTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/ListEntries/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/ListEntries/main.go index 712d024144fb..96f14292c061 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/ListEntries/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/ListEntries/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListEntriesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/ListEntryGroups/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/ListEntryGroups/main.go index 3ec9ccd78ba9..39b233c748ae 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/ListEntryGroups/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/ListEntryGroups/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListEntryGroupsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/ListTags/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/ListTags/main.go index bf1468b21d42..5a8db363cd96 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/ListTags/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/ListTags/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListTagsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/LookupEntry/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/LookupEntry/main.go index 1d03f6e6ad79..5b7952d2f1db 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/LookupEntry/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/LookupEntry/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.LookupEntryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/RenameTagTemplateField/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/RenameTagTemplateField/main.go index f65a9316aace..0ad16303b8c0 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/RenameTagTemplateField/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/RenameTagTemplateField/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.RenameTagTemplateFieldRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/RenameTagTemplateFieldEnumValue/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/RenameTagTemplateFieldEnumValue/main.go index 69d766781e67..d48e18f51207 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/RenameTagTemplateFieldEnumValue/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/RenameTagTemplateFieldEnumValue/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.RenameTagTemplateFieldEnumValueRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/SearchCatalog/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/SearchCatalog/main.go index d9a4feedf477..de5421d6e06a 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/SearchCatalog/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/SearchCatalog/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.SearchCatalogRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/SetIamPolicy/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/SetIamPolicy/main.go index 8026f4e230d4..cd70e7398693 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/SetIamPolicy/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/TestIamPermissions/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/TestIamPermissions/main.go index 3209fe812751..e34fefedb7e5 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/TestIamPermissions/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/UpdateEntry/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/UpdateEntry/main.go index 1951f8f9dcf0..bb5036d256b6 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/UpdateEntry/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/UpdateEntry/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateEntryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/UpdateEntryGroup/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/UpdateEntryGroup/main.go index ea900462ef1c..ec05df0e3e4a 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/UpdateEntryGroup/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/UpdateEntryGroup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateEntryGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/UpdateTag/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/UpdateTag/main.go index bb333fa164a3..7d9f7980ce56 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/UpdateTag/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/UpdateTag/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/UpdateTagTemplate/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/UpdateTagTemplate/main.go index 75051a4e4a88..416c04e28f4f 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/UpdateTagTemplate/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/UpdateTagTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateTagTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/Client/UpdateTagTemplateField/main.go b/internal/generated/snippets/datacatalog/apiv1/Client/UpdateTagTemplateField/main.go index defef4c7e900..f7c909a81102 100644 --- a/internal/generated/snippets/datacatalog/apiv1/Client/UpdateTagTemplateField/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/Client/UpdateTagTemplateField/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateTagTemplateFieldRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/CreatePolicyTag/main.go b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/CreatePolicyTag/main.go index 0460a48db9b9..4c2ab4adc9e7 100644 --- a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/CreatePolicyTag/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/CreatePolicyTag/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreatePolicyTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/CreateTaxonomy/main.go b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/CreateTaxonomy/main.go index ebbb3bd95f2e..e3d781a73b88 100644 --- a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/CreateTaxonomy/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/CreateTaxonomy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateTaxonomyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/DeletePolicyTag/main.go b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/DeletePolicyTag/main.go index 1aa198055cd9..5e49211d5e0b 100644 --- a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/DeletePolicyTag/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/DeletePolicyTag/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeletePolicyTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/DeleteTaxonomy/main.go b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/DeleteTaxonomy/main.go index 87791c808a16..f29cde5e2e9d 100644 --- a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/DeleteTaxonomy/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/DeleteTaxonomy/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteTaxonomyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/GetIamPolicy/main.go b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/GetIamPolicy/main.go index 19614a0282f2..5f2899397029 100644 --- a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/GetIamPolicy/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/GetPolicyTag/main.go b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/GetPolicyTag/main.go index c419bbbb687a..d651c5448349 100644 --- a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/GetPolicyTag/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/GetPolicyTag/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetPolicyTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/GetTaxonomy/main.go b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/GetTaxonomy/main.go index d44d15d35f61..ce0646fee601 100644 --- a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/GetTaxonomy/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/GetTaxonomy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetTaxonomyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/ListPolicyTags/main.go b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/ListPolicyTags/main.go index 78f50c137f73..095804826570 100644 --- a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/ListPolicyTags/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/ListPolicyTags/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListPolicyTagsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/ListTaxonomies/main.go b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/ListTaxonomies/main.go index b882963dd236..40478fc18677 100644 --- a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/ListTaxonomies/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/ListTaxonomies/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListTaxonomiesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/SetIamPolicy/main.go b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/SetIamPolicy/main.go index 1042820c9827..00811e23d293 100644 --- a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/SetIamPolicy/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/TestIamPermissions/main.go b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/TestIamPermissions/main.go index 234c2d6ba620..0f66f4bba163 100644 --- a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/TestIamPermissions/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/UpdatePolicyTag/main.go b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/UpdatePolicyTag/main.go index 46a86900c739..f2b05a23497b 100644 --- a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/UpdatePolicyTag/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/UpdatePolicyTag/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdatePolicyTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/UpdateTaxonomy/main.go b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/UpdateTaxonomy/main.go index 3188761d27db..9b34c495934e 100644 --- a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/UpdateTaxonomy/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerClient/UpdateTaxonomy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateTaxonomyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerSerializationClient/ExportTaxonomies/main.go b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerSerializationClient/ExportTaxonomies/main.go index d2e517f72c20..a16643334b4a 100644 --- a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerSerializationClient/ExportTaxonomies/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerSerializationClient/ExportTaxonomies/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerSerializationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ExportTaxonomiesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerSerializationClient/ImportTaxonomies/main.go b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerSerializationClient/ImportTaxonomies/main.go index a771b6d2ac0e..9d88b9b45234 100644 --- a/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerSerializationClient/ImportTaxonomies/main.go +++ b/internal/generated/snippets/datacatalog/apiv1/PolicyTagManagerSerializationClient/ImportTaxonomies/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerSerializationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ImportTaxonomiesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateEntry/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateEntry/main.go index 611a2d0b8556..2c87b8fab5d3 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateEntry/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateEntry/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateEntryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateEntryGroup/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateEntryGroup/main.go index aaeb05025d67..23e6b33096b5 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateEntryGroup/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateEntryGroup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateEntryGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateTag/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateTag/main.go index 8e102c2da884..0536ab4a3db8 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateTag/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateTag/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateTagTemplate/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateTagTemplate/main.go index 766863b00628..e6a0b2447a51 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateTagTemplate/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateTagTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateTagTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateTagTemplateField/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateTagTemplateField/main.go index d9fdacf4f9e5..4c58a75b0a5a 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateTagTemplateField/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/CreateTagTemplateField/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateTagTemplateFieldRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteEntry/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteEntry/main.go index 0c57c44272f2..ac0fa99a68a1 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteEntry/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteEntry/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteEntryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteEntryGroup/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteEntryGroup/main.go index ad7ac0c5d470..3f42f632baef 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteEntryGroup/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteEntryGroup/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteEntryGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteTag/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteTag/main.go index eaee889ee42c..1719e17c61dc 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteTag/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteTag/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteTagTemplate/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteTagTemplate/main.go index 75a5bf30937d..8664382cac84 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteTagTemplate/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteTagTemplate/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteTagTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteTagTemplateField/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteTagTemplateField/main.go index 27c7e9055970..1f18f52a5d35 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteTagTemplateField/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/DeleteTagTemplateField/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteTagTemplateFieldRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/GetEntry/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/GetEntry/main.go index 9d56c101faa9..0dcd8e14ad09 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/GetEntry/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/GetEntry/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetEntryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/GetEntryGroup/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/GetEntryGroup/main.go index 7ce0befaaacd..d3bd78864ef5 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/GetEntryGroup/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/GetEntryGroup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetEntryGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/GetIamPolicy/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/GetIamPolicy/main.go index 11cb9328bf6a..5df59ff1a7fb 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/GetIamPolicy/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/GetTagTemplate/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/GetTagTemplate/main.go index 8bd493a2b691..508a2d356d2c 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/GetTagTemplate/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/GetTagTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetTagTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/ListEntries/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/ListEntries/main.go index 6dedcba3c5e0..942cbff62725 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/ListEntries/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/ListEntries/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListEntriesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/ListEntryGroups/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/ListEntryGroups/main.go index 25ce077a3dc9..4f2a59273f17 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/ListEntryGroups/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/ListEntryGroups/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListEntryGroupsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/ListTags/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/ListTags/main.go index 9f281c3550fb..b6b673f68516 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/ListTags/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/ListTags/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListTagsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/LookupEntry/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/LookupEntry/main.go index 0dd34133b4b7..1cc46583d967 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/LookupEntry/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/LookupEntry/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.LookupEntryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/RenameTagTemplateField/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/RenameTagTemplateField/main.go index 523f065a4b59..9cb603f2b8d8 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/RenameTagTemplateField/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/RenameTagTemplateField/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.RenameTagTemplateFieldRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/SearchCatalog/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/SearchCatalog/main.go index 9e4dfa47cd3e..5a4ed2c0ca89 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/SearchCatalog/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/SearchCatalog/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.SearchCatalogRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/SetIamPolicy/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/SetIamPolicy/main.go index c13cd4b763e0..e4610a2c0829 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/SetIamPolicy/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/TestIamPermissions/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/TestIamPermissions/main.go index 136cddb14360..b7c04ded4398 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/TestIamPermissions/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateEntry/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateEntry/main.go index 8bbc857270ab..29dddc993325 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateEntry/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateEntry/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateEntryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateEntryGroup/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateEntryGroup/main.go index 017d4bc9cc4b..38ad4ee1503e 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateEntryGroup/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateEntryGroup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateEntryGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateTag/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateTag/main.go index 32297eddeb2f..9a3d6e9f87a8 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateTag/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateTag/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateTagTemplate/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateTagTemplate/main.go index 3548f370b31f..5ad54e5d1c8c 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateTagTemplate/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateTagTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateTagTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateTagTemplateField/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateTagTemplateField/main.go index eb3a757cc862..0f55edd4e840 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateTagTemplateField/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/Client/UpdateTagTemplateField/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateTagTemplateFieldRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/CreatePolicyTag/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/CreatePolicyTag/main.go index 9d72ab9689ed..c7b692f4a29b 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/CreatePolicyTag/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/CreatePolicyTag/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreatePolicyTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/CreateTaxonomy/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/CreateTaxonomy/main.go index 0979759d1dd3..6a0a02f9212e 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/CreateTaxonomy/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/CreateTaxonomy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.CreateTaxonomyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/DeletePolicyTag/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/DeletePolicyTag/main.go index 9f7862c8e7ed..1111a5155003 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/DeletePolicyTag/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/DeletePolicyTag/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeletePolicyTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/DeleteTaxonomy/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/DeleteTaxonomy/main.go index f6aacb2842fd..a7ddf53fbca8 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/DeleteTaxonomy/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/DeleteTaxonomy/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.DeleteTaxonomyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/GetIamPolicy/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/GetIamPolicy/main.go index 1b37dea6e5c5..9e07a1a238a5 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/GetIamPolicy/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/GetPolicyTag/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/GetPolicyTag/main.go index 94ca71d84b4e..a48be20ea322 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/GetPolicyTag/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/GetPolicyTag/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetPolicyTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/GetTaxonomy/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/GetTaxonomy/main.go index 5ded5a8f04f7..e2f406190b0c 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/GetTaxonomy/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/GetTaxonomy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.GetTaxonomyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/ListPolicyTags/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/ListPolicyTags/main.go index fa402ab5c57b..57e712ef3c04 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/ListPolicyTags/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/ListPolicyTags/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListPolicyTagsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/ListTaxonomies/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/ListTaxonomies/main.go index adf6e058f028..e6ea88721063 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/ListTaxonomies/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/ListTaxonomies/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ListTaxonomiesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/SetIamPolicy/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/SetIamPolicy/main.go index 9b96d3b2757d..1c19e2464735 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/SetIamPolicy/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/TestIamPermissions/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/TestIamPermissions/main.go index 51d4717296e3..74445fd193c9 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/TestIamPermissions/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/UpdatePolicyTag/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/UpdatePolicyTag/main.go index 7cb18d02978a..1802a149a730 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/UpdatePolicyTag/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/UpdatePolicyTag/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdatePolicyTagRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/UpdateTaxonomy/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/UpdateTaxonomy/main.go index def78a9dd678..b5a92f5ee94f 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/UpdateTaxonomy/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerClient/UpdateTaxonomy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.UpdateTaxonomyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerSerializationClient/ExportTaxonomies/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerSerializationClient/ExportTaxonomies/main.go index 2286cc49d740..9b5122c29893 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerSerializationClient/ExportTaxonomies/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerSerializationClient/ExportTaxonomies/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerSerializationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ExportTaxonomiesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerSerializationClient/ImportTaxonomies/main.go b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerSerializationClient/ImportTaxonomies/main.go index a5d1270c90b9..f0ad9f2ee536 100644 --- a/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerSerializationClient/ImportTaxonomies/main.go +++ b/internal/generated/snippets/datacatalog/apiv1beta1/PolicyTagManagerSerializationClient/ImportTaxonomies/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1beta1" - ctx := context.Background() c, err := datacatalog.NewPolicyTagManagerSerializationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datacatalogpb.ImportTaxonomiesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/CreateAnnotationSpecSet/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/CreateAnnotationSpecSet/main.go index d8922650ee78..86db731571a2 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/CreateAnnotationSpecSet/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/CreateAnnotationSpecSet/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.CreateAnnotationSpecSetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/CreateDataset/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/CreateDataset/main.go index 4f65de48ca27..78df3ff82855 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/CreateDataset/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/CreateDataset/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.CreateDatasetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/CreateEvaluationJob/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/CreateEvaluationJob/main.go index 356e4d2e4186..f3da4c869944 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/CreateEvaluationJob/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/CreateEvaluationJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.CreateEvaluationJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/CreateInstruction/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/CreateInstruction/main.go index e040495cf8c4..554282e4d20e 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/CreateInstruction/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/CreateInstruction/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.CreateInstructionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteAnnotatedDataset/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteAnnotatedDataset/main.go index a23ca5a08d5c..2db566981181 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteAnnotatedDataset/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteAnnotatedDataset/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.DeleteAnnotatedDatasetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteAnnotationSpecSet/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteAnnotationSpecSet/main.go index db56f9a43b3a..f236a6de90fa 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteAnnotationSpecSet/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteAnnotationSpecSet/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.DeleteAnnotationSpecSetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteDataset/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteDataset/main.go index 99504698904f..16c396698a21 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteDataset/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteDataset/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.DeleteDatasetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteEvaluationJob/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteEvaluationJob/main.go index a19247ea8b6c..110b891a31ed 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteEvaluationJob/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteEvaluationJob/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.DeleteEvaluationJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteInstruction/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteInstruction/main.go index 5f86c6894d17..aade4cbad999 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteInstruction/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/DeleteInstruction/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.DeleteInstructionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ExportData/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ExportData/main.go index 5091e44b6b6a..4e5161fc740e 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ExportData/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ExportData/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ExportDataRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetAnnotatedDataset/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetAnnotatedDataset/main.go index f8c57aeb2ea7..cf64c3a5f257 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetAnnotatedDataset/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetAnnotatedDataset/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.GetAnnotatedDatasetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetAnnotationSpecSet/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetAnnotationSpecSet/main.go index c11b642ef12a..b14db4e6ccae 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetAnnotationSpecSet/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetAnnotationSpecSet/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.GetAnnotationSpecSetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetDataItem/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetDataItem/main.go index aa62c3638e14..dc1f14c60f06 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetDataItem/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetDataItem/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.GetDataItemRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetDataset/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetDataset/main.go index 05552a552a29..050212a421e1 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetDataset/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetDataset/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.GetDatasetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetEvaluation/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetEvaluation/main.go index bcc8b6b5631d..7f592f5a9b46 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetEvaluation/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetEvaluation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.GetEvaluationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetEvaluationJob/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetEvaluationJob/main.go index 2d02e47b98c6..445e1b5820f1 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetEvaluationJob/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetEvaluationJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.GetEvaluationJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetExample/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetExample/main.go index 5c1e8664e841..ac98c0148883 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetExample/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetExample/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.GetExampleRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetInstruction/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetInstruction/main.go index 7a710e99d1f9..848733ed8257 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetInstruction/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/GetInstruction/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.GetInstructionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ImportData/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ImportData/main.go index 4a8097df55ef..7f5f0b79784c 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ImportData/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ImportData/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ImportDataRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/LabelImage/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/LabelImage/main.go index ecf130ce7695..6b944015725a 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/LabelImage/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/LabelImage/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.LabelImageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/LabelText/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/LabelText/main.go index 70eb8bbc75dc..8b64f833be4d 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/LabelText/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/LabelText/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.LabelTextRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/LabelVideo/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/LabelVideo/main.go index 4615af65d9c8..dfb14d8362bf 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/LabelVideo/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/LabelVideo/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.LabelVideoRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListAnnotatedDatasets/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListAnnotatedDatasets/main.go index cb74b708add0..0985c1a8c50e 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListAnnotatedDatasets/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListAnnotatedDatasets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ListAnnotatedDatasetsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListAnnotationSpecSets/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListAnnotationSpecSets/main.go index 03c4be87f5b2..bba9a1907555 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListAnnotationSpecSets/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListAnnotationSpecSets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ListAnnotationSpecSetsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListDataItems/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListDataItems/main.go index eebde4cc8f27..2ec072f28a25 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListDataItems/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListDataItems/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ListDataItemsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListDatasets/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListDatasets/main.go index 29a39a690467..fbe69e44c5c5 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListDatasets/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListDatasets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ListDatasetsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListEvaluationJobs/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListEvaluationJobs/main.go index 38bd598da64d..c0d8f52d8c94 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListEvaluationJobs/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListEvaluationJobs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ListEvaluationJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListExamples/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListExamples/main.go index bbcfd75508f4..692751a7b6e5 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListExamples/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListExamples/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ListExamplesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListInstructions/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListInstructions/main.go index 5ad680ac69f1..3df4a40b85d0 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListInstructions/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ListInstructions/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ListInstructionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/PauseEvaluationJob/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/PauseEvaluationJob/main.go index dc0f4ef37e79..6a31c0722f23 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/PauseEvaluationJob/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/PauseEvaluationJob/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.PauseEvaluationJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ResumeEvaluationJob/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ResumeEvaluationJob/main.go index b5d118f5e36c..a35530bc6124 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/ResumeEvaluationJob/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/ResumeEvaluationJob/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.ResumeEvaluationJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/SearchEvaluations/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/SearchEvaluations/main.go index 9f7fdc6e167a..408014e35df3 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/SearchEvaluations/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/SearchEvaluations/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.SearchEvaluationsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/SearchExampleComparisons/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/SearchExampleComparisons/main.go index 7a95811745de..35445828c7fa 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/SearchExampleComparisons/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/SearchExampleComparisons/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.SearchExampleComparisonsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datalabeling/apiv1beta1/Client/UpdateEvaluationJob/main.go b/internal/generated/snippets/datalabeling/apiv1beta1/Client/UpdateEvaluationJob/main.go index a6556720c1b4..eba80db6e751 100644 --- a/internal/generated/snippets/datalabeling/apiv1beta1/Client/UpdateEvaluationJob/main.go +++ b/internal/generated/snippets/datalabeling/apiv1beta1/Client/UpdateEvaluationJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import datalabelingpb "google.golang.org/genproto/googleapis/cloud/datalabeling/v1beta1" - ctx := context.Background() c, err := datalabeling.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &datalabelingpb.UpdateEvaluationJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/CreateAutoscalingPolicy/main.go b/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/CreateAutoscalingPolicy/main.go index bf7f8bef21e4..e47504c6b53a 100644 --- a/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/CreateAutoscalingPolicy/main.go +++ b/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/CreateAutoscalingPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewAutoscalingPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.CreateAutoscalingPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/DeleteAutoscalingPolicy/main.go b/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/DeleteAutoscalingPolicy/main.go index 3287e9618c6a..9a4e8d261330 100644 --- a/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/DeleteAutoscalingPolicy/main.go +++ b/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/DeleteAutoscalingPolicy/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DeleteAutoscalingPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/GetAutoscalingPolicy/main.go b/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/GetAutoscalingPolicy/main.go index d4fdf2341ed1..0cdebf9de185 100644 --- a/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/GetAutoscalingPolicy/main.go +++ b/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/GetAutoscalingPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewAutoscalingPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.GetAutoscalingPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/ListAutoscalingPolicies/main.go b/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/ListAutoscalingPolicies/main.go index cbb0ef22e9c2..213f4667a9e7 100644 --- a/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/ListAutoscalingPolicies/main.go +++ b/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/ListAutoscalingPolicies/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dataproc.NewAutoscalingPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.ListAutoscalingPoliciesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/UpdateAutoscalingPolicy/main.go b/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/UpdateAutoscalingPolicy/main.go index e6aefb14a2c4..e140749e7cfa 100644 --- a/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/UpdateAutoscalingPolicy/main.go +++ b/internal/generated/snippets/dataproc/apiv1/AutoscalingPolicyClient/UpdateAutoscalingPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewAutoscalingPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.UpdateAutoscalingPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/CreateCluster/main.go b/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/CreateCluster/main.go index e09eee1fa5c7..4600f5033a51 100644 --- a/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/CreateCluster/main.go +++ b/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/CreateCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.CreateClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/DeleteCluster/main.go b/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/DeleteCluster/main.go index f8ebe5c913e8..f543dd269fb4 100644 --- a/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/DeleteCluster/main.go +++ b/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/DeleteCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DeleteClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/DiagnoseCluster/main.go b/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/DiagnoseCluster/main.go index 5724cdd8b62e..58a40d4991eb 100644 --- a/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/DiagnoseCluster/main.go +++ b/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/DiagnoseCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DiagnoseClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/GetCluster/main.go b/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/GetCluster/main.go index 9a62e872ceb8..7085c4ab4f4e 100644 --- a/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/GetCluster/main.go +++ b/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/GetCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.GetClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/ListClusters/main.go b/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/ListClusters/main.go index 367ffa487e0a..a51507d68f78 100644 --- a/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/ListClusters/main.go +++ b/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/ListClusters/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.ListClustersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/StartCluster/main.go b/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/StartCluster/main.go index 57fcdb5c004b..1ffc76ea31f5 100644 --- a/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/StartCluster/main.go +++ b/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/StartCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.StartClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/StopCluster/main.go b/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/StopCluster/main.go index 5d03a689cb92..7c9a04e70bcd 100644 --- a/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/StopCluster/main.go +++ b/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/StopCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.StopClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/UpdateCluster/main.go b/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/UpdateCluster/main.go index f446e0a6a712..3369ff2f879a 100644 --- a/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/UpdateCluster/main.go +++ b/internal/generated/snippets/dataproc/apiv1/ClusterControllerClient/UpdateCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.UpdateClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/JobControllerClient/CancelJob/main.go b/internal/generated/snippets/dataproc/apiv1/JobControllerClient/CancelJob/main.go index 4d991a310731..2576a3cc2c3e 100644 --- a/internal/generated/snippets/dataproc/apiv1/JobControllerClient/CancelJob/main.go +++ b/internal/generated/snippets/dataproc/apiv1/JobControllerClient/CancelJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.CancelJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/JobControllerClient/DeleteJob/main.go b/internal/generated/snippets/dataproc/apiv1/JobControllerClient/DeleteJob/main.go index 1f663d52aaaf..2e86947ac071 100644 --- a/internal/generated/snippets/dataproc/apiv1/JobControllerClient/DeleteJob/main.go +++ b/internal/generated/snippets/dataproc/apiv1/JobControllerClient/DeleteJob/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DeleteJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/JobControllerClient/GetJob/main.go b/internal/generated/snippets/dataproc/apiv1/JobControllerClient/GetJob/main.go index e16b69884d10..a4c47ff5dae1 100644 --- a/internal/generated/snippets/dataproc/apiv1/JobControllerClient/GetJob/main.go +++ b/internal/generated/snippets/dataproc/apiv1/JobControllerClient/GetJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.GetJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/JobControllerClient/ListJobs/main.go b/internal/generated/snippets/dataproc/apiv1/JobControllerClient/ListJobs/main.go index 79eb506a6b14..88f53ee51fff 100644 --- a/internal/generated/snippets/dataproc/apiv1/JobControllerClient/ListJobs/main.go +++ b/internal/generated/snippets/dataproc/apiv1/JobControllerClient/ListJobs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.ListJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/JobControllerClient/SubmitJob/main.go b/internal/generated/snippets/dataproc/apiv1/JobControllerClient/SubmitJob/main.go index 2580d3acb126..54ced7a8d754 100644 --- a/internal/generated/snippets/dataproc/apiv1/JobControllerClient/SubmitJob/main.go +++ b/internal/generated/snippets/dataproc/apiv1/JobControllerClient/SubmitJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.SubmitJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/JobControllerClient/SubmitJobAsOperation/main.go b/internal/generated/snippets/dataproc/apiv1/JobControllerClient/SubmitJobAsOperation/main.go index 2d47584dadbc..17dd9850c2c0 100644 --- a/internal/generated/snippets/dataproc/apiv1/JobControllerClient/SubmitJobAsOperation/main.go +++ b/internal/generated/snippets/dataproc/apiv1/JobControllerClient/SubmitJobAsOperation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.SubmitJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/JobControllerClient/UpdateJob/main.go b/internal/generated/snippets/dataproc/apiv1/JobControllerClient/UpdateJob/main.go index 54dfdb31777a..9b4623bf482a 100644 --- a/internal/generated/snippets/dataproc/apiv1/JobControllerClient/UpdateJob/main.go +++ b/internal/generated/snippets/dataproc/apiv1/JobControllerClient/UpdateJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.UpdateJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/CreateWorkflowTemplate/main.go b/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/CreateWorkflowTemplate/main.go index 9df90139e0a9..8f0446595491 100644 --- a/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/CreateWorkflowTemplate/main.go +++ b/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/CreateWorkflowTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.CreateWorkflowTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/DeleteWorkflowTemplate/main.go b/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/DeleteWorkflowTemplate/main.go index 2ab5740c430b..531c27354b6a 100644 --- a/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/DeleteWorkflowTemplate/main.go +++ b/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/DeleteWorkflowTemplate/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DeleteWorkflowTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/GetWorkflowTemplate/main.go b/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/GetWorkflowTemplate/main.go index 18c0da652f2c..004689d4a346 100644 --- a/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/GetWorkflowTemplate/main.go +++ b/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/GetWorkflowTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.GetWorkflowTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/InstantiateInlineWorkflowTemplate/main.go b/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/InstantiateInlineWorkflowTemplate/main.go index 470403d28b38..ab9f80bbbeaa 100644 --- a/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/InstantiateInlineWorkflowTemplate/main.go +++ b/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/InstantiateInlineWorkflowTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.InstantiateInlineWorkflowTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/InstantiateWorkflowTemplate/main.go b/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/InstantiateWorkflowTemplate/main.go index c9e6d2805710..719027c5d222 100644 --- a/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/InstantiateWorkflowTemplate/main.go +++ b/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/InstantiateWorkflowTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.InstantiateWorkflowTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/ListWorkflowTemplates/main.go b/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/ListWorkflowTemplates/main.go index a0e3a5ab5d42..00085ea82f1c 100644 --- a/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/ListWorkflowTemplates/main.go +++ b/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/ListWorkflowTemplates/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.ListWorkflowTemplatesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/UpdateWorkflowTemplate/main.go b/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/UpdateWorkflowTemplate/main.go index 3be70293e1ac..bc43c9cf7667 100644 --- a/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/UpdateWorkflowTemplate/main.go +++ b/internal/generated/snippets/dataproc/apiv1/WorkflowTemplateClient/UpdateWorkflowTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.UpdateWorkflowTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/CreateAutoscalingPolicy/main.go b/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/CreateAutoscalingPolicy/main.go index a46213fe1ce9..b713b8dac631 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/CreateAutoscalingPolicy/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/CreateAutoscalingPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewAutoscalingPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.CreateAutoscalingPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/DeleteAutoscalingPolicy/main.go b/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/DeleteAutoscalingPolicy/main.go index 48ac739ec761..d0a49e098766 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/DeleteAutoscalingPolicy/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/DeleteAutoscalingPolicy/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DeleteAutoscalingPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/GetAutoscalingPolicy/main.go b/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/GetAutoscalingPolicy/main.go index bb18aa17b8d7..77e7e4636c67 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/GetAutoscalingPolicy/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/GetAutoscalingPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewAutoscalingPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.GetAutoscalingPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/ListAutoscalingPolicies/main.go b/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/ListAutoscalingPolicies/main.go index d13a40e0a602..634e22da70c4 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/ListAutoscalingPolicies/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/ListAutoscalingPolicies/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dataproc.NewAutoscalingPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.ListAutoscalingPoliciesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/UpdateAutoscalingPolicy/main.go b/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/UpdateAutoscalingPolicy/main.go index 60f4acfd491d..3f6b8a462f42 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/UpdateAutoscalingPolicy/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/AutoscalingPolicyClient/UpdateAutoscalingPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewAutoscalingPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.UpdateAutoscalingPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/CreateCluster/main.go b/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/CreateCluster/main.go index 227aa3a93fd4..be3b1924626d 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/CreateCluster/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/CreateCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.CreateClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/DeleteCluster/main.go b/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/DeleteCluster/main.go index b6a0c7e72e38..72a96b43a7e3 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/DeleteCluster/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/DeleteCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DeleteClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/DiagnoseCluster/main.go b/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/DiagnoseCluster/main.go index 7c0743e41350..000527092eef 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/DiagnoseCluster/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/DiagnoseCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DiagnoseClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/GetCluster/main.go b/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/GetCluster/main.go index e7f1bf1d2e3f..f9404b91ca04 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/GetCluster/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/GetCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.GetClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/ListClusters/main.go b/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/ListClusters/main.go index 6d24d82d2fac..80438ca4d88e 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/ListClusters/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/ListClusters/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.ListClustersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/UpdateCluster/main.go b/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/UpdateCluster/main.go index 79d3608d82d1..ff1cd0a58d11 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/UpdateCluster/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/ClusterControllerClient/UpdateCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewClusterControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.UpdateClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/CancelJob/main.go b/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/CancelJob/main.go index 1f692a962507..095305640c34 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/CancelJob/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/CancelJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.CancelJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/DeleteJob/main.go b/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/DeleteJob/main.go index 1d27d5362f16..f9218d944453 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/DeleteJob/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/DeleteJob/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DeleteJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/GetJob/main.go b/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/GetJob/main.go index be360f61c72f..44a11fd48a04 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/GetJob/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/GetJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.GetJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/ListJobs/main.go b/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/ListJobs/main.go index 2a35ac913463..8f7a0cea8782 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/ListJobs/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/ListJobs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.ListJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/SubmitJob/main.go b/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/SubmitJob/main.go index 3f4b0af25316..a4cb724645e8 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/SubmitJob/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/SubmitJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.SubmitJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/SubmitJobAsOperation/main.go b/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/SubmitJobAsOperation/main.go index 45b3b4f8ae61..306364ff9238 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/SubmitJobAsOperation/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/SubmitJobAsOperation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.SubmitJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/UpdateJob/main.go b/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/UpdateJob/main.go index 24b002d8c4f2..35c266d28081 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/UpdateJob/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/JobControllerClient/UpdateJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewJobControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.UpdateJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/CreateWorkflowTemplate/main.go b/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/CreateWorkflowTemplate/main.go index a6df9ec449e0..038e4d8d4b72 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/CreateWorkflowTemplate/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/CreateWorkflowTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.CreateWorkflowTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/DeleteWorkflowTemplate/main.go b/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/DeleteWorkflowTemplate/main.go index abddd1023500..856e042d84ce 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/DeleteWorkflowTemplate/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/DeleteWorkflowTemplate/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.DeleteWorkflowTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/GetWorkflowTemplate/main.go b/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/GetWorkflowTemplate/main.go index 569b099d5cab..2e361db68a14 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/GetWorkflowTemplate/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/GetWorkflowTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.GetWorkflowTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/InstantiateInlineWorkflowTemplate/main.go b/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/InstantiateInlineWorkflowTemplate/main.go index 73c856a0b107..337cfb404849 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/InstantiateInlineWorkflowTemplate/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/InstantiateInlineWorkflowTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.InstantiateInlineWorkflowTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/InstantiateWorkflowTemplate/main.go b/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/InstantiateWorkflowTemplate/main.go index f420efed5550..0316f7952fd3 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/InstantiateWorkflowTemplate/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/InstantiateWorkflowTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.InstantiateWorkflowTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/ListWorkflowTemplates/main.go b/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/ListWorkflowTemplates/main.go index c14cdf2e5405..ddad36198890 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/ListWorkflowTemplates/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/ListWorkflowTemplates/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.ListWorkflowTemplatesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/UpdateWorkflowTemplate/main.go b/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/UpdateWorkflowTemplate/main.go index 13cc29e88c8e..3c717f93591c 100644 --- a/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/UpdateWorkflowTemplate/main.go +++ b/internal/generated/snippets/dataproc/apiv1beta2/WorkflowTemplateClient/UpdateWorkflowTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataprocpb "google.golang.org/genproto/googleapis/cloud/dataproc/v1beta2" - ctx := context.Background() c, err := dataproc.NewWorkflowTemplateClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataprocpb.UpdateWorkflowTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataqna/apiv1alpha/AutoSuggestionClient/SuggestQueries/main.go b/internal/generated/snippets/dataqna/apiv1alpha/AutoSuggestionClient/SuggestQueries/main.go index 64d7cdcbfddc..71631100bc17 100644 --- a/internal/generated/snippets/dataqna/apiv1alpha/AutoSuggestionClient/SuggestQueries/main.go +++ b/internal/generated/snippets/dataqna/apiv1alpha/AutoSuggestionClient/SuggestQueries/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataqnapb "google.golang.org/genproto/googleapis/cloud/dataqna/v1alpha" - ctx := context.Background() c, err := dataqna.NewAutoSuggestionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataqnapb.SuggestQueriesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/CreateQuestion/main.go b/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/CreateQuestion/main.go index 02420d80fea2..f8e28810625d 100644 --- a/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/CreateQuestion/main.go +++ b/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/CreateQuestion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataqnapb "google.golang.org/genproto/googleapis/cloud/dataqna/v1alpha" - ctx := context.Background() c, err := dataqna.NewQuestionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataqnapb.CreateQuestionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/ExecuteQuestion/main.go b/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/ExecuteQuestion/main.go index 16ce001947ea..f15eeadd8925 100644 --- a/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/ExecuteQuestion/main.go +++ b/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/ExecuteQuestion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataqnapb "google.golang.org/genproto/googleapis/cloud/dataqna/v1alpha" - ctx := context.Background() c, err := dataqna.NewQuestionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataqnapb.ExecuteQuestionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/GetQuestion/main.go b/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/GetQuestion/main.go index 8847271b40d5..9ff8cacfcfd2 100644 --- a/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/GetQuestion/main.go +++ b/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/GetQuestion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataqnapb "google.golang.org/genproto/googleapis/cloud/dataqna/v1alpha" - ctx := context.Background() c, err := dataqna.NewQuestionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataqnapb.GetQuestionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/GetUserFeedback/main.go b/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/GetUserFeedback/main.go index 11371d8ec35c..2ce388444e2f 100644 --- a/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/GetUserFeedback/main.go +++ b/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/GetUserFeedback/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataqnapb "google.golang.org/genproto/googleapis/cloud/dataqna/v1alpha" - ctx := context.Background() c, err := dataqna.NewQuestionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataqnapb.GetUserFeedbackRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/UpdateUserFeedback/main.go b/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/UpdateUserFeedback/main.go index 8685e4989ecf..9d8657d03c34 100644 --- a/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/UpdateUserFeedback/main.go +++ b/internal/generated/snippets/dataqna/apiv1alpha/QuestionClient/UpdateUserFeedback/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dataqnapb "google.golang.org/genproto/googleapis/cloud/dataqna/v1alpha" - ctx := context.Background() c, err := dataqna.NewQuestionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dataqnapb.UpdateUserFeedbackRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/CreateIndex/main.go b/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/CreateIndex/main.go index 70c0374cb90e..885d4b477c23 100644 --- a/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/CreateIndex/main.go +++ b/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/CreateIndex/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/datastore/admin/v1" - ctx := context.Background() c, err := admin.NewDatastoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.CreateIndexRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/DeleteIndex/main.go b/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/DeleteIndex/main.go index 2e62fe26c298..01ffa658a072 100644 --- a/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/DeleteIndex/main.go +++ b/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/DeleteIndex/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/datastore/admin/v1" - ctx := context.Background() c, err := admin.NewDatastoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteIndexRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/ExportEntities/main.go b/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/ExportEntities/main.go index 441c096cc73f..750695cbd784 100644 --- a/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/ExportEntities/main.go +++ b/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/ExportEntities/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/datastore/admin/v1" - ctx := context.Background() c, err := admin.NewDatastoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ExportEntitiesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/GetIndex/main.go b/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/GetIndex/main.go index 91f628af591d..afa1272600be 100644 --- a/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/GetIndex/main.go +++ b/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/GetIndex/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/datastore/admin/v1" - ctx := context.Background() c, err := admin.NewDatastoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetIndexRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/ImportEntities/main.go b/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/ImportEntities/main.go index 75146389afac..33a99207e062 100644 --- a/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/ImportEntities/main.go +++ b/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/ImportEntities/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/datastore/admin/v1" - ctx := context.Background() c, err := admin.NewDatastoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ImportEntitiesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/ListIndexes/main.go b/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/ListIndexes/main.go index d39a65625c13..3e964aeab1f0 100644 --- a/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/ListIndexes/main.go +++ b/internal/generated/snippets/datastore/admin/apiv1/DatastoreAdminClient/ListIndexes/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/datastore/admin/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := admin.NewDatastoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListIndexesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/debugger/apiv2/Controller2Client/ListActiveBreakpoints/main.go b/internal/generated/snippets/debugger/apiv2/Controller2Client/ListActiveBreakpoints/main.go index a18d23e58c88..37722568af99 100644 --- a/internal/generated/snippets/debugger/apiv2/Controller2Client/ListActiveBreakpoints/main.go +++ b/internal/generated/snippets/debugger/apiv2/Controller2Client/ListActiveBreakpoints/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddebuggerpb "google.golang.org/genproto/googleapis/devtools/clouddebugger/v2" - ctx := context.Background() c, err := debugger.NewController2Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddebuggerpb.ListActiveBreakpointsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/debugger/apiv2/Controller2Client/RegisterDebuggee/main.go b/internal/generated/snippets/debugger/apiv2/Controller2Client/RegisterDebuggee/main.go index 0b4266053530..43aead717f05 100644 --- a/internal/generated/snippets/debugger/apiv2/Controller2Client/RegisterDebuggee/main.go +++ b/internal/generated/snippets/debugger/apiv2/Controller2Client/RegisterDebuggee/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddebuggerpb "google.golang.org/genproto/googleapis/devtools/clouddebugger/v2" - ctx := context.Background() c, err := debugger.NewController2Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddebuggerpb.RegisterDebuggeeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/debugger/apiv2/Controller2Client/UpdateActiveBreakpoint/main.go b/internal/generated/snippets/debugger/apiv2/Controller2Client/UpdateActiveBreakpoint/main.go index 8cd6dba79ddf..a79a412f76c6 100644 --- a/internal/generated/snippets/debugger/apiv2/Controller2Client/UpdateActiveBreakpoint/main.go +++ b/internal/generated/snippets/debugger/apiv2/Controller2Client/UpdateActiveBreakpoint/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddebuggerpb "google.golang.org/genproto/googleapis/devtools/clouddebugger/v2" - ctx := context.Background() c, err := debugger.NewController2Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddebuggerpb.UpdateActiveBreakpointRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/debugger/apiv2/Debugger2Client/DeleteBreakpoint/main.go b/internal/generated/snippets/debugger/apiv2/Debugger2Client/DeleteBreakpoint/main.go index 3283ea9422f3..08d180d21ac3 100644 --- a/internal/generated/snippets/debugger/apiv2/Debugger2Client/DeleteBreakpoint/main.go +++ b/internal/generated/snippets/debugger/apiv2/Debugger2Client/DeleteBreakpoint/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddebuggerpb.DeleteBreakpointRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/debugger/apiv2/Debugger2Client/GetBreakpoint/main.go b/internal/generated/snippets/debugger/apiv2/Debugger2Client/GetBreakpoint/main.go index c17cf47492aa..276dea88cf25 100644 --- a/internal/generated/snippets/debugger/apiv2/Debugger2Client/GetBreakpoint/main.go +++ b/internal/generated/snippets/debugger/apiv2/Debugger2Client/GetBreakpoint/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddebuggerpb "google.golang.org/genproto/googleapis/devtools/clouddebugger/v2" - ctx := context.Background() c, err := debugger.NewDebugger2Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddebuggerpb.GetBreakpointRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/debugger/apiv2/Debugger2Client/ListBreakpoints/main.go b/internal/generated/snippets/debugger/apiv2/Debugger2Client/ListBreakpoints/main.go index 4ce859a945cd..23ff42b1ffb2 100644 --- a/internal/generated/snippets/debugger/apiv2/Debugger2Client/ListBreakpoints/main.go +++ b/internal/generated/snippets/debugger/apiv2/Debugger2Client/ListBreakpoints/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddebuggerpb "google.golang.org/genproto/googleapis/devtools/clouddebugger/v2" - ctx := context.Background() c, err := debugger.NewDebugger2Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddebuggerpb.ListBreakpointsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/debugger/apiv2/Debugger2Client/ListDebuggees/main.go b/internal/generated/snippets/debugger/apiv2/Debugger2Client/ListDebuggees/main.go index 8f9182fadbc6..799bc66fc559 100644 --- a/internal/generated/snippets/debugger/apiv2/Debugger2Client/ListDebuggees/main.go +++ b/internal/generated/snippets/debugger/apiv2/Debugger2Client/ListDebuggees/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddebuggerpb "google.golang.org/genproto/googleapis/devtools/clouddebugger/v2" - ctx := context.Background() c, err := debugger.NewDebugger2Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddebuggerpb.ListDebuggeesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/debugger/apiv2/Debugger2Client/SetBreakpoint/main.go b/internal/generated/snippets/debugger/apiv2/Debugger2Client/SetBreakpoint/main.go index 3ba91565ca3d..a8792508a409 100644 --- a/internal/generated/snippets/debugger/apiv2/Debugger2Client/SetBreakpoint/main.go +++ b/internal/generated/snippets/debugger/apiv2/Debugger2Client/SetBreakpoint/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouddebuggerpb "google.golang.org/genproto/googleapis/devtools/clouddebugger/v2" - ctx := context.Background() c, err := debugger.NewDebugger2Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouddebuggerpb.SetBreakpointRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/DeleteAgent/main.go b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/DeleteAgent/main.go index f536e28beb5c..d3131071be0b 100644 --- a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/DeleteAgent/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/DeleteAgent/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/ExportAgent/main.go b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/ExportAgent/main.go index 1f3d0e964001..b482f2693999 100644 --- a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/ExportAgent/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/ExportAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ExportAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/GetAgent/main.go b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/GetAgent/main.go index f2e73a6bf0bc..781195f1f487 100644 --- a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/GetAgent/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/GetAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/GetValidationResult/main.go b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/GetValidationResult/main.go index ab1863f18fc2..65b98a978f8e 100644 --- a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/GetValidationResult/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/GetValidationResult/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetValidationResultRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/ImportAgent/main.go b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/ImportAgent/main.go index 8188e4629dc3..f9f4223f4446 100644 --- a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/ImportAgent/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/ImportAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ImportAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/RestoreAgent/main.go b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/RestoreAgent/main.go index c5dcc55f00bd..a5caede5f546 100644 --- a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/RestoreAgent/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/RestoreAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.RestoreAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/SearchAgents/main.go b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/SearchAgents/main.go index d86d1be3ad83..75ba93dcdcf1 100644 --- a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/SearchAgents/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/SearchAgents/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.SearchAgentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/SetAgent/main.go b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/SetAgent/main.go index 56977185379b..ee9d47d7c26b 100644 --- a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/SetAgent/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/SetAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.SetAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/TrainAgent/main.go b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/TrainAgent/main.go index cbacfc84c001..f3d3aed5f466 100644 --- a/internal/generated/snippets/dialogflow/apiv2/AgentsClient/TrainAgent/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/AgentsClient/TrainAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.TrainAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/AnswerRecordsClient/ListAnswerRecords/main.go b/internal/generated/snippets/dialogflow/apiv2/AnswerRecordsClient/ListAnswerRecords/main.go index 8b3895e56ca5..8ffbdf3aa507 100644 --- a/internal/generated/snippets/dialogflow/apiv2/AnswerRecordsClient/ListAnswerRecords/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/AnswerRecordsClient/ListAnswerRecords/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewAnswerRecordsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListAnswerRecordsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/AnswerRecordsClient/UpdateAnswerRecord/main.go b/internal/generated/snippets/dialogflow/apiv2/AnswerRecordsClient/UpdateAnswerRecord/main.go index dcb82bff45e5..9e164618ecc0 100644 --- a/internal/generated/snippets/dialogflow/apiv2/AnswerRecordsClient/UpdateAnswerRecord/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/AnswerRecordsClient/UpdateAnswerRecord/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewAnswerRecordsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateAnswerRecordRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ContextsClient/CreateContext/main.go b/internal/generated/snippets/dialogflow/apiv2/ContextsClient/CreateContext/main.go index 35c54acf1ae7..3f3fa7af3f60 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ContextsClient/CreateContext/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ContextsClient/CreateContext/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewContextsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateContextRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ContextsClient/DeleteAllContexts/main.go b/internal/generated/snippets/dialogflow/apiv2/ContextsClient/DeleteAllContexts/main.go index c816db8b4a28..045efcbec616 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ContextsClient/DeleteAllContexts/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ContextsClient/DeleteAllContexts/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteAllContextsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ContextsClient/DeleteContext/main.go b/internal/generated/snippets/dialogflow/apiv2/ContextsClient/DeleteContext/main.go index 2686ea377900..028b43865dc8 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ContextsClient/DeleteContext/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ContextsClient/DeleteContext/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteContextRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ContextsClient/GetContext/main.go b/internal/generated/snippets/dialogflow/apiv2/ContextsClient/GetContext/main.go index 543d203c7327..a43c5e1b8845 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ContextsClient/GetContext/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ContextsClient/GetContext/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewContextsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetContextRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ContextsClient/ListContexts/main.go b/internal/generated/snippets/dialogflow/apiv2/ContextsClient/ListContexts/main.go index d752a20c562e..1e92abe6f16b 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ContextsClient/ListContexts/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ContextsClient/ListContexts/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewContextsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListContextsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ContextsClient/UpdateContext/main.go b/internal/generated/snippets/dialogflow/apiv2/ContextsClient/UpdateContext/main.go index 2aa94c1cb10a..eb1e0dbba65b 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ContextsClient/UpdateContext/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ContextsClient/UpdateContext/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewContextsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateContextRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/CreateConversationProfile/main.go b/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/CreateConversationProfile/main.go index 801ef8d9d55b..1611446da5ba 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/CreateConversationProfile/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/CreateConversationProfile/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewConversationProfilesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateConversationProfileRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/DeleteConversationProfile/main.go b/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/DeleteConversationProfile/main.go index 6098bd744edc..ba80b749f44c 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/DeleteConversationProfile/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/DeleteConversationProfile/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteConversationProfileRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/GetConversationProfile/main.go b/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/GetConversationProfile/main.go index 4e3f3ecda700..46b489dff6a9 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/GetConversationProfile/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/GetConversationProfile/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewConversationProfilesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetConversationProfileRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/ListConversationProfiles/main.go b/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/ListConversationProfiles/main.go index d75f051b5cbb..f64595009dbb 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/ListConversationProfiles/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/ListConversationProfiles/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewConversationProfilesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListConversationProfilesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/UpdateConversationProfile/main.go b/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/UpdateConversationProfile/main.go index 354a3320d4c2..78ad4c84180b 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/UpdateConversationProfile/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ConversationProfilesClient/UpdateConversationProfile/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewConversationProfilesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateConversationProfileRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/CompleteConversation/main.go b/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/CompleteConversation/main.go index 12aa448b704d..959eb1ae25a2 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/CompleteConversation/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/CompleteConversation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewConversationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CompleteConversationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/CreateConversation/main.go b/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/CreateConversation/main.go index aa4e8bd041de..9acecc0ecaf1 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/CreateConversation/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/CreateConversation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewConversationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateConversationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/GetConversation/main.go b/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/GetConversation/main.go index c489e3f8fb45..99bc5f83b647 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/GetConversation/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/GetConversation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewConversationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetConversationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/ListConversations/main.go b/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/ListConversations/main.go index 78cf14cd7cfb..91d8e1532e41 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/ListConversations/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/ListConversations/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewConversationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListConversationsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/ListMessages/main.go b/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/ListMessages/main.go index fdbc330a1d93..c62088beab4b 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/ListMessages/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ConversationsClient/ListMessages/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewConversationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListMessagesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/CreateDocument/main.go b/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/CreateDocument/main.go index 5847013627af..5e3cfb1eda3c 100644 --- a/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/CreateDocument/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/CreateDocument/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewDocumentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateDocumentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/DeleteDocument/main.go b/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/DeleteDocument/main.go index 7e2cce86547b..9adb91d12b2f 100644 --- a/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/DeleteDocument/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/DeleteDocument/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewDocumentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteDocumentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/GetDocument/main.go b/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/GetDocument/main.go index 9596f1f0a2a6..489943bd641c 100644 --- a/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/GetDocument/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/GetDocument/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewDocumentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetDocumentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/ListDocuments/main.go b/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/ListDocuments/main.go index bded0b1c7e86..489680f29169 100644 --- a/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/ListDocuments/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/ListDocuments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewDocumentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListDocumentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/ReloadDocument/main.go b/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/ReloadDocument/main.go index bb0299e94085..9671320b3f78 100644 --- a/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/ReloadDocument/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/ReloadDocument/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewDocumentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ReloadDocumentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/UpdateDocument/main.go b/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/UpdateDocument/main.go index 8f470e697808..dc6f956dc678 100644 --- a/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/UpdateDocument/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/DocumentsClient/UpdateDocument/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewDocumentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateDocumentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchCreateEntities/main.go b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchCreateEntities/main.go index a969a4f5bbb3..e4a7643e211e 100644 --- a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchCreateEntities/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchCreateEntities/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.BatchCreateEntitiesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchDeleteEntities/main.go b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchDeleteEntities/main.go index ff803ed5303f..5e08e7515225 100644 --- a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchDeleteEntities/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchDeleteEntities/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.BatchDeleteEntitiesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchDeleteEntityTypes/main.go b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchDeleteEntityTypes/main.go index 9247b9f1c691..a9f2193043cc 100644 --- a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchDeleteEntityTypes/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchDeleteEntityTypes/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.BatchDeleteEntityTypesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchUpdateEntities/main.go b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchUpdateEntities/main.go index dc53345fafbb..97d0ccf6d017 100644 --- a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchUpdateEntities/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchUpdateEntities/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.BatchUpdateEntitiesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchUpdateEntityTypes/main.go b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchUpdateEntityTypes/main.go index be66d5efaa5a..567569aa8934 100644 --- a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchUpdateEntityTypes/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/BatchUpdateEntityTypes/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.BatchUpdateEntityTypesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/CreateEntityType/main.go b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/CreateEntityType/main.go index 588064811d0b..f5a99ff93561 100644 --- a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/CreateEntityType/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/CreateEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/DeleteEntityType/main.go b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/DeleteEntityType/main.go index 0ccf9f42eea7..73dcd6c3d3f8 100644 --- a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/DeleteEntityType/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/DeleteEntityType/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/GetEntityType/main.go b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/GetEntityType/main.go index 006f740b3fdb..dee56bc51f36 100644 --- a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/GetEntityType/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/GetEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/ListEntityTypes/main.go b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/ListEntityTypes/main.go index 934a934a2f47..b540bc330b8c 100644 --- a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/ListEntityTypes/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/ListEntityTypes/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListEntityTypesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/UpdateEntityType/main.go b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/UpdateEntityType/main.go index 2fea84b13244..7f582a08a8e9 100644 --- a/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/UpdateEntityType/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/EntityTypesClient/UpdateEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/CreateEnvironment/main.go b/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/CreateEnvironment/main.go index 15428dfbd569..2a35e759aa72 100644 --- a/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/CreateEnvironment/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/CreateEnvironment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateEnvironmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/DeleteEnvironment/main.go b/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/DeleteEnvironment/main.go index 3b817d593105..9f231b9f3f81 100644 --- a/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/DeleteEnvironment/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/DeleteEnvironment/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteEnvironmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/GetEnvironment/main.go b/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/GetEnvironment/main.go index b28871b79cfd..ab66c8bab6c3 100644 --- a/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/GetEnvironment/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/GetEnvironment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetEnvironmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/GetEnvironmentHistory/main.go b/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/GetEnvironmentHistory/main.go index 82aae6f04690..bd0d711d2380 100644 --- a/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/GetEnvironmentHistory/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/GetEnvironmentHistory/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetEnvironmentHistoryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/ListEnvironments/main.go b/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/ListEnvironments/main.go index fcb66910f7be..e15762d1f145 100644 --- a/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/ListEnvironments/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/ListEnvironments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListEnvironmentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/UpdateEnvironment/main.go b/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/UpdateEnvironment/main.go index d0b1c0eeabc2..51cea4405513 100644 --- a/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/UpdateEnvironment/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/EnvironmentsClient/UpdateEnvironment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateEnvironmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/FulfillmentsClient/GetFulfillment/main.go b/internal/generated/snippets/dialogflow/apiv2/FulfillmentsClient/GetFulfillment/main.go index de6f26a41b0e..4cc01e4eddea 100644 --- a/internal/generated/snippets/dialogflow/apiv2/FulfillmentsClient/GetFulfillment/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/FulfillmentsClient/GetFulfillment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewFulfillmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetFulfillmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/FulfillmentsClient/UpdateFulfillment/main.go b/internal/generated/snippets/dialogflow/apiv2/FulfillmentsClient/UpdateFulfillment/main.go index 97527c5fcce1..8d5e58d6f293 100644 --- a/internal/generated/snippets/dialogflow/apiv2/FulfillmentsClient/UpdateFulfillment/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/FulfillmentsClient/UpdateFulfillment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewFulfillmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateFulfillmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/IntentsClient/BatchDeleteIntents/main.go b/internal/generated/snippets/dialogflow/apiv2/IntentsClient/BatchDeleteIntents/main.go index c2f4b32d0832..c5be75be9d91 100644 --- a/internal/generated/snippets/dialogflow/apiv2/IntentsClient/BatchDeleteIntents/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/IntentsClient/BatchDeleteIntents/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.BatchDeleteIntentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/IntentsClient/BatchUpdateIntents/main.go b/internal/generated/snippets/dialogflow/apiv2/IntentsClient/BatchUpdateIntents/main.go index 3489a1a061a0..90c8711c27cb 100644 --- a/internal/generated/snippets/dialogflow/apiv2/IntentsClient/BatchUpdateIntents/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/IntentsClient/BatchUpdateIntents/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.BatchUpdateIntentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/IntentsClient/CreateIntent/main.go b/internal/generated/snippets/dialogflow/apiv2/IntentsClient/CreateIntent/main.go index 81f7303944a7..ac4a07538330 100644 --- a/internal/generated/snippets/dialogflow/apiv2/IntentsClient/CreateIntent/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/IntentsClient/CreateIntent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/IntentsClient/DeleteIntent/main.go b/internal/generated/snippets/dialogflow/apiv2/IntentsClient/DeleteIntent/main.go index 2c85cae0b61f..e43554676a60 100644 --- a/internal/generated/snippets/dialogflow/apiv2/IntentsClient/DeleteIntent/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/IntentsClient/DeleteIntent/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/IntentsClient/GetIntent/main.go b/internal/generated/snippets/dialogflow/apiv2/IntentsClient/GetIntent/main.go index 6a9d4808b6c0..e734c3525601 100644 --- a/internal/generated/snippets/dialogflow/apiv2/IntentsClient/GetIntent/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/IntentsClient/GetIntent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/IntentsClient/ListIntents/main.go b/internal/generated/snippets/dialogflow/apiv2/IntentsClient/ListIntents/main.go index 6db4b196cbe2..0ea6daf5d692 100644 --- a/internal/generated/snippets/dialogflow/apiv2/IntentsClient/ListIntents/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/IntentsClient/ListIntents/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListIntentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/IntentsClient/UpdateIntent/main.go b/internal/generated/snippets/dialogflow/apiv2/IntentsClient/UpdateIntent/main.go index 5e9f484a0d94..c7c070382c69 100644 --- a/internal/generated/snippets/dialogflow/apiv2/IntentsClient/UpdateIntent/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/IntentsClient/UpdateIntent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/CreateKnowledgeBase/main.go b/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/CreateKnowledgeBase/main.go index 7757d1bd663e..3f7ee795b6ee 100644 --- a/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/CreateKnowledgeBase/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/CreateKnowledgeBase/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewKnowledgeBasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateKnowledgeBaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/DeleteKnowledgeBase/main.go b/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/DeleteKnowledgeBase/main.go index c148d95c5df8..e1464aa841af 100644 --- a/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/DeleteKnowledgeBase/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/DeleteKnowledgeBase/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteKnowledgeBaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/GetKnowledgeBase/main.go b/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/GetKnowledgeBase/main.go index f09a50672607..c670ae235420 100644 --- a/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/GetKnowledgeBase/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/GetKnowledgeBase/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewKnowledgeBasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetKnowledgeBaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/ListKnowledgeBases/main.go b/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/ListKnowledgeBases/main.go index 87a25ac69a84..274fc9de5a5c 100644 --- a/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/ListKnowledgeBases/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/ListKnowledgeBases/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewKnowledgeBasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListKnowledgeBasesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/UpdateKnowledgeBase/main.go b/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/UpdateKnowledgeBase/main.go index e2aa7b8ef486..918108256781 100644 --- a/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/UpdateKnowledgeBase/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/KnowledgeBasesClient/UpdateKnowledgeBase/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewKnowledgeBasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateKnowledgeBaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/AnalyzeContent/main.go b/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/AnalyzeContent/main.go index 6d4c00cd6d59..f0ad7da977b3 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/AnalyzeContent/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/AnalyzeContent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewParticipantsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.AnalyzeContentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/CreateParticipant/main.go b/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/CreateParticipant/main.go index 36ff4fa4c14b..abb2c70ed693 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/CreateParticipant/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/CreateParticipant/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewParticipantsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateParticipantRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/GetParticipant/main.go b/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/GetParticipant/main.go index 8acdf53de1ed..d68e0cf43910 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/GetParticipant/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/GetParticipant/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewParticipantsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetParticipantRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/ListParticipants/main.go b/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/ListParticipants/main.go index 2dbd51395d44..a0c67adf96a2 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/ListParticipants/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/ListParticipants/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewParticipantsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListParticipantsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/SuggestArticles/main.go b/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/SuggestArticles/main.go index 55f1b5b8954a..f67827add8dd 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/SuggestArticles/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/SuggestArticles/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewParticipantsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.SuggestArticlesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/SuggestFaqAnswers/main.go b/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/SuggestFaqAnswers/main.go index 8a8302301ebd..f8b5b4c2f500 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/SuggestFaqAnswers/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/SuggestFaqAnswers/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewParticipantsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.SuggestFaqAnswersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/UpdateParticipant/main.go b/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/UpdateParticipant/main.go index 437b1aca6598..7f3b4cdeb6bb 100644 --- a/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/UpdateParticipant/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/ParticipantsClient/UpdateParticipant/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewParticipantsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateParticipantRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/CreateSessionEntityType/main.go b/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/CreateSessionEntityType/main.go index 338a4dc4684d..8feba4528d5a 100644 --- a/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/CreateSessionEntityType/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/CreateSessionEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateSessionEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/DeleteSessionEntityType/main.go b/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/DeleteSessionEntityType/main.go index 549e90ad9fb2..300204d214d1 100644 --- a/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/DeleteSessionEntityType/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/DeleteSessionEntityType/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteSessionEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/GetSessionEntityType/main.go b/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/GetSessionEntityType/main.go index 8359d4970949..d4de5eaae215 100644 --- a/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/GetSessionEntityType/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/GetSessionEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetSessionEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/ListSessionEntityTypes/main.go b/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/ListSessionEntityTypes/main.go index 1933e9884d5f..1c88767581be 100644 --- a/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/ListSessionEntityTypes/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/ListSessionEntityTypes/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListSessionEntityTypesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/UpdateSessionEntityType/main.go b/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/UpdateSessionEntityType/main.go index 9149517d4d33..5b02e99af517 100644 --- a/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/UpdateSessionEntityType/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/SessionEntityTypesClient/UpdateSessionEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateSessionEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/SessionsClient/DetectIntent/main.go b/internal/generated/snippets/dialogflow/apiv2/SessionsClient/DetectIntent/main.go index 1ed24f6a2a2f..7c1258db4554 100644 --- a/internal/generated/snippets/dialogflow/apiv2/SessionsClient/DetectIntent/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/SessionsClient/DetectIntent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DetectIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/SessionsClient/StreamingDetectIntent/main.go b/internal/generated/snippets/dialogflow/apiv2/SessionsClient/StreamingDetectIntent/main.go index cb91f64b854a..e36b065ad6cf 100644 --- a/internal/generated/snippets/dialogflow/apiv2/SessionsClient/StreamingDetectIntent/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/SessionsClient/StreamingDetectIntent/main.go @@ -25,13 +25,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.StreamingDetectIntent(ctx) if err != nil { // TODO: Handle error. diff --git a/internal/generated/snippets/dialogflow/apiv2/VersionsClient/CreateVersion/main.go b/internal/generated/snippets/dialogflow/apiv2/VersionsClient/CreateVersion/main.go index 78e62d0527a1..22de102a1918 100644 --- a/internal/generated/snippets/dialogflow/apiv2/VersionsClient/CreateVersion/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/VersionsClient/CreateVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.CreateVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/VersionsClient/DeleteVersion/main.go b/internal/generated/snippets/dialogflow/apiv2/VersionsClient/DeleteVersion/main.go index 433d1f05dfc3..cfc122aba43b 100644 --- a/internal/generated/snippets/dialogflow/apiv2/VersionsClient/DeleteVersion/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/VersionsClient/DeleteVersion/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.DeleteVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/VersionsClient/GetVersion/main.go b/internal/generated/snippets/dialogflow/apiv2/VersionsClient/GetVersion/main.go index eb6cc90d8641..9d93b456098b 100644 --- a/internal/generated/snippets/dialogflow/apiv2/VersionsClient/GetVersion/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/VersionsClient/GetVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.GetVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/VersionsClient/ListVersions/main.go b/internal/generated/snippets/dialogflow/apiv2/VersionsClient/ListVersions/main.go index 70ac2ece204b..e41bbb4d2084 100644 --- a/internal/generated/snippets/dialogflow/apiv2/VersionsClient/ListVersions/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/VersionsClient/ListVersions/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dialogflow.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.ListVersionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/apiv2/VersionsClient/UpdateVersion/main.go b/internal/generated/snippets/dialogflow/apiv2/VersionsClient/UpdateVersion/main.go index 5281568ac61d..7008cd7ad088 100644 --- a/internal/generated/snippets/dialogflow/apiv2/VersionsClient/UpdateVersion/main.go +++ b/internal/generated/snippets/dialogflow/apiv2/VersionsClient/UpdateVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2" - ctx := context.Background() c, err := dialogflow.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dialogflowpb.UpdateVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/CreateAgent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/CreateAgent/main.go index ceca952aea6b..0bcaeb441d2d 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/CreateAgent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/CreateAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/DeleteAgent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/DeleteAgent/main.go index 388be3727ffe..93f2bfde250a 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/DeleteAgent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/DeleteAgent/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/ExportAgent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/ExportAgent/main.go index 192f0791a93c..4016e12bf0e5 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/ExportAgent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/ExportAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ExportAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/GetAgent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/GetAgent/main.go index bf1a22477e36..1c6a93a6084e 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/GetAgent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/GetAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/GetAgentValidationResult/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/GetAgentValidationResult/main.go index 011e3475bacc..5c241d1d6dd7 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/GetAgentValidationResult/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/GetAgentValidationResult/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetAgentValidationResultRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/ListAgents/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/ListAgents/main.go index 71f6f82f19a3..70125e651807 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/ListAgents/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/ListAgents/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListAgentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/RestoreAgent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/RestoreAgent/main.go index 0f59cb37a582..7a320c35f67f 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/RestoreAgent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/RestoreAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.RestoreAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/UpdateAgent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/UpdateAgent/main.go index 2bbfd17e1a34..c840012ff49e 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/UpdateAgent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/UpdateAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/ValidateAgent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/ValidateAgent/main.go index 42d8cd530ac8..2d58e675ec87 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/ValidateAgent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/AgentsClient/ValidateAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ValidateAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/CreateEntityType/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/CreateEntityType/main.go index 63dcb4d61078..7d98ede95de4 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/CreateEntityType/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/CreateEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/DeleteEntityType/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/DeleteEntityType/main.go index 9f6deae3d7b0..b89956744c0c 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/DeleteEntityType/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/DeleteEntityType/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/GetEntityType/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/GetEntityType/main.go index 9623090ba552..4227f068d289 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/GetEntityType/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/GetEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/ListEntityTypes/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/ListEntityTypes/main.go index 0f74c291095d..de324642ac95 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/ListEntityTypes/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/ListEntityTypes/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListEntityTypesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/UpdateEntityType/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/UpdateEntityType/main.go index b840aadda1a7..f932c5de18a4 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/UpdateEntityType/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/EntityTypesClient/UpdateEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/CreateEnvironment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/CreateEnvironment/main.go index ec45fc2dd880..b8d4a09dd71c 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/CreateEnvironment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/CreateEnvironment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateEnvironmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/DeleteEnvironment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/DeleteEnvironment/main.go index 3ba1962ff004..b71edc7c8e69 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/DeleteEnvironment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/DeleteEnvironment/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteEnvironmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/GetEnvironment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/GetEnvironment/main.go index 0b4e387b843c..d92a055f7ea6 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/GetEnvironment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/GetEnvironment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetEnvironmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/ListEnvironments/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/ListEnvironments/main.go index d05956936997..b4d6d15ff44a 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/ListEnvironments/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/ListEnvironments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListEnvironmentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/LookupEnvironmentHistory/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/LookupEnvironmentHistory/main.go index 32f288df7a42..4fb37e8024b0 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/LookupEnvironmentHistory/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/LookupEnvironmentHistory/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.LookupEnvironmentHistoryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/UpdateEnvironment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/UpdateEnvironment/main.go index ba4103789a25..67735c4e588b 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/UpdateEnvironment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/EnvironmentsClient/UpdateEnvironment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateEnvironmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/CreateExperiment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/CreateExperiment/main.go index fb2ae805c779..a39634563271 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/CreateExperiment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/CreateExperiment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateExperimentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/DeleteExperiment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/DeleteExperiment/main.go index 242c9e92aeb8..a12d8bf04474 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/DeleteExperiment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/DeleteExperiment/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteExperimentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/GetExperiment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/GetExperiment/main.go index e60b22aa4c82..2fce50ff1fcc 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/GetExperiment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/GetExperiment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetExperimentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/ListExperiments/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/ListExperiments/main.go index 73aa077a4f71..c345c08940f6 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/ListExperiments/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/ListExperiments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListExperimentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/StartExperiment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/StartExperiment/main.go index d3fe4e6473ae..538ca112315d 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/StartExperiment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/StartExperiment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.StartExperimentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/StopExperiment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/StopExperiment/main.go index 836f6305189e..77ea555da0cb 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/StopExperiment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/StopExperiment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.StopExperimentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/UpdateExperiment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/UpdateExperiment/main.go index 7b9eae1a0594..632ac41f57ab 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/UpdateExperiment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/ExperimentsClient/UpdateExperiment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateExperimentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/CreateFlow/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/CreateFlow/main.go index df3ae0b60714..6261262e54f1 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/CreateFlow/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/CreateFlow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateFlowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/DeleteFlow/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/DeleteFlow/main.go index 00f7585342b9..0ddbb143fc8a 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/DeleteFlow/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/DeleteFlow/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteFlowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/ExportFlow/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/ExportFlow/main.go index 095a201702ec..146690e7fab7 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/ExportFlow/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/ExportFlow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ExportFlowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/GetFlow/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/GetFlow/main.go index c2cbbe46f884..3ee7898a861b 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/GetFlow/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/GetFlow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetFlowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/GetFlowValidationResult/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/GetFlowValidationResult/main.go index 53e3004c16d1..b4acf274fecc 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/GetFlowValidationResult/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/GetFlowValidationResult/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetFlowValidationResultRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/ImportFlow/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/ImportFlow/main.go index 77a16bdf22f9..ac9b2ba27beb 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/ImportFlow/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/ImportFlow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ImportFlowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/ListFlows/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/ListFlows/main.go index 0e0ff73003e7..30ef0c879336 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/ListFlows/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/ListFlows/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListFlowsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/TrainFlow/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/TrainFlow/main.go index d1ecf1baf2f2..cd8973f76f62 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/TrainFlow/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/TrainFlow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.TrainFlowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/UpdateFlow/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/UpdateFlow/main.go index c43f44192f5d..3d1aeffe03b4 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/UpdateFlow/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/UpdateFlow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateFlowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/ValidateFlow/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/ValidateFlow/main.go index 802d39394dc3..b13275feb485 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/ValidateFlow/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/FlowsClient/ValidateFlow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ValidateFlowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/CreateIntent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/CreateIntent/main.go index 22a740ca1618..94a21e2feafd 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/CreateIntent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/CreateIntent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/DeleteIntent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/DeleteIntent/main.go index 8daeee403a59..e45b4ba7aa10 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/DeleteIntent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/DeleteIntent/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/GetIntent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/GetIntent/main.go index d9936df80f12..38a501406ca2 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/GetIntent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/GetIntent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/ListIntents/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/ListIntents/main.go index ac4e9035f068..1f392116fb48 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/ListIntents/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/ListIntents/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListIntentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/UpdateIntent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/UpdateIntent/main.go index e7f4245c2496..3e8920a018ba 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/UpdateIntent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/IntentsClient/UpdateIntent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/CreatePage/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/CreatePage/main.go index 9dc562bfe0e1..92419def207b 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/CreatePage/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/CreatePage/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewPagesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreatePageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/DeletePage/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/DeletePage/main.go index 90df3ff40fe9..fd3c0b32011c 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/DeletePage/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/DeletePage/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeletePageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/GetPage/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/GetPage/main.go index 847c1f380ee6..4e240b5c446b 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/GetPage/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/GetPage/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewPagesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetPageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/ListPages/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/ListPages/main.go index ba8f14e19562..b0e1e84bcd44 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/ListPages/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/ListPages/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewPagesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListPagesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/UpdatePage/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/UpdatePage/main.go index ed8f2a36788e..6fbea118c042 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/UpdatePage/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/PagesClient/UpdatePage/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewPagesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdatePageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/CreateSecuritySettings/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/CreateSecuritySettings/main.go index d578d0242979..4afa2ff5322d 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/CreateSecuritySettings/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/CreateSecuritySettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSecuritySettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateSecuritySettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/DeleteSecuritySettings/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/DeleteSecuritySettings/main.go index cb0299beb3ec..9e4ac8fb299f 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/DeleteSecuritySettings/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/DeleteSecuritySettings/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteSecuritySettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/GetSecuritySettings/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/GetSecuritySettings/main.go index 6b09089b8b06..52cf0c15e541 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/GetSecuritySettings/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/GetSecuritySettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSecuritySettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetSecuritySettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/ListSecuritySettings/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/ListSecuritySettings/main.go index cdee88e98001..3534515209cb 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/ListSecuritySettings/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/ListSecuritySettings/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewSecuritySettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListSecuritySettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/UpdateSecuritySettings/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/UpdateSecuritySettings/main.go index 16e426f97d57..de873e99b9f3 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/UpdateSecuritySettings/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/SecuritySettingsClient/UpdateSecuritySettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSecuritySettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateSecuritySettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/CreateSessionEntityType/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/CreateSessionEntityType/main.go index 57aaf3383a4e..219a3e69b60d 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/CreateSessionEntityType/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/CreateSessionEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateSessionEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/DeleteSessionEntityType/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/DeleteSessionEntityType/main.go index 29d2de08cd03..ed9ae121d1d0 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/DeleteSessionEntityType/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/DeleteSessionEntityType/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteSessionEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/GetSessionEntityType/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/GetSessionEntityType/main.go index 2a145715d55a..ef91daf2dcc6 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/GetSessionEntityType/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/GetSessionEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetSessionEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/ListSessionEntityTypes/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/ListSessionEntityTypes/main.go index c094d7e0acbe..fb69e5432030 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/ListSessionEntityTypes/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/ListSessionEntityTypes/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListSessionEntityTypesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/UpdateSessionEntityType/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/UpdateSessionEntityType/main.go index 4303c6c154bc..77cee6b8c415 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/UpdateSessionEntityType/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/SessionEntityTypesClient/UpdateSessionEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateSessionEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/SessionsClient/DetectIntent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/SessionsClient/DetectIntent/main.go index e7aea12151be..74926b801a6f 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/SessionsClient/DetectIntent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/SessionsClient/DetectIntent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DetectIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/SessionsClient/FulfillIntent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/SessionsClient/FulfillIntent/main.go index 0b8662e6f5a9..bd82e975df67 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/SessionsClient/FulfillIntent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/SessionsClient/FulfillIntent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.FulfillIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/SessionsClient/MatchIntent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/SessionsClient/MatchIntent/main.go index 9da7d57f49cf..a4e8471015c4 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/SessionsClient/MatchIntent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/SessionsClient/MatchIntent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.MatchIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/SessionsClient/StreamingDetectIntent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/SessionsClient/StreamingDetectIntent/main.go index a8a66e548900..b66ba3ef301f 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/SessionsClient/StreamingDetectIntent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/SessionsClient/StreamingDetectIntent/main.go @@ -25,13 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.StreamingDetectIntent(ctx) if err != nil { // TODO: Handle error. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/BatchDeleteTestCases/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/BatchDeleteTestCases/main.go index 8a3a3c0becf4..16d95b344b14 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/BatchDeleteTestCases/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/BatchDeleteTestCases/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.BatchDeleteTestCasesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/BatchRunTestCases/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/BatchRunTestCases/main.go index e1b02786e215..d707c3f8a583 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/BatchRunTestCases/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/BatchRunTestCases/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.BatchRunTestCasesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/CalculateCoverage/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/CalculateCoverage/main.go index ccb2a01fdb14..13b615ae7150 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/CalculateCoverage/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/CalculateCoverage/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CalculateCoverageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/CreateTestCase/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/CreateTestCase/main.go index 4fa1be04fa4d..9805423150a6 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/CreateTestCase/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/CreateTestCase/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateTestCaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/ExportTestCases/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/ExportTestCases/main.go index a1814fae69a6..27c3f35c7248 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/ExportTestCases/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/ExportTestCases/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ExportTestCasesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/GetTestCase/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/GetTestCase/main.go index f1c7349a35b7..23d670252d77 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/GetTestCase/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/GetTestCase/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetTestCaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/GetTestCaseResult/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/GetTestCaseResult/main.go index bd2acbf64d82..19bf94bc2e2c 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/GetTestCaseResult/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/GetTestCaseResult/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetTestCaseResultRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/ImportTestCases/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/ImportTestCases/main.go index 1d40ff9718b2..0f7f3b3f4f38 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/ImportTestCases/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/ImportTestCases/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ImportTestCasesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/ListTestCaseResults/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/ListTestCaseResults/main.go index 15096b2233ea..f0f93ab59ffe 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/ListTestCaseResults/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/ListTestCaseResults/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListTestCaseResultsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/ListTestCases/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/ListTestCases/main.go index 29c7fc8cb72b..d4970a4a6c10 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/ListTestCases/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/ListTestCases/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListTestCasesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/RunTestCase/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/RunTestCase/main.go index 809b5494439b..139953ffa45e 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/RunTestCase/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/RunTestCase/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.RunTestCaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/UpdateTestCase/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/UpdateTestCase/main.go index 6716b92a7aef..ca18a4bbfe69 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/UpdateTestCase/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/TestCasesClient/UpdateTestCase/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateTestCaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/CreateTransitionRouteGroup/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/CreateTransitionRouteGroup/main.go index aebf6aa73eca..1e1ec95d369e 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/CreateTransitionRouteGroup/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/CreateTransitionRouteGroup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTransitionRouteGroupsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateTransitionRouteGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/DeleteTransitionRouteGroup/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/DeleteTransitionRouteGroup/main.go index efc56e0ce881..90bffd2bc5a7 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/DeleteTransitionRouteGroup/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/DeleteTransitionRouteGroup/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteTransitionRouteGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/GetTransitionRouteGroup/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/GetTransitionRouteGroup/main.go index 916bbc6f204e..b6251b9c7e7e 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/GetTransitionRouteGroup/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/GetTransitionRouteGroup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTransitionRouteGroupsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetTransitionRouteGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/ListTransitionRouteGroups/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/ListTransitionRouteGroups/main.go index d30dc8cf5ef1..6927362efd22 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/ListTransitionRouteGroups/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/ListTransitionRouteGroups/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewTransitionRouteGroupsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListTransitionRouteGroupsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/UpdateTransitionRouteGroup/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/UpdateTransitionRouteGroup/main.go index 9779be160ab6..4d980c0edcc3 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/UpdateTransitionRouteGroup/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/TransitionRouteGroupsClient/UpdateTransitionRouteGroup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewTransitionRouteGroupsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateTransitionRouteGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/CreateVersion/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/CreateVersion/main.go index 00ed2521dff7..8bf0c0685fe2 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/CreateVersion/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/CreateVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/DeleteVersion/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/DeleteVersion/main.go index 68590e67a1b5..d945c9b2c6b8 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/DeleteVersion/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/DeleteVersion/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/GetVersion/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/GetVersion/main.go index 6d311c907490..993131307ffb 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/GetVersion/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/GetVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/ListVersions/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/ListVersions/main.go index 21ae804fdc5a..a9f9f686872b 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/ListVersions/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/ListVersions/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListVersionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/LoadVersion/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/LoadVersion/main.go index 0dce06fb8692..c10ab896dba1 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/LoadVersion/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/LoadVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.LoadVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/UpdateVersion/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/UpdateVersion/main.go index f065977395dc..d9d645999401 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/UpdateVersion/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/VersionsClient/UpdateVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/CreateWebhook/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/CreateWebhook/main.go index 477c8f9711ee..e763adfb0c8a 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/CreateWebhook/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/CreateWebhook/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewWebhooksClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateWebhookRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/DeleteWebhook/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/DeleteWebhook/main.go index 644725323112..4ba123fc9b32 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/DeleteWebhook/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/DeleteWebhook/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteWebhookRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/GetWebhook/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/GetWebhook/main.go index c51d7bcaf7fa..bcfc5d737869 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/GetWebhook/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/GetWebhook/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewWebhooksClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetWebhookRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/ListWebhooks/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/ListWebhooks/main.go index 8f990dab09bb..48676810bbc5 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/ListWebhooks/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/ListWebhooks/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewWebhooksClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListWebhooksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/UpdateWebhook/main.go b/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/UpdateWebhook/main.go index ae6c9b2f222e..d1ee7720f115 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/UpdateWebhook/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3/WebhooksClient/UpdateWebhook/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3" - ctx := context.Background() c, err := cx.NewWebhooksClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateWebhookRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/CreateAgent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/CreateAgent/main.go index acbf7883958d..b653fe978c88 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/CreateAgent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/CreateAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/DeleteAgent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/DeleteAgent/main.go index 8587774e7fa7..59f8db8579e3 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/DeleteAgent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/DeleteAgent/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/ExportAgent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/ExportAgent/main.go index af740a7057fa..266935a98550 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/ExportAgent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/ExportAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ExportAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/GetAgent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/GetAgent/main.go index 383615ecd344..6c87abbf5b4f 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/GetAgent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/GetAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/GetAgentValidationResult/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/GetAgentValidationResult/main.go index e45d718d5cef..3a31afab27fb 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/GetAgentValidationResult/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/GetAgentValidationResult/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetAgentValidationResultRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/ListAgents/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/ListAgents/main.go index 445acef362f0..f5af93f50a10 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/ListAgents/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/ListAgents/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListAgentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/RestoreAgent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/RestoreAgent/main.go index de4f0b128ed7..f6b3b7368e85 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/RestoreAgent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/RestoreAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.RestoreAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/UpdateAgent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/UpdateAgent/main.go index 168a82172559..37dcbb664deb 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/UpdateAgent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/UpdateAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/ValidateAgent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/ValidateAgent/main.go index 6964fde5f497..7c52535878f1 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/ValidateAgent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/AgentsClient/ValidateAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewAgentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ValidateAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/CreateEntityType/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/CreateEntityType/main.go index 46f4e6365933..674825b75c8b 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/CreateEntityType/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/CreateEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/DeleteEntityType/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/DeleteEntityType/main.go index 1183bcaf9860..ca5097b3c5db 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/DeleteEntityType/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/DeleteEntityType/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/GetEntityType/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/GetEntityType/main.go index 6f8c8fd8d791..e1fcf1c40b72 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/GetEntityType/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/GetEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/ListEntityTypes/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/ListEntityTypes/main.go index 57206df4b16e..895c2dccf284 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/ListEntityTypes/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/ListEntityTypes/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListEntityTypesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/UpdateEntityType/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/UpdateEntityType/main.go index 83e0d58e8db7..758a0204982e 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/UpdateEntityType/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EntityTypesClient/UpdateEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/CreateEnvironment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/CreateEnvironment/main.go index 6d4f9297c18f..af34d3c7b49c 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/CreateEnvironment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/CreateEnvironment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateEnvironmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/DeleteEnvironment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/DeleteEnvironment/main.go index 65287b286d7e..ed9ffbef9724 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/DeleteEnvironment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/DeleteEnvironment/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteEnvironmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/GetEnvironment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/GetEnvironment/main.go index 0a687c1c2ff9..feb13f55603a 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/GetEnvironment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/GetEnvironment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetEnvironmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/ListEnvironments/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/ListEnvironments/main.go index d09ddaace9a5..c89078c6ed48 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/ListEnvironments/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/ListEnvironments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListEnvironmentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/LookupEnvironmentHistory/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/LookupEnvironmentHistory/main.go index f498b47d4389..5503fbbe74eb 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/LookupEnvironmentHistory/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/LookupEnvironmentHistory/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.LookupEnvironmentHistoryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/UpdateEnvironment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/UpdateEnvironment/main.go index f52c41228566..11a34f3172f2 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/UpdateEnvironment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/EnvironmentsClient/UpdateEnvironment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewEnvironmentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateEnvironmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/CreateExperiment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/CreateExperiment/main.go index 8367f4a6b9be..428a40191797 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/CreateExperiment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/CreateExperiment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateExperimentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/DeleteExperiment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/DeleteExperiment/main.go index 9fcb276c7794..45f6a8b3ea01 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/DeleteExperiment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/DeleteExperiment/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteExperimentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/GetExperiment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/GetExperiment/main.go index 2f24c35b04c0..1c4ade1f905c 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/GetExperiment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/GetExperiment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetExperimentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/ListExperiments/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/ListExperiments/main.go index e10be7de659c..20cc060981c7 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/ListExperiments/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/ListExperiments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListExperimentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/StartExperiment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/StartExperiment/main.go index 918fdfdd5e55..b9cef4b6f941 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/StartExperiment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/StartExperiment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.StartExperimentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/StopExperiment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/StopExperiment/main.go index fdeac0ef8783..2889da8563a0 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/StopExperiment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/StopExperiment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.StopExperimentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/UpdateExperiment/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/UpdateExperiment/main.go index 3db80010b5cf..4c40973a2b4b 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/UpdateExperiment/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/ExperimentsClient/UpdateExperiment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewExperimentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateExperimentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/CreateFlow/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/CreateFlow/main.go index 239d3ccc8978..07ba3fd01eef 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/CreateFlow/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/CreateFlow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateFlowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/DeleteFlow/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/DeleteFlow/main.go index 0e5e7b057c33..175cef4085a7 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/DeleteFlow/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/DeleteFlow/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteFlowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/ExportFlow/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/ExportFlow/main.go index f5399f494718..995a820e527e 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/ExportFlow/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/ExportFlow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ExportFlowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/GetFlow/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/GetFlow/main.go index ffa0ee4c3fcc..4bb9a3c96ed7 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/GetFlow/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/GetFlow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetFlowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/GetFlowValidationResult/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/GetFlowValidationResult/main.go index 812e92b7370b..423c12db6160 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/GetFlowValidationResult/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/GetFlowValidationResult/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetFlowValidationResultRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/ImportFlow/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/ImportFlow/main.go index a94d758bb825..0d99d2aba202 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/ImportFlow/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/ImportFlow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ImportFlowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/ListFlows/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/ListFlows/main.go index ce064413871f..05547fd55943 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/ListFlows/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/ListFlows/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListFlowsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/TrainFlow/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/TrainFlow/main.go index 9db42c1341d7..ce9122486ca7 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/TrainFlow/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/TrainFlow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.TrainFlowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/UpdateFlow/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/UpdateFlow/main.go index 0fd4aae8edf6..8ce26b510943 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/UpdateFlow/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/UpdateFlow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateFlowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/ValidateFlow/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/ValidateFlow/main.go index 6c02e78653c7..2f5d38f4fc9b 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/ValidateFlow/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/FlowsClient/ValidateFlow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewFlowsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ValidateFlowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/CreateIntent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/CreateIntent/main.go index 8f5d18eb3d75..196bf5b29aaa 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/CreateIntent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/CreateIntent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/DeleteIntent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/DeleteIntent/main.go index 7c7b660d517e..65f3fbeded94 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/DeleteIntent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/DeleteIntent/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/GetIntent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/GetIntent/main.go index 6d18c633f6b0..9072b33fc8f2 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/GetIntent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/GetIntent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/ListIntents/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/ListIntents/main.go index af0e2ddc14cd..709639f365b6 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/ListIntents/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/ListIntents/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListIntentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/UpdateIntent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/UpdateIntent/main.go index a6a5b48483da..a50f1b705c43 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/UpdateIntent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/IntentsClient/UpdateIntent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewIntentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/CreatePage/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/CreatePage/main.go index c84a87fe8d65..dce48a9def3b 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/CreatePage/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/CreatePage/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewPagesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreatePageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/DeletePage/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/DeletePage/main.go index e60e461141cc..af19281521be 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/DeletePage/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/DeletePage/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeletePageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/GetPage/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/GetPage/main.go index 6e1f94af4190..72871e9e9adf 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/GetPage/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/GetPage/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewPagesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetPageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/ListPages/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/ListPages/main.go index c427b904f5a0..42bf37fc9350 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/ListPages/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/ListPages/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewPagesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListPagesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/UpdatePage/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/UpdatePage/main.go index 2ee4fbd88e94..747b650408ed 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/UpdatePage/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/PagesClient/UpdatePage/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewPagesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdatePageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/CreateSecuritySettings/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/CreateSecuritySettings/main.go index 3dd234562a6e..7d90f9170bb3 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/CreateSecuritySettings/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/CreateSecuritySettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSecuritySettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateSecuritySettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/DeleteSecuritySettings/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/DeleteSecuritySettings/main.go index 257a154308c0..a8a42d21a84c 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/DeleteSecuritySettings/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/DeleteSecuritySettings/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteSecuritySettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/GetSecuritySettings/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/GetSecuritySettings/main.go index dfab8bb2d87b..4159ad779dff 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/GetSecuritySettings/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/GetSecuritySettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSecuritySettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetSecuritySettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/ListSecuritySettings/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/ListSecuritySettings/main.go index 200ebc3b0856..b665cbd223d4 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/ListSecuritySettings/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/ListSecuritySettings/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewSecuritySettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListSecuritySettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/UpdateSecuritySettings/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/UpdateSecuritySettings/main.go index ee90611da48c..f1795342c582 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/UpdateSecuritySettings/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SecuritySettingsClient/UpdateSecuritySettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSecuritySettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateSecuritySettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/CreateSessionEntityType/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/CreateSessionEntityType/main.go index 198143a92163..515eefdf1b4b 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/CreateSessionEntityType/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/CreateSessionEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateSessionEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/DeleteSessionEntityType/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/DeleteSessionEntityType/main.go index ccd64f0a8a4a..4cbff074dbe4 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/DeleteSessionEntityType/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/DeleteSessionEntityType/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteSessionEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/GetSessionEntityType/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/GetSessionEntityType/main.go index f9d749974cc2..b7e90b4e5c05 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/GetSessionEntityType/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/GetSessionEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetSessionEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/ListSessionEntityTypes/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/ListSessionEntityTypes/main.go index 8883701cb42c..b3aea5199bb1 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/ListSessionEntityTypes/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/ListSessionEntityTypes/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListSessionEntityTypesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/UpdateSessionEntityType/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/UpdateSessionEntityType/main.go index d07d5909fef0..e2c5559bb0a1 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/UpdateSessionEntityType/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionEntityTypesClient/UpdateSessionEntityType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSessionEntityTypesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateSessionEntityTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionsClient/DetectIntent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionsClient/DetectIntent/main.go index eaecf2f4db39..efd81b6f0fbc 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionsClient/DetectIntent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionsClient/DetectIntent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DetectIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionsClient/FulfillIntent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionsClient/FulfillIntent/main.go index 349b30b3f50c..786e26273a60 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionsClient/FulfillIntent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionsClient/FulfillIntent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.FulfillIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionsClient/MatchIntent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionsClient/MatchIntent/main.go index 903c6fca9f2c..e32759f91455 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionsClient/MatchIntent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionsClient/MatchIntent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.MatchIntentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionsClient/StreamingDetectIntent/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionsClient/StreamingDetectIntent/main.go index b5147ac2226a..b3cb9b949d02 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionsClient/StreamingDetectIntent/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/SessionsClient/StreamingDetectIntent/main.go @@ -25,13 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewSessionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.StreamingDetectIntent(ctx) if err != nil { // TODO: Handle error. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/BatchDeleteTestCases/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/BatchDeleteTestCases/main.go index c801a1f8d18e..b253bf982eef 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/BatchDeleteTestCases/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/BatchDeleteTestCases/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.BatchDeleteTestCasesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/BatchRunTestCases/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/BatchRunTestCases/main.go index a25df284feea..c12ab402fa5d 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/BatchRunTestCases/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/BatchRunTestCases/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.BatchRunTestCasesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/CalculateCoverage/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/CalculateCoverage/main.go index 31d9e7d90270..14543c988e73 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/CalculateCoverage/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/CalculateCoverage/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CalculateCoverageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/CreateTestCase/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/CreateTestCase/main.go index 4a8f19e95327..af284b8f80de 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/CreateTestCase/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/CreateTestCase/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateTestCaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/ExportTestCases/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/ExportTestCases/main.go index c5c9b892875a..a43dc32afde1 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/ExportTestCases/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/ExportTestCases/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ExportTestCasesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/GetTestCase/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/GetTestCase/main.go index 607f28d9dadb..f46a63eeba7f 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/GetTestCase/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/GetTestCase/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetTestCaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/GetTestCaseResult/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/GetTestCaseResult/main.go index 0d7f04c61008..20cd088f9c64 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/GetTestCaseResult/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/GetTestCaseResult/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetTestCaseResultRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/ImportTestCases/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/ImportTestCases/main.go index 6b7f25d86f57..0f3c8002d6d5 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/ImportTestCases/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/ImportTestCases/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ImportTestCasesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/ListTestCaseResults/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/ListTestCaseResults/main.go index 5af235e75519..4070a96f8fda 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/ListTestCaseResults/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/ListTestCaseResults/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListTestCaseResultsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/ListTestCases/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/ListTestCases/main.go index 497a4d17f881..3e47604f866d 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/ListTestCases/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/ListTestCases/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListTestCasesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/RunTestCase/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/RunTestCase/main.go index add3c04f6b19..73c7bbedf4f5 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/RunTestCase/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/RunTestCase/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.RunTestCaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/UpdateTestCase/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/UpdateTestCase/main.go index ac8dd0a5edaf..0d526f528ab0 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/UpdateTestCase/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TestCasesClient/UpdateTestCase/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTestCasesClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateTestCaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/CreateTransitionRouteGroup/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/CreateTransitionRouteGroup/main.go index 5beaed25e392..52812e7d5803 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/CreateTransitionRouteGroup/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/CreateTransitionRouteGroup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTransitionRouteGroupsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateTransitionRouteGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/DeleteTransitionRouteGroup/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/DeleteTransitionRouteGroup/main.go index 41cb4cea3eeb..bef895049737 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/DeleteTransitionRouteGroup/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/DeleteTransitionRouteGroup/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteTransitionRouteGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/GetTransitionRouteGroup/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/GetTransitionRouteGroup/main.go index 9ee0f9beb917..533bb9bb5eb9 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/GetTransitionRouteGroup/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/GetTransitionRouteGroup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTransitionRouteGroupsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetTransitionRouteGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/ListTransitionRouteGroups/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/ListTransitionRouteGroups/main.go index 50cb81cf306f..0a1b6ee8f77f 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/ListTransitionRouteGroups/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/ListTransitionRouteGroups/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewTransitionRouteGroupsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListTransitionRouteGroupsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/UpdateTransitionRouteGroup/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/UpdateTransitionRouteGroup/main.go index f32b211220dc..178997d53777 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/UpdateTransitionRouteGroup/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/TransitionRouteGroupsClient/UpdateTransitionRouteGroup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewTransitionRouteGroupsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateTransitionRouteGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/CreateVersion/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/CreateVersion/main.go index 95bcdd31b012..02b8a1cf42fa 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/CreateVersion/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/CreateVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/DeleteVersion/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/DeleteVersion/main.go index 8c8f3387b714..211ff8304eac 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/DeleteVersion/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/DeleteVersion/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/GetVersion/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/GetVersion/main.go index 1d72dc29e604..21e12b581573 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/GetVersion/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/GetVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/ListVersions/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/ListVersions/main.go index f5fe7735f5d8..b8583fa21c82 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/ListVersions/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/ListVersions/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListVersionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/LoadVersion/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/LoadVersion/main.go index 2be1cd6e68de..faee9d216c9a 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/LoadVersion/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/LoadVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.LoadVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/UpdateVersion/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/UpdateVersion/main.go index 9146e1ea2d81..317f1baa6e49 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/UpdateVersion/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/VersionsClient/UpdateVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewVersionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/CreateWebhook/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/CreateWebhook/main.go index 67822cd05c14..3026371ebad9 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/CreateWebhook/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/CreateWebhook/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewWebhooksClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.CreateWebhookRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/DeleteWebhook/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/DeleteWebhook/main.go index f5ba4beda931..aab3a3c5d1ec 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/DeleteWebhook/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/DeleteWebhook/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.DeleteWebhookRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/GetWebhook/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/GetWebhook/main.go index 646c1df4c0b2..17617b922d38 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/GetWebhook/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/GetWebhook/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewWebhooksClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.GetWebhookRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/ListWebhooks/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/ListWebhooks/main.go index ac4c18eda9bd..77b5aac36cea 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/ListWebhooks/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/ListWebhooks/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := cx.NewWebhooksClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.ListWebhooksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/UpdateWebhook/main.go b/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/UpdateWebhook/main.go index 68524afa24a6..6e5f2427bff5 100644 --- a/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/UpdateWebhook/main.go +++ b/internal/generated/snippets/dialogflow/cx/apiv3beta1/WebhooksClient/UpdateWebhook/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cxpb "google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3beta1" - ctx := context.Background() c, err := cx.NewWebhooksClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cxpb.UpdateWebhookRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/ActivateJobTrigger/main.go b/internal/generated/snippets/dlp/apiv2/Client/ActivateJobTrigger/main.go index 47b981d4dc6f..366455e018e4 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/ActivateJobTrigger/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/ActivateJobTrigger/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.ActivateJobTriggerRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/CancelDlpJob/main.go b/internal/generated/snippets/dlp/apiv2/Client/CancelDlpJob/main.go index 09bc36b7dd34..e3c519f8bb2e 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/CancelDlpJob/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/CancelDlpJob/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.CancelDlpJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/CreateDeidentifyTemplate/main.go b/internal/generated/snippets/dlp/apiv2/Client/CreateDeidentifyTemplate/main.go index b48d024e9357..4c9d7816ab69 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/CreateDeidentifyTemplate/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/CreateDeidentifyTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.CreateDeidentifyTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/CreateDlpJob/main.go b/internal/generated/snippets/dlp/apiv2/Client/CreateDlpJob/main.go index adca6c725e9c..437d8b8b34cc 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/CreateDlpJob/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/CreateDlpJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.CreateDlpJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/CreateInspectTemplate/main.go b/internal/generated/snippets/dlp/apiv2/Client/CreateInspectTemplate/main.go index 7963b23b346d..2180fb066b9a 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/CreateInspectTemplate/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/CreateInspectTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.CreateInspectTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/CreateJobTrigger/main.go b/internal/generated/snippets/dlp/apiv2/Client/CreateJobTrigger/main.go index a1ca1ccafc81..3053fa755e46 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/CreateJobTrigger/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/CreateJobTrigger/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.CreateJobTriggerRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/CreateStoredInfoType/main.go b/internal/generated/snippets/dlp/apiv2/Client/CreateStoredInfoType/main.go index cd7ed6f96211..780b7261b011 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/CreateStoredInfoType/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/CreateStoredInfoType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.CreateStoredInfoTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/DeidentifyContent/main.go b/internal/generated/snippets/dlp/apiv2/Client/DeidentifyContent/main.go index 3767c4210c36..9b5c81f9ac6c 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/DeidentifyContent/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/DeidentifyContent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.DeidentifyContentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/DeleteDeidentifyTemplate/main.go b/internal/generated/snippets/dlp/apiv2/Client/DeleteDeidentifyTemplate/main.go index f206a5c6d823..44718f1d8250 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/DeleteDeidentifyTemplate/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/DeleteDeidentifyTemplate/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.DeleteDeidentifyTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/DeleteDlpJob/main.go b/internal/generated/snippets/dlp/apiv2/Client/DeleteDlpJob/main.go index b7e6d3b7f733..c1bfbfe77e7c 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/DeleteDlpJob/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/DeleteDlpJob/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.DeleteDlpJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/DeleteInspectTemplate/main.go b/internal/generated/snippets/dlp/apiv2/Client/DeleteInspectTemplate/main.go index baa508924acb..88e4320a05d5 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/DeleteInspectTemplate/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/DeleteInspectTemplate/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.DeleteInspectTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/DeleteJobTrigger/main.go b/internal/generated/snippets/dlp/apiv2/Client/DeleteJobTrigger/main.go index 301eb0ebe2fb..4e5ae6b11d1f 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/DeleteJobTrigger/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/DeleteJobTrigger/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.DeleteJobTriggerRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/DeleteStoredInfoType/main.go b/internal/generated/snippets/dlp/apiv2/Client/DeleteStoredInfoType/main.go index a86f13ef3542..afe5cd813d62 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/DeleteStoredInfoType/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/DeleteStoredInfoType/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.DeleteStoredInfoTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/FinishDlpJob/main.go b/internal/generated/snippets/dlp/apiv2/Client/FinishDlpJob/main.go index 3eccd6ff873b..d52144282897 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/FinishDlpJob/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/FinishDlpJob/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.FinishDlpJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/GetDeidentifyTemplate/main.go b/internal/generated/snippets/dlp/apiv2/Client/GetDeidentifyTemplate/main.go index f1aab5123e59..6d9a13c5c569 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/GetDeidentifyTemplate/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/GetDeidentifyTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.GetDeidentifyTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/GetDlpJob/main.go b/internal/generated/snippets/dlp/apiv2/Client/GetDlpJob/main.go index b65084526571..bd17b35d4cce 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/GetDlpJob/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/GetDlpJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.GetDlpJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/GetInspectTemplate/main.go b/internal/generated/snippets/dlp/apiv2/Client/GetInspectTemplate/main.go index 8712882fe1d6..0bac7abc610f 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/GetInspectTemplate/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/GetInspectTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.GetInspectTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/GetJobTrigger/main.go b/internal/generated/snippets/dlp/apiv2/Client/GetJobTrigger/main.go index 23436db76110..e0d8553273ef 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/GetJobTrigger/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/GetJobTrigger/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.GetJobTriggerRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/GetStoredInfoType/main.go b/internal/generated/snippets/dlp/apiv2/Client/GetStoredInfoType/main.go index fcfd07873bc8..4dd9fc4da1b6 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/GetStoredInfoType/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/GetStoredInfoType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.GetStoredInfoTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/HybridInspectDlpJob/main.go b/internal/generated/snippets/dlp/apiv2/Client/HybridInspectDlpJob/main.go index 9b1b78e58973..0931a915408f 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/HybridInspectDlpJob/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/HybridInspectDlpJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.HybridInspectDlpJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/HybridInspectJobTrigger/main.go b/internal/generated/snippets/dlp/apiv2/Client/HybridInspectJobTrigger/main.go index 175b794e55ec..1258d7d722e1 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/HybridInspectJobTrigger/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/HybridInspectJobTrigger/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.HybridInspectJobTriggerRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/InspectContent/main.go b/internal/generated/snippets/dlp/apiv2/Client/InspectContent/main.go index 171a2187c48c..99ef8e8a47a3 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/InspectContent/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/InspectContent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.InspectContentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/ListDeidentifyTemplates/main.go b/internal/generated/snippets/dlp/apiv2/Client/ListDeidentifyTemplates/main.go index b56e394d1244..89f226c73f45 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/ListDeidentifyTemplates/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/ListDeidentifyTemplates/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.ListDeidentifyTemplatesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/ListDlpJobs/main.go b/internal/generated/snippets/dlp/apiv2/Client/ListDlpJobs/main.go index 9b963c157119..a5f6806775d9 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/ListDlpJobs/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/ListDlpJobs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.ListDlpJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/ListInfoTypes/main.go b/internal/generated/snippets/dlp/apiv2/Client/ListInfoTypes/main.go index 1415f14f241f..e5f8c0e6f657 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/ListInfoTypes/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/ListInfoTypes/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.ListInfoTypesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/ListInspectTemplates/main.go b/internal/generated/snippets/dlp/apiv2/Client/ListInspectTemplates/main.go index 44b4ed078825..812f259c1a96 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/ListInspectTemplates/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/ListInspectTemplates/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.ListInspectTemplatesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/ListJobTriggers/main.go b/internal/generated/snippets/dlp/apiv2/Client/ListJobTriggers/main.go index 4fec0e01526f..a8bd844d2cc2 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/ListJobTriggers/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/ListJobTriggers/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.ListJobTriggersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/ListStoredInfoTypes/main.go b/internal/generated/snippets/dlp/apiv2/Client/ListStoredInfoTypes/main.go index 6623f738671e..b0e17d186ed1 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/ListStoredInfoTypes/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/ListStoredInfoTypes/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.ListStoredInfoTypesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/RedactImage/main.go b/internal/generated/snippets/dlp/apiv2/Client/RedactImage/main.go index 6fb695ef67d4..8ad9934922bc 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/RedactImage/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/RedactImage/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.RedactImageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/ReidentifyContent/main.go b/internal/generated/snippets/dlp/apiv2/Client/ReidentifyContent/main.go index fe59b8200520..bee6a60eeaac 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/ReidentifyContent/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/ReidentifyContent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.ReidentifyContentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/UpdateDeidentifyTemplate/main.go b/internal/generated/snippets/dlp/apiv2/Client/UpdateDeidentifyTemplate/main.go index 9ef9185a4b7c..83cad4b15a2a 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/UpdateDeidentifyTemplate/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/UpdateDeidentifyTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.UpdateDeidentifyTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/UpdateInspectTemplate/main.go b/internal/generated/snippets/dlp/apiv2/Client/UpdateInspectTemplate/main.go index d95154b404a4..9b8f4e07e26b 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/UpdateInspectTemplate/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/UpdateInspectTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.UpdateInspectTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/UpdateJobTrigger/main.go b/internal/generated/snippets/dlp/apiv2/Client/UpdateJobTrigger/main.go index ab18c9e3896c..d4d13552390e 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/UpdateJobTrigger/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/UpdateJobTrigger/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.UpdateJobTriggerRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/dlp/apiv2/Client/UpdateStoredInfoType/main.go b/internal/generated/snippets/dlp/apiv2/Client/UpdateStoredInfoType/main.go index 5f273154f0cf..d3546aa46ca6 100644 --- a/internal/generated/snippets/dlp/apiv2/Client/UpdateStoredInfoType/main.go +++ b/internal/generated/snippets/dlp/apiv2/Client/UpdateStoredInfoType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dlppb "google.golang.org/genproto/googleapis/privacy/dlp/v2" - ctx := context.Background() c, err := dlp.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dlppb.UpdateStoredInfoTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/documentai/apiv1/DocumentProcessorClient/BatchProcessDocuments/main.go b/internal/generated/snippets/documentai/apiv1/DocumentProcessorClient/BatchProcessDocuments/main.go index 286dbae7e3de..38cdc47b4c6b 100644 --- a/internal/generated/snippets/documentai/apiv1/DocumentProcessorClient/BatchProcessDocuments/main.go +++ b/internal/generated/snippets/documentai/apiv1/DocumentProcessorClient/BatchProcessDocuments/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import documentaipb "google.golang.org/genproto/googleapis/cloud/documentai/v1" - ctx := context.Background() c, err := documentai.NewDocumentProcessorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &documentaipb.BatchProcessRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/documentai/apiv1/DocumentProcessorClient/ProcessDocument/main.go b/internal/generated/snippets/documentai/apiv1/DocumentProcessorClient/ProcessDocument/main.go index 4babe59bc682..67a325083d6a 100644 --- a/internal/generated/snippets/documentai/apiv1/DocumentProcessorClient/ProcessDocument/main.go +++ b/internal/generated/snippets/documentai/apiv1/DocumentProcessorClient/ProcessDocument/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import documentaipb "google.golang.org/genproto/googleapis/cloud/documentai/v1" - ctx := context.Background() c, err := documentai.NewDocumentProcessorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &documentaipb.ProcessRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/documentai/apiv1/DocumentProcessorClient/ReviewDocument/main.go b/internal/generated/snippets/documentai/apiv1/DocumentProcessorClient/ReviewDocument/main.go index 5d57ddcaf701..d78d4e17efac 100644 --- a/internal/generated/snippets/documentai/apiv1/DocumentProcessorClient/ReviewDocument/main.go +++ b/internal/generated/snippets/documentai/apiv1/DocumentProcessorClient/ReviewDocument/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import documentaipb "google.golang.org/genproto/googleapis/cloud/documentai/v1" - ctx := context.Background() c, err := documentai.NewDocumentProcessorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &documentaipb.ReviewDocumentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/documentai/apiv1beta3/DocumentProcessorClient/BatchProcessDocuments/main.go b/internal/generated/snippets/documentai/apiv1beta3/DocumentProcessorClient/BatchProcessDocuments/main.go index a1fe97852269..aec1b55af0b1 100644 --- a/internal/generated/snippets/documentai/apiv1beta3/DocumentProcessorClient/BatchProcessDocuments/main.go +++ b/internal/generated/snippets/documentai/apiv1beta3/DocumentProcessorClient/BatchProcessDocuments/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import documentaipb "google.golang.org/genproto/googleapis/cloud/documentai/v1beta3" - ctx := context.Background() c, err := documentai.NewDocumentProcessorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &documentaipb.BatchProcessRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/documentai/apiv1beta3/DocumentProcessorClient/ProcessDocument/main.go b/internal/generated/snippets/documentai/apiv1beta3/DocumentProcessorClient/ProcessDocument/main.go index b9b0ea4f9fe0..706c2d26d37d 100644 --- a/internal/generated/snippets/documentai/apiv1beta3/DocumentProcessorClient/ProcessDocument/main.go +++ b/internal/generated/snippets/documentai/apiv1beta3/DocumentProcessorClient/ProcessDocument/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import documentaipb "google.golang.org/genproto/googleapis/cloud/documentai/v1beta3" - ctx := context.Background() c, err := documentai.NewDocumentProcessorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &documentaipb.ProcessRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/documentai/apiv1beta3/DocumentProcessorClient/ReviewDocument/main.go b/internal/generated/snippets/documentai/apiv1beta3/DocumentProcessorClient/ReviewDocument/main.go index 0ddc864b2d3e..d9b2d5d22719 100644 --- a/internal/generated/snippets/documentai/apiv1beta3/DocumentProcessorClient/ReviewDocument/main.go +++ b/internal/generated/snippets/documentai/apiv1beta3/DocumentProcessorClient/ReviewDocument/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import documentaipb "google.golang.org/genproto/googleapis/cloud/documentai/v1beta3" - ctx := context.Background() c, err := documentai.NewDocumentProcessorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &documentaipb.ReviewDocumentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/domains/apiv1beta1/Client/ConfigureContactSettings/main.go b/internal/generated/snippets/domains/apiv1beta1/Client/ConfigureContactSettings/main.go index 4ac06ae4ea13..8309b71bafdb 100644 --- a/internal/generated/snippets/domains/apiv1beta1/Client/ConfigureContactSettings/main.go +++ b/internal/generated/snippets/domains/apiv1beta1/Client/ConfigureContactSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.ConfigureContactSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/domains/apiv1beta1/Client/ConfigureDnsSettings/main.go b/internal/generated/snippets/domains/apiv1beta1/Client/ConfigureDnsSettings/main.go index 4016e8040f80..718af17ff9fa 100644 --- a/internal/generated/snippets/domains/apiv1beta1/Client/ConfigureDnsSettings/main.go +++ b/internal/generated/snippets/domains/apiv1beta1/Client/ConfigureDnsSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.ConfigureDnsSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/domains/apiv1beta1/Client/ConfigureManagementSettings/main.go b/internal/generated/snippets/domains/apiv1beta1/Client/ConfigureManagementSettings/main.go index 0eb523aea8c6..51b9f34a9df5 100644 --- a/internal/generated/snippets/domains/apiv1beta1/Client/ConfigureManagementSettings/main.go +++ b/internal/generated/snippets/domains/apiv1beta1/Client/ConfigureManagementSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.ConfigureManagementSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/domains/apiv1beta1/Client/DeleteRegistration/main.go b/internal/generated/snippets/domains/apiv1beta1/Client/DeleteRegistration/main.go index 080b4472369b..ffb30e458a3e 100644 --- a/internal/generated/snippets/domains/apiv1beta1/Client/DeleteRegistration/main.go +++ b/internal/generated/snippets/domains/apiv1beta1/Client/DeleteRegistration/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.DeleteRegistrationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/domains/apiv1beta1/Client/ExportRegistration/main.go b/internal/generated/snippets/domains/apiv1beta1/Client/ExportRegistration/main.go index 89a7080dea2b..948fdbacbc8a 100644 --- a/internal/generated/snippets/domains/apiv1beta1/Client/ExportRegistration/main.go +++ b/internal/generated/snippets/domains/apiv1beta1/Client/ExportRegistration/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.ExportRegistrationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/domains/apiv1beta1/Client/GetRegistration/main.go b/internal/generated/snippets/domains/apiv1beta1/Client/GetRegistration/main.go index bfbfe8e13048..4c373fe0ad47 100644 --- a/internal/generated/snippets/domains/apiv1beta1/Client/GetRegistration/main.go +++ b/internal/generated/snippets/domains/apiv1beta1/Client/GetRegistration/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.GetRegistrationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/domains/apiv1beta1/Client/ListRegistrations/main.go b/internal/generated/snippets/domains/apiv1beta1/Client/ListRegistrations/main.go index 913d586be86e..6ca5fd9120f0 100644 --- a/internal/generated/snippets/domains/apiv1beta1/Client/ListRegistrations/main.go +++ b/internal/generated/snippets/domains/apiv1beta1/Client/ListRegistrations/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.ListRegistrationsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/domains/apiv1beta1/Client/RegisterDomain/main.go b/internal/generated/snippets/domains/apiv1beta1/Client/RegisterDomain/main.go index 9d017102bc5e..3b58c17946d0 100644 --- a/internal/generated/snippets/domains/apiv1beta1/Client/RegisterDomain/main.go +++ b/internal/generated/snippets/domains/apiv1beta1/Client/RegisterDomain/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.RegisterDomainRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/domains/apiv1beta1/Client/ResetAuthorizationCode/main.go b/internal/generated/snippets/domains/apiv1beta1/Client/ResetAuthorizationCode/main.go index 32ca0219cd92..e3c86559f0ec 100644 --- a/internal/generated/snippets/domains/apiv1beta1/Client/ResetAuthorizationCode/main.go +++ b/internal/generated/snippets/domains/apiv1beta1/Client/ResetAuthorizationCode/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.ResetAuthorizationCodeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/domains/apiv1beta1/Client/RetrieveAuthorizationCode/main.go b/internal/generated/snippets/domains/apiv1beta1/Client/RetrieveAuthorizationCode/main.go index 0f55f3f7ff80..8b6c877e0877 100644 --- a/internal/generated/snippets/domains/apiv1beta1/Client/RetrieveAuthorizationCode/main.go +++ b/internal/generated/snippets/domains/apiv1beta1/Client/RetrieveAuthorizationCode/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.RetrieveAuthorizationCodeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/domains/apiv1beta1/Client/RetrieveRegisterParameters/main.go b/internal/generated/snippets/domains/apiv1beta1/Client/RetrieveRegisterParameters/main.go index f1a07ecf6b77..0a0327f5655c 100644 --- a/internal/generated/snippets/domains/apiv1beta1/Client/RetrieveRegisterParameters/main.go +++ b/internal/generated/snippets/domains/apiv1beta1/Client/RetrieveRegisterParameters/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.RetrieveRegisterParametersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/domains/apiv1beta1/Client/SearchDomains/main.go b/internal/generated/snippets/domains/apiv1beta1/Client/SearchDomains/main.go index bfb8b676f4ac..8e56742080c7 100644 --- a/internal/generated/snippets/domains/apiv1beta1/Client/SearchDomains/main.go +++ b/internal/generated/snippets/domains/apiv1beta1/Client/SearchDomains/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.SearchDomainsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/domains/apiv1beta1/Client/UpdateRegistration/main.go b/internal/generated/snippets/domains/apiv1beta1/Client/UpdateRegistration/main.go index 1338c152fff8..24c2ebff4fe9 100644 --- a/internal/generated/snippets/domains/apiv1beta1/Client/UpdateRegistration/main.go +++ b/internal/generated/snippets/domains/apiv1beta1/Client/UpdateRegistration/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import domainspb "google.golang.org/genproto/googleapis/cloud/domains/v1beta1" - ctx := context.Background() c, err := domains.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &domainspb.UpdateRegistrationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/errorreporting/apiv1beta1/ErrorGroupClient/GetGroup/main.go b/internal/generated/snippets/errorreporting/apiv1beta1/ErrorGroupClient/GetGroup/main.go index 9880f33f1415..488a4086e580 100644 --- a/internal/generated/snippets/errorreporting/apiv1beta1/ErrorGroupClient/GetGroup/main.go +++ b/internal/generated/snippets/errorreporting/apiv1beta1/ErrorGroupClient/GetGroup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouderrorreportingpb "google.golang.org/genproto/googleapis/devtools/clouderrorreporting/v1beta1" - ctx := context.Background() c, err := errorreporting.NewErrorGroupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouderrorreportingpb.GetGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/errorreporting/apiv1beta1/ErrorGroupClient/UpdateGroup/main.go b/internal/generated/snippets/errorreporting/apiv1beta1/ErrorGroupClient/UpdateGroup/main.go index 99b99ab7fe1c..9eeeef5de438 100644 --- a/internal/generated/snippets/errorreporting/apiv1beta1/ErrorGroupClient/UpdateGroup/main.go +++ b/internal/generated/snippets/errorreporting/apiv1beta1/ErrorGroupClient/UpdateGroup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouderrorreportingpb "google.golang.org/genproto/googleapis/devtools/clouderrorreporting/v1beta1" - ctx := context.Background() c, err := errorreporting.NewErrorGroupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouderrorreportingpb.UpdateGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/errorreporting/apiv1beta1/ErrorStatsClient/DeleteEvents/main.go b/internal/generated/snippets/errorreporting/apiv1beta1/ErrorStatsClient/DeleteEvents/main.go index 175dc78da98a..c66a1a9cebb6 100644 --- a/internal/generated/snippets/errorreporting/apiv1beta1/ErrorStatsClient/DeleteEvents/main.go +++ b/internal/generated/snippets/errorreporting/apiv1beta1/ErrorStatsClient/DeleteEvents/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouderrorreportingpb "google.golang.org/genproto/googleapis/devtools/clouderrorreporting/v1beta1" - ctx := context.Background() c, err := errorreporting.NewErrorStatsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouderrorreportingpb.DeleteEventsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/errorreporting/apiv1beta1/ErrorStatsClient/ListEvents/main.go b/internal/generated/snippets/errorreporting/apiv1beta1/ErrorStatsClient/ListEvents/main.go index 280c0017214b..4cca20fb220d 100644 --- a/internal/generated/snippets/errorreporting/apiv1beta1/ErrorStatsClient/ListEvents/main.go +++ b/internal/generated/snippets/errorreporting/apiv1beta1/ErrorStatsClient/ListEvents/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import clouderrorreportingpb "google.golang.org/genproto/googleapis/devtools/clouderrorreporting/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := errorreporting.NewErrorStatsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouderrorreportingpb.ListEventsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/errorreporting/apiv1beta1/ErrorStatsClient/ListGroupStats/main.go b/internal/generated/snippets/errorreporting/apiv1beta1/ErrorStatsClient/ListGroupStats/main.go index 597d3e4dacbb..6424fe02c727 100644 --- a/internal/generated/snippets/errorreporting/apiv1beta1/ErrorStatsClient/ListGroupStats/main.go +++ b/internal/generated/snippets/errorreporting/apiv1beta1/ErrorStatsClient/ListGroupStats/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import clouderrorreportingpb "google.golang.org/genproto/googleapis/devtools/clouderrorreporting/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := errorreporting.NewErrorStatsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouderrorreportingpb.ListGroupStatsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/errorreporting/apiv1beta1/ReportErrorsClient/ReportErrorEvent/main.go b/internal/generated/snippets/errorreporting/apiv1beta1/ReportErrorsClient/ReportErrorEvent/main.go index 4aa1a0f75fec..b19cc399ba74 100644 --- a/internal/generated/snippets/errorreporting/apiv1beta1/ReportErrorsClient/ReportErrorEvent/main.go +++ b/internal/generated/snippets/errorreporting/apiv1beta1/ReportErrorsClient/ReportErrorEvent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import clouderrorreportingpb "google.golang.org/genproto/googleapis/devtools/clouderrorreporting/v1beta1" - ctx := context.Background() c, err := errorreporting.NewReportErrorsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &clouderrorreportingpb.ReportErrorEventRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/Client/BatchWrite/main.go b/internal/generated/snippets/firestore/apiv1/Client/BatchWrite/main.go index c280f4e2f316..c968d77e2a47 100644 --- a/internal/generated/snippets/firestore/apiv1/Client/BatchWrite/main.go +++ b/internal/generated/snippets/firestore/apiv1/Client/BatchWrite/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.BatchWriteRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/Client/BeginTransaction/main.go b/internal/generated/snippets/firestore/apiv1/Client/BeginTransaction/main.go index 45d4470636f7..af87133777b1 100644 --- a/internal/generated/snippets/firestore/apiv1/Client/BeginTransaction/main.go +++ b/internal/generated/snippets/firestore/apiv1/Client/BeginTransaction/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.BeginTransactionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/Client/Commit/main.go b/internal/generated/snippets/firestore/apiv1/Client/Commit/main.go index e568839696f1..6552277b1053 100644 --- a/internal/generated/snippets/firestore/apiv1/Client/Commit/main.go +++ b/internal/generated/snippets/firestore/apiv1/Client/Commit/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.CommitRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/Client/CreateDocument/main.go b/internal/generated/snippets/firestore/apiv1/Client/CreateDocument/main.go index f9d8d9f8a7d1..9900e8716f5e 100644 --- a/internal/generated/snippets/firestore/apiv1/Client/CreateDocument/main.go +++ b/internal/generated/snippets/firestore/apiv1/Client/CreateDocument/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.CreateDocumentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/Client/DeleteDocument/main.go b/internal/generated/snippets/firestore/apiv1/Client/DeleteDocument/main.go index b34dd650a480..64eed2566a2e 100644 --- a/internal/generated/snippets/firestore/apiv1/Client/DeleteDocument/main.go +++ b/internal/generated/snippets/firestore/apiv1/Client/DeleteDocument/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.DeleteDocumentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/Client/GetDocument/main.go b/internal/generated/snippets/firestore/apiv1/Client/GetDocument/main.go index 745692457a24..9c534339163c 100644 --- a/internal/generated/snippets/firestore/apiv1/Client/GetDocument/main.go +++ b/internal/generated/snippets/firestore/apiv1/Client/GetDocument/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.GetDocumentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/Client/ListCollectionIds/main.go b/internal/generated/snippets/firestore/apiv1/Client/ListCollectionIds/main.go index df9944d6ab33..b32160be7f8d 100644 --- a/internal/generated/snippets/firestore/apiv1/Client/ListCollectionIds/main.go +++ b/internal/generated/snippets/firestore/apiv1/Client/ListCollectionIds/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.ListCollectionIdsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/Client/ListDocuments/main.go b/internal/generated/snippets/firestore/apiv1/Client/ListDocuments/main.go index cfb54c69d29b..8d747d156c0d 100644 --- a/internal/generated/snippets/firestore/apiv1/Client/ListDocuments/main.go +++ b/internal/generated/snippets/firestore/apiv1/Client/ListDocuments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.ListDocumentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/Client/Listen/main.go b/internal/generated/snippets/firestore/apiv1/Client/Listen/main.go index e8de12e9da08..8b2c19608205 100644 --- a/internal/generated/snippets/firestore/apiv1/Client/Listen/main.go +++ b/internal/generated/snippets/firestore/apiv1/Client/Listen/main.go @@ -25,13 +25,12 @@ import ( ) func main() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.Listen(ctx) if err != nil { // TODO: Handle error. diff --git a/internal/generated/snippets/firestore/apiv1/Client/PartitionQuery/main.go b/internal/generated/snippets/firestore/apiv1/Client/PartitionQuery/main.go index 0a43c136f5f4..26bfff6347b8 100644 --- a/internal/generated/snippets/firestore/apiv1/Client/PartitionQuery/main.go +++ b/internal/generated/snippets/firestore/apiv1/Client/PartitionQuery/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.PartitionQueryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/Client/Rollback/main.go b/internal/generated/snippets/firestore/apiv1/Client/Rollback/main.go index 555b0831ec70..4090a57a09e7 100644 --- a/internal/generated/snippets/firestore/apiv1/Client/Rollback/main.go +++ b/internal/generated/snippets/firestore/apiv1/Client/Rollback/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.RollbackRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/Client/UpdateDocument/main.go b/internal/generated/snippets/firestore/apiv1/Client/UpdateDocument/main.go index ee475ba2cb67..e1152e0619ce 100644 --- a/internal/generated/snippets/firestore/apiv1/Client/UpdateDocument/main.go +++ b/internal/generated/snippets/firestore/apiv1/Client/UpdateDocument/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &firestorepb.UpdateDocumentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/Client/Write/main.go b/internal/generated/snippets/firestore/apiv1/Client/Write/main.go index 6309aef2c4b4..229bbc9422b4 100644 --- a/internal/generated/snippets/firestore/apiv1/Client/Write/main.go +++ b/internal/generated/snippets/firestore/apiv1/Client/Write/main.go @@ -25,13 +25,12 @@ import ( ) func main() { - // import firestorepb "google.golang.org/genproto/googleapis/firestore/v1" - ctx := context.Background() c, err := firestore.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.Write(ctx) if err != nil { // TODO: Handle error. diff --git a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/CreateIndex/main.go b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/CreateIndex/main.go index 6ce928e0d11c..fc146c0ab0ad 100644 --- a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/CreateIndex/main.go +++ b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/CreateIndex/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/firestore/admin/v1" - ctx := context.Background() c, err := apiv1.NewFirestoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.CreateIndexRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/DeleteIndex/main.go b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/DeleteIndex/main.go index 5ffc5e249997..b52540792399 100644 --- a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/DeleteIndex/main.go +++ b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/DeleteIndex/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.DeleteIndexRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/ExportDocuments/main.go b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/ExportDocuments/main.go index e237725fd4bf..e3d8dd9955e2 100644 --- a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/ExportDocuments/main.go +++ b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/ExportDocuments/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/firestore/admin/v1" - ctx := context.Background() c, err := apiv1.NewFirestoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ExportDocumentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/GetField/main.go b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/GetField/main.go index c8478cdea639..4c38cd6b0a49 100644 --- a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/GetField/main.go +++ b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/GetField/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/firestore/admin/v1" - ctx := context.Background() c, err := apiv1.NewFirestoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetFieldRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/GetIndex/main.go b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/GetIndex/main.go index 9f32dadbad9e..e92cb58d709e 100644 --- a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/GetIndex/main.go +++ b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/GetIndex/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/firestore/admin/v1" - ctx := context.Background() c, err := apiv1.NewFirestoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.GetIndexRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/ImportDocuments/main.go b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/ImportDocuments/main.go index 2996b699a730..2c82f5f3af87 100644 --- a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/ImportDocuments/main.go +++ b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/ImportDocuments/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/firestore/admin/v1" - ctx := context.Background() c, err := apiv1.NewFirestoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ImportDocumentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/ListFields/main.go b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/ListFields/main.go index eb6abeb6f2a4..0747310f92a3 100644 --- a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/ListFields/main.go +++ b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/ListFields/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/firestore/admin/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := apiv1.NewFirestoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListFieldsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/ListIndexes/main.go b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/ListIndexes/main.go index bf199d231be1..0edf92d1d2f5 100644 --- a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/ListIndexes/main.go +++ b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/ListIndexes/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/firestore/admin/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := apiv1.NewFirestoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.ListIndexesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/UpdateField/main.go b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/UpdateField/main.go index e3d3a126da23..2f2e30505c30 100644 --- a/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/UpdateField/main.go +++ b/internal/generated/snippets/firestore/apiv1/admin/FirestoreAdminClient/UpdateField/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import adminpb "google.golang.org/genproto/googleapis/firestore/admin/v1" - ctx := context.Background() c, err := apiv1.NewFirestoreAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &adminpb.UpdateFieldRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/CallFunction/main.go b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/CallFunction/main.go index 214c32441adf..5c3d5c0b1036 100644 --- a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/CallFunction/main.go +++ b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/CallFunction/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import functionspb "google.golang.org/genproto/googleapis/cloud/functions/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &functionspb.CallFunctionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/CreateFunction/main.go b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/CreateFunction/main.go index a1625e728cef..28ce6d5381f2 100644 --- a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/CreateFunction/main.go +++ b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/CreateFunction/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import functionspb "google.golang.org/genproto/googleapis/cloud/functions/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &functionspb.CreateFunctionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/DeleteFunction/main.go b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/DeleteFunction/main.go index 1a267f2b64f0..0c09d25ce1c8 100644 --- a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/DeleteFunction/main.go +++ b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/DeleteFunction/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import functionspb "google.golang.org/genproto/googleapis/cloud/functions/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &functionspb.DeleteFunctionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/GenerateDownloadUrl/main.go b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/GenerateDownloadUrl/main.go index 2fb7112f589c..7fa92ed5d063 100644 --- a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/GenerateDownloadUrl/main.go +++ b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/GenerateDownloadUrl/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import functionspb "google.golang.org/genproto/googleapis/cloud/functions/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &functionspb.GenerateDownloadUrlRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/GenerateUploadUrl/main.go b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/GenerateUploadUrl/main.go index 883a33812955..7048cdde7e80 100644 --- a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/GenerateUploadUrl/main.go +++ b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/GenerateUploadUrl/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import functionspb "google.golang.org/genproto/googleapis/cloud/functions/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &functionspb.GenerateUploadUrlRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/GetFunction/main.go b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/GetFunction/main.go index faff44076364..25e23b1fdcc7 100644 --- a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/GetFunction/main.go +++ b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/GetFunction/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import functionspb "google.golang.org/genproto/googleapis/cloud/functions/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &functionspb.GetFunctionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/GetIamPolicy/main.go b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/GetIamPolicy/main.go index 33a58c111eb2..7ff3916d14c9 100644 --- a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/GetIamPolicy/main.go +++ b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/ListFunctions/main.go b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/ListFunctions/main.go index da595d0ebdb5..f7ece9038b1f 100644 --- a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/ListFunctions/main.go +++ b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/ListFunctions/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import functionspb "google.golang.org/genproto/googleapis/cloud/functions/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &functionspb.ListFunctionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/SetIamPolicy/main.go b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/SetIamPolicy/main.go index 8f5b34fe584c..7afe2bbd5779 100644 --- a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/SetIamPolicy/main.go +++ b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/TestIamPermissions/main.go b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/TestIamPermissions/main.go index 804243f4cfd2..17fb966fd59d 100644 --- a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/TestIamPermissions/main.go +++ b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/UpdateFunction/main.go b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/UpdateFunction/main.go index 4e123495175d..1a85349a1c7a 100644 --- a/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/UpdateFunction/main.go +++ b/internal/generated/snippets/functions/apiv1/CloudFunctionsClient/UpdateFunction/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import functionspb "google.golang.org/genproto/googleapis/cloud/functions/v1" - ctx := context.Background() c, err := functions.NewCloudFunctionsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &functionspb.UpdateFunctionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/CreateGameServerCluster/main.go b/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/CreateGameServerCluster/main.go index 50b1ca2fd43e..8fc0d2be6ccb 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/CreateGameServerCluster/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/CreateGameServerCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.CreateGameServerClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/DeleteGameServerCluster/main.go b/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/DeleteGameServerCluster/main.go index 0c7369c88f8f..3f2031fc1f13 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/DeleteGameServerCluster/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/DeleteGameServerCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.DeleteGameServerClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/GetGameServerCluster/main.go b/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/GetGameServerCluster/main.go index ee63d0c85ade..62f9569bcef8 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/GetGameServerCluster/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/GetGameServerCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetGameServerClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/ListGameServerClusters/main.go b/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/ListGameServerClusters/main.go index e8c523735ff1..8f72b966d002 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/ListGameServerClusters/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/ListGameServerClusters/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.ListGameServerClustersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/PreviewCreateGameServerCluster/main.go b/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/PreviewCreateGameServerCluster/main.go index 5e874d91875a..9ee070828d0a 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/PreviewCreateGameServerCluster/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/PreviewCreateGameServerCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewCreateGameServerClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/PreviewDeleteGameServerCluster/main.go b/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/PreviewDeleteGameServerCluster/main.go index 9773889bf2f7..f4c40496dc37 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/PreviewDeleteGameServerCluster/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/PreviewDeleteGameServerCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewDeleteGameServerClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/PreviewUpdateGameServerCluster/main.go b/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/PreviewUpdateGameServerCluster/main.go index e647e13cb9f7..bfc25fb92f10 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/PreviewUpdateGameServerCluster/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/PreviewUpdateGameServerCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewUpdateGameServerClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/UpdateGameServerCluster/main.go b/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/UpdateGameServerCluster/main.go index f3b5510a23b3..528219537727 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/UpdateGameServerCluster/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerClustersClient/UpdateGameServerCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.UpdateGameServerClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerConfigsClient/CreateGameServerConfig/main.go b/internal/generated/snippets/gaming/apiv1/GameServerConfigsClient/CreateGameServerConfig/main.go index bebe234fd8a0..8613d2826009 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerConfigsClient/CreateGameServerConfig/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerConfigsClient/CreateGameServerConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerConfigsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.CreateGameServerConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerConfigsClient/DeleteGameServerConfig/main.go b/internal/generated/snippets/gaming/apiv1/GameServerConfigsClient/DeleteGameServerConfig/main.go index c0ea13c93124..4133e12dd78e 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerConfigsClient/DeleteGameServerConfig/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerConfigsClient/DeleteGameServerConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerConfigsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.DeleteGameServerConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerConfigsClient/GetGameServerConfig/main.go b/internal/generated/snippets/gaming/apiv1/GameServerConfigsClient/GetGameServerConfig/main.go index b0f152dc806d..8d8ae09249d6 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerConfigsClient/GetGameServerConfig/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerConfigsClient/GetGameServerConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerConfigsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetGameServerConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerConfigsClient/ListGameServerConfigs/main.go b/internal/generated/snippets/gaming/apiv1/GameServerConfigsClient/ListGameServerConfigs/main.go index f7deca744b97..3338310db8c7 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerConfigsClient/ListGameServerConfigs/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerConfigsClient/ListGameServerConfigs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gaming.NewGameServerConfigsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.ListGameServerConfigsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/CreateGameServerDeployment/main.go b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/CreateGameServerDeployment/main.go index 1e775856e948..8ccd25616189 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/CreateGameServerDeployment/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/CreateGameServerDeployment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.CreateGameServerDeploymentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/DeleteGameServerDeployment/main.go b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/DeleteGameServerDeployment/main.go index edac09c4f20e..915e681d6927 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/DeleteGameServerDeployment/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/DeleteGameServerDeployment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.DeleteGameServerDeploymentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/FetchDeploymentState/main.go b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/FetchDeploymentState/main.go index c4be70111b4b..6d516cfc066f 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/FetchDeploymentState/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/FetchDeploymentState/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.FetchDeploymentStateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/GetGameServerDeployment/main.go b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/GetGameServerDeployment/main.go index 445a9545185d..4d2d910704d0 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/GetGameServerDeployment/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/GetGameServerDeployment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetGameServerDeploymentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/GetGameServerDeploymentRollout/main.go b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/GetGameServerDeploymentRollout/main.go index 9817efdfef01..0c20200c8178 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/GetGameServerDeploymentRollout/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/GetGameServerDeploymentRollout/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetGameServerDeploymentRolloutRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/ListGameServerDeployments/main.go b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/ListGameServerDeployments/main.go index 466b6c1bb670..e07a19446d59 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/ListGameServerDeployments/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/ListGameServerDeployments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.ListGameServerDeploymentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/PreviewGameServerDeploymentRollout/main.go b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/PreviewGameServerDeploymentRollout/main.go index 6d1d400516b1..5cfa4e485703 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/PreviewGameServerDeploymentRollout/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/PreviewGameServerDeploymentRollout/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewGameServerDeploymentRolloutRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/UpdateGameServerDeployment/main.go b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/UpdateGameServerDeployment/main.go index 6926003720f4..bfa5265b1fe8 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/UpdateGameServerDeployment/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/UpdateGameServerDeployment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.UpdateGameServerDeploymentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/UpdateGameServerDeploymentRollout/main.go b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/UpdateGameServerDeploymentRollout/main.go index 38241865f022..e2652a5cdad9 100644 --- a/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/UpdateGameServerDeploymentRollout/main.go +++ b/internal/generated/snippets/gaming/apiv1/GameServerDeploymentsClient/UpdateGameServerDeploymentRollout/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.UpdateGameServerDeploymentRolloutRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/RealmsClient/CreateRealm/main.go b/internal/generated/snippets/gaming/apiv1/RealmsClient/CreateRealm/main.go index 529a35e75400..07ca2db0490c 100644 --- a/internal/generated/snippets/gaming/apiv1/RealmsClient/CreateRealm/main.go +++ b/internal/generated/snippets/gaming/apiv1/RealmsClient/CreateRealm/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.CreateRealmRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/RealmsClient/DeleteRealm/main.go b/internal/generated/snippets/gaming/apiv1/RealmsClient/DeleteRealm/main.go index 712f8668fd7c..efad6be03573 100644 --- a/internal/generated/snippets/gaming/apiv1/RealmsClient/DeleteRealm/main.go +++ b/internal/generated/snippets/gaming/apiv1/RealmsClient/DeleteRealm/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.DeleteRealmRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/RealmsClient/GetRealm/main.go b/internal/generated/snippets/gaming/apiv1/RealmsClient/GetRealm/main.go index 11e1793209a9..c37ca859657f 100644 --- a/internal/generated/snippets/gaming/apiv1/RealmsClient/GetRealm/main.go +++ b/internal/generated/snippets/gaming/apiv1/RealmsClient/GetRealm/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetRealmRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/RealmsClient/ListRealms/main.go b/internal/generated/snippets/gaming/apiv1/RealmsClient/ListRealms/main.go index 5a4e46d80649..4712f14074e7 100644 --- a/internal/generated/snippets/gaming/apiv1/RealmsClient/ListRealms/main.go +++ b/internal/generated/snippets/gaming/apiv1/RealmsClient/ListRealms/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.ListRealmsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/RealmsClient/PreviewRealmUpdate/main.go b/internal/generated/snippets/gaming/apiv1/RealmsClient/PreviewRealmUpdate/main.go index b9a504f81bff..16509b235f11 100644 --- a/internal/generated/snippets/gaming/apiv1/RealmsClient/PreviewRealmUpdate/main.go +++ b/internal/generated/snippets/gaming/apiv1/RealmsClient/PreviewRealmUpdate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewRealmUpdateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1/RealmsClient/UpdateRealm/main.go b/internal/generated/snippets/gaming/apiv1/RealmsClient/UpdateRealm/main.go index d20fa985ead1..37916702d5fd 100644 --- a/internal/generated/snippets/gaming/apiv1/RealmsClient/UpdateRealm/main.go +++ b/internal/generated/snippets/gaming/apiv1/RealmsClient/UpdateRealm/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.UpdateRealmRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/CreateGameServerCluster/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/CreateGameServerCluster/main.go index 933f38b59b6f..e601f9099725 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/CreateGameServerCluster/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/CreateGameServerCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.CreateGameServerClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/DeleteGameServerCluster/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/DeleteGameServerCluster/main.go index 1ca71d53b769..486c282fa58f 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/DeleteGameServerCluster/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/DeleteGameServerCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.DeleteGameServerClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/GetGameServerCluster/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/GetGameServerCluster/main.go index 5dfd95450c2d..4143655c0d2f 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/GetGameServerCluster/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/GetGameServerCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetGameServerClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/ListGameServerClusters/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/ListGameServerClusters/main.go index eb0b621684bf..4591da4e2978 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/ListGameServerClusters/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/ListGameServerClusters/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.ListGameServerClustersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/PreviewCreateGameServerCluster/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/PreviewCreateGameServerCluster/main.go index 5fdb469087c5..a573be652f40 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/PreviewCreateGameServerCluster/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/PreviewCreateGameServerCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewCreateGameServerClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/PreviewDeleteGameServerCluster/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/PreviewDeleteGameServerCluster/main.go index 7066716cfa82..de1577729f13 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/PreviewDeleteGameServerCluster/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/PreviewDeleteGameServerCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewDeleteGameServerClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/PreviewUpdateGameServerCluster/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/PreviewUpdateGameServerCluster/main.go index 23d32b0d2ceb..b2383a6d93d6 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/PreviewUpdateGameServerCluster/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/PreviewUpdateGameServerCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewUpdateGameServerClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/UpdateGameServerCluster/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/UpdateGameServerCluster/main.go index 08bfce06cd47..2f9e183a1a37 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/UpdateGameServerCluster/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerClustersClient/UpdateGameServerCluster/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerClustersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.UpdateGameServerClusterRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerConfigsClient/CreateGameServerConfig/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerConfigsClient/CreateGameServerConfig/main.go index 5dcf5b1dd591..f1910ca21b79 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerConfigsClient/CreateGameServerConfig/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerConfigsClient/CreateGameServerConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerConfigsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.CreateGameServerConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerConfigsClient/DeleteGameServerConfig/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerConfigsClient/DeleteGameServerConfig/main.go index cf8890825a50..ea2cdef83afa 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerConfigsClient/DeleteGameServerConfig/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerConfigsClient/DeleteGameServerConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerConfigsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.DeleteGameServerConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerConfigsClient/GetGameServerConfig/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerConfigsClient/GetGameServerConfig/main.go index 117fa790ab9a..5fe95be30375 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerConfigsClient/GetGameServerConfig/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerConfigsClient/GetGameServerConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerConfigsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetGameServerConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerConfigsClient/ListGameServerConfigs/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerConfigsClient/ListGameServerConfigs/main.go index bb035d872e48..f6d36d9c8f02 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerConfigsClient/ListGameServerConfigs/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerConfigsClient/ListGameServerConfigs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gaming.NewGameServerConfigsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.ListGameServerConfigsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/CreateGameServerDeployment/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/CreateGameServerDeployment/main.go index 527d5deb4217..76385431af30 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/CreateGameServerDeployment/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/CreateGameServerDeployment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.CreateGameServerDeploymentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/DeleteGameServerDeployment/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/DeleteGameServerDeployment/main.go index 6caf9bbbc0a7..9371b5bc4080 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/DeleteGameServerDeployment/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/DeleteGameServerDeployment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.DeleteGameServerDeploymentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/FetchDeploymentState/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/FetchDeploymentState/main.go index 98c88150507c..748413e3c612 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/FetchDeploymentState/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/FetchDeploymentState/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.FetchDeploymentStateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/GetGameServerDeployment/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/GetGameServerDeployment/main.go index 6480af68ba99..9dc272f9389e 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/GetGameServerDeployment/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/GetGameServerDeployment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetGameServerDeploymentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/GetGameServerDeploymentRollout/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/GetGameServerDeploymentRollout/main.go index 3d9401f43605..9a7845ea46f7 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/GetGameServerDeploymentRollout/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/GetGameServerDeploymentRollout/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetGameServerDeploymentRolloutRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/ListGameServerDeployments/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/ListGameServerDeployments/main.go index 3ddbcc51c1aa..c2212a793036 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/ListGameServerDeployments/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/ListGameServerDeployments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.ListGameServerDeploymentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/PreviewGameServerDeploymentRollout/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/PreviewGameServerDeploymentRollout/main.go index ea91b9108aac..f30148b41d73 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/PreviewGameServerDeploymentRollout/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/PreviewGameServerDeploymentRollout/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewGameServerDeploymentRolloutRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/UpdateGameServerDeployment/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/UpdateGameServerDeployment/main.go index 3c4fc40e6b83..abd487525f6d 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/UpdateGameServerDeployment/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/UpdateGameServerDeployment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.UpdateGameServerDeploymentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/UpdateGameServerDeploymentRollout/main.go b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/UpdateGameServerDeploymentRollout/main.go index 2d7c99238f69..92b3e371328a 100644 --- a/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/UpdateGameServerDeploymentRollout/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/GameServerDeploymentsClient/UpdateGameServerDeploymentRollout/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewGameServerDeploymentsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.UpdateGameServerDeploymentRolloutRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/RealmsClient/CreateRealm/main.go b/internal/generated/snippets/gaming/apiv1beta/RealmsClient/CreateRealm/main.go index 984e23fd8551..a382d6124025 100644 --- a/internal/generated/snippets/gaming/apiv1beta/RealmsClient/CreateRealm/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/RealmsClient/CreateRealm/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.CreateRealmRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/RealmsClient/DeleteRealm/main.go b/internal/generated/snippets/gaming/apiv1beta/RealmsClient/DeleteRealm/main.go index 769d36260990..501adeb140a0 100644 --- a/internal/generated/snippets/gaming/apiv1beta/RealmsClient/DeleteRealm/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/RealmsClient/DeleteRealm/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.DeleteRealmRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/RealmsClient/GetRealm/main.go b/internal/generated/snippets/gaming/apiv1beta/RealmsClient/GetRealm/main.go index 117e6ad1911f..867cd9b7d4fa 100644 --- a/internal/generated/snippets/gaming/apiv1beta/RealmsClient/GetRealm/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/RealmsClient/GetRealm/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.GetRealmRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/RealmsClient/ListRealms/main.go b/internal/generated/snippets/gaming/apiv1beta/RealmsClient/ListRealms/main.go index 947b1bdd96ac..c2b04eabba02 100644 --- a/internal/generated/snippets/gaming/apiv1beta/RealmsClient/ListRealms/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/RealmsClient/ListRealms/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.ListRealmsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/RealmsClient/PreviewRealmUpdate/main.go b/internal/generated/snippets/gaming/apiv1beta/RealmsClient/PreviewRealmUpdate/main.go index 582a31b59341..a85490859e03 100644 --- a/internal/generated/snippets/gaming/apiv1beta/RealmsClient/PreviewRealmUpdate/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/RealmsClient/PreviewRealmUpdate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.PreviewRealmUpdateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gaming/apiv1beta/RealmsClient/UpdateRealm/main.go b/internal/generated/snippets/gaming/apiv1beta/RealmsClient/UpdateRealm/main.go index 1ae7eba4868f..7b538993a1c8 100644 --- a/internal/generated/snippets/gaming/apiv1beta/RealmsClient/UpdateRealm/main.go +++ b/internal/generated/snippets/gaming/apiv1beta/RealmsClient/UpdateRealm/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1beta" - ctx := context.Background() c, err := gaming.NewRealmsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gamingpb.UpdateRealmRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/CreateMembership/main.go b/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/CreateMembership/main.go index c4a1c37aaf8b..e59839efd6f3 100644 --- a/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/CreateMembership/main.go +++ b/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/CreateMembership/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gkehubpb "google.golang.org/genproto/googleapis/cloud/gkehub/v1beta1" - ctx := context.Background() c, err := gkehub.NewGkeHubMembershipClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gkehubpb.CreateMembershipRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/DeleteMembership/main.go b/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/DeleteMembership/main.go index 3ab1c9713e4f..8c3f8b3cf218 100644 --- a/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/DeleteMembership/main.go +++ b/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/DeleteMembership/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gkehubpb "google.golang.org/genproto/googleapis/cloud/gkehub/v1beta1" - ctx := context.Background() c, err := gkehub.NewGkeHubMembershipClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gkehubpb.DeleteMembershipRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/GenerateConnectManifest/main.go b/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/GenerateConnectManifest/main.go index 1fcf2d7f2a2c..ac7c98528e93 100644 --- a/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/GenerateConnectManifest/main.go +++ b/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/GenerateConnectManifest/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gkehubpb "google.golang.org/genproto/googleapis/cloud/gkehub/v1beta1" - ctx := context.Background() c, err := gkehub.NewGkeHubMembershipClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gkehubpb.GenerateConnectManifestRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/GenerateExclusivityManifest/main.go b/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/GenerateExclusivityManifest/main.go index 9d38ac263f0d..94e79c9327a4 100644 --- a/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/GenerateExclusivityManifest/main.go +++ b/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/GenerateExclusivityManifest/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gkehubpb "google.golang.org/genproto/googleapis/cloud/gkehub/v1beta1" - ctx := context.Background() c, err := gkehub.NewGkeHubMembershipClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gkehubpb.GenerateExclusivityManifestRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/GetMembership/main.go b/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/GetMembership/main.go index b2fc357ebdb8..6a3c7f4f59b6 100644 --- a/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/GetMembership/main.go +++ b/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/GetMembership/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gkehubpb "google.golang.org/genproto/googleapis/cloud/gkehub/v1beta1" - ctx := context.Background() c, err := gkehub.NewGkeHubMembershipClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gkehubpb.GetMembershipRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/ListMemberships/main.go b/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/ListMemberships/main.go index 79bbf3bcd12e..65f46d57af98 100644 --- a/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/ListMemberships/main.go +++ b/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/ListMemberships/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import gkehubpb "google.golang.org/genproto/googleapis/cloud/gkehub/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := gkehub.NewGkeHubMembershipClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gkehubpb.ListMembershipsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/UpdateMembership/main.go b/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/UpdateMembership/main.go index 50615aa81293..9b6c8c3b8ead 100644 --- a/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/UpdateMembership/main.go +++ b/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/UpdateMembership/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gkehubpb "google.golang.org/genproto/googleapis/cloud/gkehub/v1beta1" - ctx := context.Background() c, err := gkehub.NewGkeHubMembershipClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gkehubpb.UpdateMembershipRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/ValidateExclusivity/main.go b/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/ValidateExclusivity/main.go index ca6adea36879..6a034b12e477 100644 --- a/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/ValidateExclusivity/main.go +++ b/internal/generated/snippets/gkehub/apiv1beta1/GkeHubMembershipClient/ValidateExclusivity/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import gkehubpb "google.golang.org/genproto/googleapis/cloud/gkehub/v1beta1" - ctx := context.Background() c, err := gkehub.NewGkeHubMembershipClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &gkehubpb.ValidateExclusivityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/go.mod b/internal/generated/snippets/go.mod index af3987ad2826..ad4172e9dc6f 100644 --- a/internal/generated/snippets/go.mod +++ b/internal/generated/snippets/go.mod @@ -32,5 +32,5 @@ require ( cloud.google.com/go/pubsublite v0.0.0-00010101000000-000000000000 cloud.google.com/go/spanner v0.0.0-00010101000000-000000000000 google.golang.org/api v0.46.0 - google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a + google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d ) diff --git a/internal/generated/snippets/go.sum b/internal/generated/snippets/go.sum index b7184909b593..b728e66f96a4 100644 --- a/internal/generated/snippets/go.sum +++ b/internal/generated/snippets/go.sum @@ -142,9 +142,9 @@ google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98 google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/genproto v0.0.0-20210429181445-86c259c2b4ab/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= google.golang.org/genproto v0.0.0-20210506142907-4a47615972c2/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= -google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= -google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a h1:VA0wtJaR+W1I11P2f535J7D/YxyvEFMTMvcmyeZ9FBE= google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d h1:bRz6UmsZEz/CzoTjUDp4ZcdguhSWi6CyU299wMQBpZU= +google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= diff --git a/internal/generated/snippets/iam/credentials/apiv1/IamCredentialsClient/GenerateAccessToken/main.go b/internal/generated/snippets/iam/credentials/apiv1/IamCredentialsClient/GenerateAccessToken/main.go index 9e4887e1cd94..1fcd0929a520 100644 --- a/internal/generated/snippets/iam/credentials/apiv1/IamCredentialsClient/GenerateAccessToken/main.go +++ b/internal/generated/snippets/iam/credentials/apiv1/IamCredentialsClient/GenerateAccessToken/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import credentialspb "google.golang.org/genproto/googleapis/iam/credentials/v1" - ctx := context.Background() c, err := credentials.NewIamCredentialsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &credentialspb.GenerateAccessTokenRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iam/credentials/apiv1/IamCredentialsClient/GenerateIdToken/main.go b/internal/generated/snippets/iam/credentials/apiv1/IamCredentialsClient/GenerateIdToken/main.go index baeea5191ede..12fabd76d8a7 100644 --- a/internal/generated/snippets/iam/credentials/apiv1/IamCredentialsClient/GenerateIdToken/main.go +++ b/internal/generated/snippets/iam/credentials/apiv1/IamCredentialsClient/GenerateIdToken/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import credentialspb "google.golang.org/genproto/googleapis/iam/credentials/v1" - ctx := context.Background() c, err := credentials.NewIamCredentialsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &credentialspb.GenerateIdTokenRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iam/credentials/apiv1/IamCredentialsClient/SignBlob/main.go b/internal/generated/snippets/iam/credentials/apiv1/IamCredentialsClient/SignBlob/main.go index 600c9e824d19..b33f5d008524 100644 --- a/internal/generated/snippets/iam/credentials/apiv1/IamCredentialsClient/SignBlob/main.go +++ b/internal/generated/snippets/iam/credentials/apiv1/IamCredentialsClient/SignBlob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import credentialspb "google.golang.org/genproto/googleapis/iam/credentials/v1" - ctx := context.Background() c, err := credentials.NewIamCredentialsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &credentialspb.SignBlobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iam/credentials/apiv1/IamCredentialsClient/SignJwt/main.go b/internal/generated/snippets/iam/credentials/apiv1/IamCredentialsClient/SignJwt/main.go index ff5cd5186923..2cfff64f63b6 100644 --- a/internal/generated/snippets/iam/credentials/apiv1/IamCredentialsClient/SignJwt/main.go +++ b/internal/generated/snippets/iam/credentials/apiv1/IamCredentialsClient/SignJwt/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import credentialspb "google.golang.org/genproto/googleapis/iam/credentials/v1" - ctx := context.Background() c, err := credentials.NewIamCredentialsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &credentialspb.SignJwtRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/BindDeviceToGateway/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/BindDeviceToGateway/main.go index 3e8549221a63..79c36910c32e 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/BindDeviceToGateway/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/BindDeviceToGateway/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.BindDeviceToGatewayRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/CreateDevice/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/CreateDevice/main.go index d909e28abda8..3e00c7a635cd 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/CreateDevice/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/CreateDevice/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.CreateDeviceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/CreateDeviceRegistry/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/CreateDeviceRegistry/main.go index 05b0f9aa0e65..d143ef8a78cf 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/CreateDeviceRegistry/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/CreateDeviceRegistry/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.CreateDeviceRegistryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/DeleteDevice/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/DeleteDevice/main.go index afcf65eda0ff..667edbe93c6e 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/DeleteDevice/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/DeleteDevice/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.DeleteDeviceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/DeleteDeviceRegistry/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/DeleteDeviceRegistry/main.go index 6f0ec7674262..a34b57d52a3e 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/DeleteDeviceRegistry/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/DeleteDeviceRegistry/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.DeleteDeviceRegistryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/GetDevice/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/GetDevice/main.go index 884e7fb174c9..515f9d18d31d 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/GetDevice/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/GetDevice/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.GetDeviceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/GetDeviceRegistry/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/GetDeviceRegistry/main.go index d740e29b6998..3f5d650280bf 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/GetDeviceRegistry/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/GetDeviceRegistry/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.GetDeviceRegistryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/GetIamPolicy/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/GetIamPolicy/main.go index 94c011bbbd50..1f2c5db1911e 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/GetIamPolicy/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ListDeviceConfigVersions/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ListDeviceConfigVersions/main.go index 29ba0f7fe294..2b5fca02d555 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ListDeviceConfigVersions/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ListDeviceConfigVersions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.ListDeviceConfigVersionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ListDeviceRegistries/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ListDeviceRegistries/main.go index b5e85817c0db..b0bed608d008 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ListDeviceRegistries/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ListDeviceRegistries/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.ListDeviceRegistriesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ListDeviceStates/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ListDeviceStates/main.go index 02dc29781e86..1aca527ca134 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ListDeviceStates/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ListDeviceStates/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.ListDeviceStatesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ListDevices/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ListDevices/main.go index 1fd349760afc..6a9fd394f2f5 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ListDevices/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ListDevices/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.ListDevicesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ModifyCloudToDeviceConfig/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ModifyCloudToDeviceConfig/main.go index 2f11f99004d1..8d04d7f7845d 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ModifyCloudToDeviceConfig/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/ModifyCloudToDeviceConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.ModifyCloudToDeviceConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/SendCommandToDevice/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/SendCommandToDevice/main.go index 3d49a174ce65..395cf335c146 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/SendCommandToDevice/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/SendCommandToDevice/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.SendCommandToDeviceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/SetIamPolicy/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/SetIamPolicy/main.go index ffef68cdcb34..23b18073bfaf 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/SetIamPolicy/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/TestIamPermissions/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/TestIamPermissions/main.go index d24b2995bdf1..0538fc429dd2 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/TestIamPermissions/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/UnbindDeviceFromGateway/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/UnbindDeviceFromGateway/main.go index 53648e642107..0cb11abfc76e 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/UnbindDeviceFromGateway/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/UnbindDeviceFromGateway/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.UnbindDeviceFromGatewayRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/UpdateDevice/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/UpdateDevice/main.go index 4fcdb0c53638..9bfe7b0e509b 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/UpdateDevice/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/UpdateDevice/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.UpdateDeviceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/UpdateDeviceRegistry/main.go b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/UpdateDeviceRegistry/main.go index 01ef6e621cbd..3d8a0b156a0b 100644 --- a/internal/generated/snippets/iot/apiv1/DeviceManagerClient/UpdateDeviceRegistry/main.go +++ b/internal/generated/snippets/iot/apiv1/DeviceManagerClient/UpdateDeviceRegistry/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.UpdateDeviceRegistryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/AsymmetricDecrypt/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/AsymmetricDecrypt/main.go index 14768d2a6c05..6d49136e6991 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/AsymmetricDecrypt/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/AsymmetricDecrypt/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.AsymmetricDecryptRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/AsymmetricSign/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/AsymmetricSign/main.go index 252ca7ab3f89..4fc3b63a2aaa 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/AsymmetricSign/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/AsymmetricSign/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.AsymmetricSignRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/CreateCryptoKey/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/CreateCryptoKey/main.go index a42e42c08130..24a9f6e54f6c 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/CreateCryptoKey/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/CreateCryptoKey/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.CreateCryptoKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/CreateCryptoKeyVersion/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/CreateCryptoKeyVersion/main.go index 2b4faf5752b6..6378f9595634 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/CreateCryptoKeyVersion/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/CreateCryptoKeyVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.CreateCryptoKeyVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/CreateImportJob/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/CreateImportJob/main.go index 8f3484dacd1f..1d62784b1ce4 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/CreateImportJob/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/CreateImportJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.CreateImportJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/CreateKeyRing/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/CreateKeyRing/main.go index 1430d3172100..965acd78a04d 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/CreateKeyRing/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/CreateKeyRing/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.CreateKeyRingRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/Decrypt/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/Decrypt/main.go index a80a7702a503..3ce5dc108e03 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/Decrypt/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/Decrypt/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.DecryptRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/DestroyCryptoKeyVersion/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/DestroyCryptoKeyVersion/main.go index 9ace7d1f7980..e74100bd581a 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/DestroyCryptoKeyVersion/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/DestroyCryptoKeyVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.DestroyCryptoKeyVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/Encrypt/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/Encrypt/main.go index 643110a539f1..4738f0f51f1b 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/Encrypt/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/Encrypt/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.EncryptRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetCryptoKey/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetCryptoKey/main.go index df98e30054d4..ef07d2a0c9a2 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetCryptoKey/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetCryptoKey/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.GetCryptoKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetCryptoKeyVersion/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetCryptoKeyVersion/main.go index 293dd8834f60..c16ddc3a30a9 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetCryptoKeyVersion/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetCryptoKeyVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.GetCryptoKeyVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetImportJob/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetImportJob/main.go index 457e8d946f28..f002e0f7f407 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetImportJob/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetImportJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.GetImportJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetKeyRing/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetKeyRing/main.go index 40d8e147ac73..56d3446ca2cb 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetKeyRing/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetKeyRing/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.GetKeyRingRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetPublicKey/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetPublicKey/main.go index a5bae62e5a85..cb056063851d 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetPublicKey/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/GetPublicKey/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.GetPublicKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/ImportCryptoKeyVersion/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/ImportCryptoKeyVersion/main.go index e393f93a3c32..fdec4336b77b 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/ImportCryptoKeyVersion/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/ImportCryptoKeyVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.ImportCryptoKeyVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/ListCryptoKeyVersions/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/ListCryptoKeyVersions/main.go index cfe548af862b..5acbcc07326f 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/ListCryptoKeyVersions/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/ListCryptoKeyVersions/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.ListCryptoKeyVersionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/ListCryptoKeys/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/ListCryptoKeys/main.go index e734bbee1f50..948fc650e28e 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/ListCryptoKeys/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/ListCryptoKeys/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.ListCryptoKeysRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/ListImportJobs/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/ListImportJobs/main.go index c4ccb52e1739..26be26a1f7f5 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/ListImportJobs/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/ListImportJobs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.ListImportJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/ListKeyRings/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/ListKeyRings/main.go index 904b1f0a10fe..266f8f7871be 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/ListKeyRings/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/ListKeyRings/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.ListKeyRingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/RestoreCryptoKeyVersion/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/RestoreCryptoKeyVersion/main.go index 0b67adef3651..143e8bf3fea8 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/RestoreCryptoKeyVersion/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/RestoreCryptoKeyVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.RestoreCryptoKeyVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/UpdateCryptoKey/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/UpdateCryptoKey/main.go index 8996d6b2b248..6771c91f1d2f 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/UpdateCryptoKey/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/UpdateCryptoKey/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.UpdateCryptoKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/UpdateCryptoKeyPrimaryVersion/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/UpdateCryptoKeyPrimaryVersion/main.go index 212ae73e768d..37df90d71751 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/UpdateCryptoKeyPrimaryVersion/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/UpdateCryptoKeyPrimaryVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.UpdateCryptoKeyPrimaryVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/kms/apiv1/KeyManagementClient/UpdateCryptoKeyVersion/main.go b/internal/generated/snippets/kms/apiv1/KeyManagementClient/UpdateCryptoKeyVersion/main.go index 222bdbf3d96c..c673de27bfe2 100644 --- a/internal/generated/snippets/kms/apiv1/KeyManagementClient/UpdateCryptoKeyVersion/main.go +++ b/internal/generated/snippets/kms/apiv1/KeyManagementClient/UpdateCryptoKeyVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.UpdateCryptoKeyVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/language/apiv1/Client/AnalyzeEntities/main.go b/internal/generated/snippets/language/apiv1/Client/AnalyzeEntities/main.go index bdc40a743af1..5a6da545d438 100644 --- a/internal/generated/snippets/language/apiv1/Client/AnalyzeEntities/main.go +++ b/internal/generated/snippets/language/apiv1/Client/AnalyzeEntities/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnalyzeEntitiesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/language/apiv1/Client/AnalyzeEntitySentiment/main.go b/internal/generated/snippets/language/apiv1/Client/AnalyzeEntitySentiment/main.go index 0313f94576d3..db9b878b9f9f 100644 --- a/internal/generated/snippets/language/apiv1/Client/AnalyzeEntitySentiment/main.go +++ b/internal/generated/snippets/language/apiv1/Client/AnalyzeEntitySentiment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnalyzeEntitySentimentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/language/apiv1/Client/AnalyzeSentiment/main.go b/internal/generated/snippets/language/apiv1/Client/AnalyzeSentiment/main.go index 17b44126e8f6..a534de94250b 100644 --- a/internal/generated/snippets/language/apiv1/Client/AnalyzeSentiment/main.go +++ b/internal/generated/snippets/language/apiv1/Client/AnalyzeSentiment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnalyzeSentimentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/language/apiv1/Client/AnalyzeSyntax/main.go b/internal/generated/snippets/language/apiv1/Client/AnalyzeSyntax/main.go index cef87d6fad51..28c710e9600c 100644 --- a/internal/generated/snippets/language/apiv1/Client/AnalyzeSyntax/main.go +++ b/internal/generated/snippets/language/apiv1/Client/AnalyzeSyntax/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnalyzeSyntaxRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/language/apiv1/Client/AnnotateText/main.go b/internal/generated/snippets/language/apiv1/Client/AnnotateText/main.go index 3f05b2bc2eae..31edc7278d4a 100644 --- a/internal/generated/snippets/language/apiv1/Client/AnnotateText/main.go +++ b/internal/generated/snippets/language/apiv1/Client/AnnotateText/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnnotateTextRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/language/apiv1/Client/ClassifyText/main.go b/internal/generated/snippets/language/apiv1/Client/ClassifyText/main.go index 34f4f267c8bc..f9fb9807e27a 100644 --- a/internal/generated/snippets/language/apiv1/Client/ClassifyText/main.go +++ b/internal/generated/snippets/language/apiv1/Client/ClassifyText/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.ClassifyTextRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/language/apiv1beta2/Client/AnalyzeEntities/main.go b/internal/generated/snippets/language/apiv1beta2/Client/AnalyzeEntities/main.go index e1cf5741ca94..8f9ff28fe247 100644 --- a/internal/generated/snippets/language/apiv1beta2/Client/AnalyzeEntities/main.go +++ b/internal/generated/snippets/language/apiv1beta2/Client/AnalyzeEntities/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1beta2" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnalyzeEntitiesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/language/apiv1beta2/Client/AnalyzeEntitySentiment/main.go b/internal/generated/snippets/language/apiv1beta2/Client/AnalyzeEntitySentiment/main.go index 0477343cbc4e..a9042555ca7d 100644 --- a/internal/generated/snippets/language/apiv1beta2/Client/AnalyzeEntitySentiment/main.go +++ b/internal/generated/snippets/language/apiv1beta2/Client/AnalyzeEntitySentiment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1beta2" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnalyzeEntitySentimentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/language/apiv1beta2/Client/AnalyzeSentiment/main.go b/internal/generated/snippets/language/apiv1beta2/Client/AnalyzeSentiment/main.go index 695381574387..2a1cb3ffa4cf 100644 --- a/internal/generated/snippets/language/apiv1beta2/Client/AnalyzeSentiment/main.go +++ b/internal/generated/snippets/language/apiv1beta2/Client/AnalyzeSentiment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1beta2" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnalyzeSentimentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/language/apiv1beta2/Client/AnalyzeSyntax/main.go b/internal/generated/snippets/language/apiv1beta2/Client/AnalyzeSyntax/main.go index 1d5c77b6aa69..3a1e8dd41308 100644 --- a/internal/generated/snippets/language/apiv1beta2/Client/AnalyzeSyntax/main.go +++ b/internal/generated/snippets/language/apiv1beta2/Client/AnalyzeSyntax/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1beta2" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnalyzeSyntaxRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/language/apiv1beta2/Client/AnnotateText/main.go b/internal/generated/snippets/language/apiv1beta2/Client/AnnotateText/main.go index a695cc42ea58..2830701f1c6e 100644 --- a/internal/generated/snippets/language/apiv1beta2/Client/AnnotateText/main.go +++ b/internal/generated/snippets/language/apiv1beta2/Client/AnnotateText/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1beta2" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnnotateTextRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/language/apiv1beta2/Client/ClassifyText/main.go b/internal/generated/snippets/language/apiv1beta2/Client/ClassifyText/main.go index dc65e4ce44cd..454e31be3589 100644 --- a/internal/generated/snippets/language/apiv1beta2/Client/ClassifyText/main.go +++ b/internal/generated/snippets/language/apiv1beta2/Client/ClassifyText/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1beta2" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.ClassifyTextRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/Client/DeleteLog/main.go b/internal/generated/snippets/logging/apiv2/Client/DeleteLog/main.go index 8fbf6af7fbb5..d4d8631b2cf9 100644 --- a/internal/generated/snippets/logging/apiv2/Client/DeleteLog/main.go +++ b/internal/generated/snippets/logging/apiv2/Client/DeleteLog/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.DeleteLogRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/Client/ListLogEntries/main.go b/internal/generated/snippets/logging/apiv2/Client/ListLogEntries/main.go index f81c3aa832ef..c1f3eca9a58d 100644 --- a/internal/generated/snippets/logging/apiv2/Client/ListLogEntries/main.go +++ b/internal/generated/snippets/logging/apiv2/Client/ListLogEntries/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := logging.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.ListLogEntriesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/Client/ListLogs/main.go b/internal/generated/snippets/logging/apiv2/Client/ListLogs/main.go index 205d1dc71ef8..e51d5db52189 100644 --- a/internal/generated/snippets/logging/apiv2/Client/ListLogs/main.go +++ b/internal/generated/snippets/logging/apiv2/Client/ListLogs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := logging.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.ListLogsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/Client/ListMonitoredResourceDescriptors/main.go b/internal/generated/snippets/logging/apiv2/Client/ListMonitoredResourceDescriptors/main.go index d0ddc7c4f972..bb2e8fabbbbf 100644 --- a/internal/generated/snippets/logging/apiv2/Client/ListMonitoredResourceDescriptors/main.go +++ b/internal/generated/snippets/logging/apiv2/Client/ListMonitoredResourceDescriptors/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := logging.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.ListMonitoredResourceDescriptorsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/Client/TailLogEntries/main.go b/internal/generated/snippets/logging/apiv2/Client/TailLogEntries/main.go index f3ea6fd335f7..f5f2558ef05e 100644 --- a/internal/generated/snippets/logging/apiv2/Client/TailLogEntries/main.go +++ b/internal/generated/snippets/logging/apiv2/Client/TailLogEntries/main.go @@ -25,13 +25,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.TailLogEntries(ctx) if err != nil { // TODO: Handle error. diff --git a/internal/generated/snippets/logging/apiv2/Client/WriteLogEntries/main.go b/internal/generated/snippets/logging/apiv2/Client/WriteLogEntries/main.go index 814a06d931ba..2a67d8c31705 100644 --- a/internal/generated/snippets/logging/apiv2/Client/WriteLogEntries/main.go +++ b/internal/generated/snippets/logging/apiv2/Client/WriteLogEntries/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.WriteLogEntriesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/CreateBucket/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/CreateBucket/main.go index a37f0fcbfe89..5ff692c63786 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/CreateBucket/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/CreateBucket/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.CreateBucketRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/CreateExclusion/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/CreateExclusion/main.go index 986d677ccb19..5807dec765ca 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/CreateExclusion/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/CreateExclusion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.CreateExclusionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/CreateSink/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/CreateSink/main.go index 2dd72e485fee..2fe2799f8c1d 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/CreateSink/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/CreateSink/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.CreateSinkRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/CreateView/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/CreateView/main.go index f24e4e352f20..88af615e1e67 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/CreateView/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/CreateView/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.CreateViewRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/DeleteBucket/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/DeleteBucket/main.go index 4adef411858b..9c67bb456a23 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/DeleteBucket/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/DeleteBucket/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.DeleteBucketRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/DeleteExclusion/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/DeleteExclusion/main.go index 298c907f84f1..55d1de1fc8df 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/DeleteExclusion/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/DeleteExclusion/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.DeleteExclusionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/DeleteSink/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/DeleteSink/main.go index f6cad54ac1c5..60b024c6fbb1 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/DeleteSink/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/DeleteSink/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.DeleteSinkRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/DeleteView/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/DeleteView/main.go index 6533fa76a494..86ef5b20b85c 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/DeleteView/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/DeleteView/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.DeleteViewRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/GetBucket/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/GetBucket/main.go index a71aaf682d17..7d25a5d35d85 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/GetBucket/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/GetBucket/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.GetBucketRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/GetCmekSettings/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/GetCmekSettings/main.go index 0ea0d51bbf81..f8773a9019e3 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/GetCmekSettings/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/GetCmekSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.GetCmekSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/GetExclusion/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/GetExclusion/main.go index fe09f9552ddd..e5b992e4deeb 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/GetExclusion/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/GetExclusion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.GetExclusionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/GetSink/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/GetSink/main.go index 190bde75dd6c..8c445b4437c8 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/GetSink/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/GetSink/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.GetSinkRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/GetView/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/GetView/main.go index 58eab5560a7f..63892e1c610f 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/GetView/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/GetView/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.GetViewRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/ListBuckets/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/ListBuckets/main.go index b13064691f83..ba3e5e93858e 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/ListBuckets/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/ListBuckets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.ListBucketsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/ListExclusions/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/ListExclusions/main.go index dfa26a367ee6..957736ecfaeb 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/ListExclusions/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/ListExclusions/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.ListExclusionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/ListSinks/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/ListSinks/main.go index e894c28870aa..4aa8c9234994 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/ListSinks/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/ListSinks/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.ListSinksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/ListViews/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/ListViews/main.go index 894ac9ff133c..cd2c68f414de 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/ListViews/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/ListViews/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.ListViewsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/UndeleteBucket/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/UndeleteBucket/main.go index 29e190f79e4c..a88b6077f1e5 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/UndeleteBucket/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/UndeleteBucket/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.UndeleteBucketRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateBucket/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateBucket/main.go index bb6447754e0f..5b7b2e04b96f 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateBucket/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateBucket/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.UpdateBucketRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateCmekSettings/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateCmekSettings/main.go index b1454b876279..2c1ec5d5a1f5 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateCmekSettings/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateCmekSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.UpdateCmekSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateExclusion/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateExclusion/main.go index da9753c09292..708eb4073fe2 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateExclusion/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateExclusion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.UpdateExclusionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateSink/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateSink/main.go index feec3efa39e4..0993eac317c0 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateSink/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateSink/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.UpdateSinkRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateView/main.go b/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateView/main.go index 2e0b3ccda0b4..c53fa4aad424 100644 --- a/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateView/main.go +++ b/internal/generated/snippets/logging/apiv2/ConfigClient/UpdateView/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.UpdateViewRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/MetricsClient/CreateLogMetric/main.go b/internal/generated/snippets/logging/apiv2/MetricsClient/CreateLogMetric/main.go index c3c376f6d88b..2a2fe12b184a 100644 --- a/internal/generated/snippets/logging/apiv2/MetricsClient/CreateLogMetric/main.go +++ b/internal/generated/snippets/logging/apiv2/MetricsClient/CreateLogMetric/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewMetricsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.CreateLogMetricRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/MetricsClient/DeleteLogMetric/main.go b/internal/generated/snippets/logging/apiv2/MetricsClient/DeleteLogMetric/main.go index 98ae24859969..85da24fee1ec 100644 --- a/internal/generated/snippets/logging/apiv2/MetricsClient/DeleteLogMetric/main.go +++ b/internal/generated/snippets/logging/apiv2/MetricsClient/DeleteLogMetric/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.DeleteLogMetricRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/MetricsClient/GetLogMetric/main.go b/internal/generated/snippets/logging/apiv2/MetricsClient/GetLogMetric/main.go index 8dedc9208388..3edad464efeb 100644 --- a/internal/generated/snippets/logging/apiv2/MetricsClient/GetLogMetric/main.go +++ b/internal/generated/snippets/logging/apiv2/MetricsClient/GetLogMetric/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewMetricsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.GetLogMetricRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/MetricsClient/ListLogMetrics/main.go b/internal/generated/snippets/logging/apiv2/MetricsClient/ListLogMetrics/main.go index b6f1e527857d..499013724244 100644 --- a/internal/generated/snippets/logging/apiv2/MetricsClient/ListLogMetrics/main.go +++ b/internal/generated/snippets/logging/apiv2/MetricsClient/ListLogMetrics/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := logging.NewMetricsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.ListLogMetricsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/logging/apiv2/MetricsClient/UpdateLogMetric/main.go b/internal/generated/snippets/logging/apiv2/MetricsClient/UpdateLogMetric/main.go index 10144f4c9967..6d2c2d022e1a 100644 --- a/internal/generated/snippets/logging/apiv2/MetricsClient/UpdateLogMetric/main.go +++ b/internal/generated/snippets/logging/apiv2/MetricsClient/UpdateLogMetric/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewMetricsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.UpdateLogMetricRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/longrunning/autogen/OperationsClient/CancelOperation/main.go b/internal/generated/snippets/longrunning/autogen/OperationsClient/CancelOperation/main.go index 32f373b53b29..628922122695 100644 --- a/internal/generated/snippets/longrunning/autogen/OperationsClient/CancelOperation/main.go +++ b/internal/generated/snippets/longrunning/autogen/OperationsClient/CancelOperation/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &longrunningpb.CancelOperationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/longrunning/autogen/OperationsClient/DeleteOperation/main.go b/internal/generated/snippets/longrunning/autogen/OperationsClient/DeleteOperation/main.go index 2dc6f811e956..17da22cdabab 100644 --- a/internal/generated/snippets/longrunning/autogen/OperationsClient/DeleteOperation/main.go +++ b/internal/generated/snippets/longrunning/autogen/OperationsClient/DeleteOperation/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &longrunningpb.DeleteOperationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/longrunning/autogen/OperationsClient/GetOperation/main.go b/internal/generated/snippets/longrunning/autogen/OperationsClient/GetOperation/main.go index 7b730556b37d..d8cf467f3179 100644 --- a/internal/generated/snippets/longrunning/autogen/OperationsClient/GetOperation/main.go +++ b/internal/generated/snippets/longrunning/autogen/OperationsClient/GetOperation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import longrunningpb "google.golang.org/genproto/googleapis/longrunning" - ctx := context.Background() c, err := longrunning.NewOperationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &longrunningpb.GetOperationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/longrunning/autogen/OperationsClient/ListOperations/main.go b/internal/generated/snippets/longrunning/autogen/OperationsClient/ListOperations/main.go index ae8e986e7e74..2bddc9a62efd 100644 --- a/internal/generated/snippets/longrunning/autogen/OperationsClient/ListOperations/main.go +++ b/internal/generated/snippets/longrunning/autogen/OperationsClient/ListOperations/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import longrunningpb "google.golang.org/genproto/googleapis/longrunning" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := longrunning.NewOperationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &longrunningpb.ListOperationsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/longrunning/autogen/OperationsClient/WaitOperation/main.go b/internal/generated/snippets/longrunning/autogen/OperationsClient/WaitOperation/main.go index 347845df3f31..bcc1602b6bde 100644 --- a/internal/generated/snippets/longrunning/autogen/OperationsClient/WaitOperation/main.go +++ b/internal/generated/snippets/longrunning/autogen/OperationsClient/WaitOperation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import longrunningpb "google.golang.org/genproto/googleapis/longrunning" - ctx := context.Background() c, err := longrunning.NewOperationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &longrunningpb.WaitOperationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/managedidentities/apiv1/Client/AttachTrust/main.go b/internal/generated/snippets/managedidentities/apiv1/Client/AttachTrust/main.go index dd634a4a3d8e..c9fea731bf54 100644 --- a/internal/generated/snippets/managedidentities/apiv1/Client/AttachTrust/main.go +++ b/internal/generated/snippets/managedidentities/apiv1/Client/AttachTrust/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.AttachTrustRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/managedidentities/apiv1/Client/CreateMicrosoftAdDomain/main.go b/internal/generated/snippets/managedidentities/apiv1/Client/CreateMicrosoftAdDomain/main.go index 46819b0044c5..be67ec74f78a 100644 --- a/internal/generated/snippets/managedidentities/apiv1/Client/CreateMicrosoftAdDomain/main.go +++ b/internal/generated/snippets/managedidentities/apiv1/Client/CreateMicrosoftAdDomain/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.CreateMicrosoftAdDomainRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/managedidentities/apiv1/Client/DeleteDomain/main.go b/internal/generated/snippets/managedidentities/apiv1/Client/DeleteDomain/main.go index 583bf413a2ed..e559f4cdfebb 100644 --- a/internal/generated/snippets/managedidentities/apiv1/Client/DeleteDomain/main.go +++ b/internal/generated/snippets/managedidentities/apiv1/Client/DeleteDomain/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.DeleteDomainRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/managedidentities/apiv1/Client/DetachTrust/main.go b/internal/generated/snippets/managedidentities/apiv1/Client/DetachTrust/main.go index 0b16698f15b6..e5353f8b9c19 100644 --- a/internal/generated/snippets/managedidentities/apiv1/Client/DetachTrust/main.go +++ b/internal/generated/snippets/managedidentities/apiv1/Client/DetachTrust/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.DetachTrustRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/managedidentities/apiv1/Client/GetDomain/main.go b/internal/generated/snippets/managedidentities/apiv1/Client/GetDomain/main.go index 8a4c1193e4dc..aeacedca9201 100644 --- a/internal/generated/snippets/managedidentities/apiv1/Client/GetDomain/main.go +++ b/internal/generated/snippets/managedidentities/apiv1/Client/GetDomain/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.GetDomainRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/managedidentities/apiv1/Client/ListDomains/main.go b/internal/generated/snippets/managedidentities/apiv1/Client/ListDomains/main.go index eff63b84a85c..d986fff07e5d 100644 --- a/internal/generated/snippets/managedidentities/apiv1/Client/ListDomains/main.go +++ b/internal/generated/snippets/managedidentities/apiv1/Client/ListDomains/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.ListDomainsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/managedidentities/apiv1/Client/ReconfigureTrust/main.go b/internal/generated/snippets/managedidentities/apiv1/Client/ReconfigureTrust/main.go index 856db305dc4c..d64f8cc5b905 100644 --- a/internal/generated/snippets/managedidentities/apiv1/Client/ReconfigureTrust/main.go +++ b/internal/generated/snippets/managedidentities/apiv1/Client/ReconfigureTrust/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.ReconfigureTrustRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/managedidentities/apiv1/Client/ResetAdminPassword/main.go b/internal/generated/snippets/managedidentities/apiv1/Client/ResetAdminPassword/main.go index 4ff9d3c297b4..17f50fa25bf7 100644 --- a/internal/generated/snippets/managedidentities/apiv1/Client/ResetAdminPassword/main.go +++ b/internal/generated/snippets/managedidentities/apiv1/Client/ResetAdminPassword/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.ResetAdminPasswordRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/managedidentities/apiv1/Client/UpdateDomain/main.go b/internal/generated/snippets/managedidentities/apiv1/Client/UpdateDomain/main.go index 5920b41ac4c1..2e854f012582 100644 --- a/internal/generated/snippets/managedidentities/apiv1/Client/UpdateDomain/main.go +++ b/internal/generated/snippets/managedidentities/apiv1/Client/UpdateDomain/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.UpdateDomainRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/managedidentities/apiv1/Client/ValidateTrust/main.go b/internal/generated/snippets/managedidentities/apiv1/Client/ValidateTrust/main.go index 0d14eb8b0531..48fddaeb3f10 100644 --- a/internal/generated/snippets/managedidentities/apiv1/Client/ValidateTrust/main.go +++ b/internal/generated/snippets/managedidentities/apiv1/Client/ValidateTrust/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.ValidateTrustRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/mediatranslation/apiv1beta1/SpeechTranslationClient/StreamingTranslateSpeech/main.go b/internal/generated/snippets/mediatranslation/apiv1beta1/SpeechTranslationClient/StreamingTranslateSpeech/main.go index 7ea7392ebb40..25d295126ee9 100644 --- a/internal/generated/snippets/mediatranslation/apiv1beta1/SpeechTranslationClient/StreamingTranslateSpeech/main.go +++ b/internal/generated/snippets/mediatranslation/apiv1beta1/SpeechTranslationClient/StreamingTranslateSpeech/main.go @@ -25,13 +25,12 @@ import ( ) func main() { - // import mediatranslationpb "google.golang.org/genproto/googleapis/cloud/mediatranslation/v1beta1" - ctx := context.Background() c, err := mediatranslation.NewSpeechTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.StreamingTranslateSpeech(ctx) if err != nil { // TODO: Handle error. diff --git a/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/ApplyParameters/main.go b/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/ApplyParameters/main.go index bf80554c5c56..ff59190e940c 100644 --- a/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/ApplyParameters/main.go +++ b/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/ApplyParameters/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.ApplyParametersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/CreateInstance/main.go b/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/CreateInstance/main.go index 0aa5c3e07d60..d8e2f7b7db44 100644 --- a/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/CreateInstance/main.go +++ b/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/CreateInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.CreateInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/DeleteInstance/main.go b/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/DeleteInstance/main.go index 9786a68ff5d3..2492ef3b1700 100644 --- a/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/DeleteInstance/main.go +++ b/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/DeleteInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.DeleteInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/GetInstance/main.go b/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/GetInstance/main.go index 5b1e0191fa9e..1731532a5f6c 100644 --- a/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/GetInstance/main.go +++ b/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/GetInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.GetInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/ListInstances/main.go b/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/ListInstances/main.go index 3fe93a20bad6..cee7b0ce5070 100644 --- a/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/ListInstances/main.go +++ b/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/ListInstances/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.ListInstancesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/UpdateInstance/main.go b/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/UpdateInstance/main.go index a6211ec116ee..34f96c0964dc 100644 --- a/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/UpdateInstance/main.go +++ b/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/UpdateInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.UpdateInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/UpdateParameters/main.go b/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/UpdateParameters/main.go index 2a4b71242c50..206143f2d5a4 100644 --- a/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/UpdateParameters/main.go +++ b/internal/generated/snippets/memcache/apiv1/CloudMemcacheClient/UpdateParameters/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.UpdateParametersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/ApplyParameters/main.go b/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/ApplyParameters/main.go index 3b34f2aafac3..46a09da990b2 100644 --- a/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/ApplyParameters/main.go +++ b/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/ApplyParameters/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1beta2" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.ApplyParametersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/ApplySoftwareUpdate/main.go b/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/ApplySoftwareUpdate/main.go index 17235309968a..166b87ac04e8 100644 --- a/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/ApplySoftwareUpdate/main.go +++ b/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/ApplySoftwareUpdate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1beta2" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.ApplySoftwareUpdateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/CreateInstance/main.go b/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/CreateInstance/main.go index 0d5afd80fb51..0554f4b55904 100644 --- a/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/CreateInstance/main.go +++ b/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/CreateInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1beta2" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.CreateInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/DeleteInstance/main.go b/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/DeleteInstance/main.go index 1cb3d3c77b25..3e0571b7cc49 100644 --- a/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/DeleteInstance/main.go +++ b/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/DeleteInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1beta2" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.DeleteInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/GetInstance/main.go b/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/GetInstance/main.go index 3035712efcdb..3bb67afe1aa4 100644 --- a/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/GetInstance/main.go +++ b/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/GetInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1beta2" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.GetInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/ListInstances/main.go b/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/ListInstances/main.go index ee03d7783086..92448db90488 100644 --- a/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/ListInstances/main.go +++ b/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/ListInstances/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.ListInstancesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/UpdateInstance/main.go b/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/UpdateInstance/main.go index 6e1b7852bd6b..fff0394cca34 100644 --- a/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/UpdateInstance/main.go +++ b/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/UpdateInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1beta2" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.UpdateInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/UpdateParameters/main.go b/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/UpdateParameters/main.go index b3ce1665df4f..6b4b1e29822b 100644 --- a/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/UpdateParameters/main.go +++ b/internal/generated/snippets/memcache/apiv1beta2/CloudMemcacheClient/UpdateParameters/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1beta2" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.UpdateParametersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/CreateMetadataImport/main.go b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/CreateMetadataImport/main.go index 399c66aed51c..2251ef3fb36e 100644 --- a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/CreateMetadataImport/main.go +++ b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/CreateMetadataImport/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.CreateMetadataImportRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/CreateService/main.go b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/CreateService/main.go index 3cdc193c8d78..9bcb55766286 100644 --- a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/CreateService/main.go +++ b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/CreateService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.CreateServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/DeleteService/main.go b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/DeleteService/main.go index e946de98c468..5b3cbff6297d 100644 --- a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/DeleteService/main.go +++ b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/DeleteService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.DeleteServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/ExportMetadata/main.go b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/ExportMetadata/main.go index 25af2576b60b..11a024c3234c 100644 --- a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/ExportMetadata/main.go +++ b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/ExportMetadata/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ExportMetadataRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/GetMetadataImport/main.go b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/GetMetadataImport/main.go index 748911c2cf84..d67832e90010 100644 --- a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/GetMetadataImport/main.go +++ b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/GetMetadataImport/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.GetMetadataImportRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/GetService/main.go b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/GetService/main.go index 1a489c6ec7d5..59fe706fa2a4 100644 --- a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/GetService/main.go +++ b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/GetService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.GetServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/ListMetadataImports/main.go b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/ListMetadataImports/main.go index 81c5f8f59fdb..ec742e2f9585 100644 --- a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/ListMetadataImports/main.go +++ b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/ListMetadataImports/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ListMetadataImportsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/ListServices/main.go b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/ListServices/main.go index cd52a91d013f..e9807b3b4ea5 100644 --- a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/ListServices/main.go +++ b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/ListServices/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ListServicesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/UpdateMetadataImport/main.go b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/UpdateMetadataImport/main.go index b09a1b0bbac5..eadc59754bda 100644 --- a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/UpdateMetadataImport/main.go +++ b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/UpdateMetadataImport/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.UpdateMetadataImportRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/UpdateService/main.go b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/UpdateService/main.go index 3fcbc3c77cd5..72df7f60862a 100644 --- a/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/UpdateService/main.go +++ b/internal/generated/snippets/metastore/apiv1/DataprocMetastoreClient/UpdateService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.UpdateServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/CreateBackup/main.go b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/CreateBackup/main.go index c7c46085b0e9..a02df602daf0 100644 --- a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/CreateBackup/main.go +++ b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/CreateBackup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.CreateBackupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/CreateMetadataImport/main.go b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/CreateMetadataImport/main.go index 4ae0d23bf1c6..ed57dbb505f9 100644 --- a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/CreateMetadataImport/main.go +++ b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/CreateMetadataImport/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.CreateMetadataImportRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/CreateService/main.go b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/CreateService/main.go index 38c305951840..b66cc9af2a21 100644 --- a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/CreateService/main.go +++ b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/CreateService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.CreateServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/DeleteBackup/main.go b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/DeleteBackup/main.go index 41e2c528f0be..ca431db0678e 100644 --- a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/DeleteBackup/main.go +++ b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/DeleteBackup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.DeleteBackupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/DeleteService/main.go b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/DeleteService/main.go index 74f6e9f5efd9..a5bc3ee373a6 100644 --- a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/DeleteService/main.go +++ b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/DeleteService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.DeleteServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/ExportMetadata/main.go b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/ExportMetadata/main.go index 69f5e3ce5b2f..2a6999fc460b 100644 --- a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/ExportMetadata/main.go +++ b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/ExportMetadata/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ExportMetadataRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/GetBackup/main.go b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/GetBackup/main.go index c8af4eaa49f6..06fd1a2bf152 100644 --- a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/GetBackup/main.go +++ b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/GetBackup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.GetBackupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/GetMetadataImport/main.go b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/GetMetadataImport/main.go index 81d8da6b00a3..7b4902b5c798 100644 --- a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/GetMetadataImport/main.go +++ b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/GetMetadataImport/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.GetMetadataImportRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/GetService/main.go b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/GetService/main.go index 423cb293f309..df94875fbca4 100644 --- a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/GetService/main.go +++ b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/GetService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.GetServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/ListBackups/main.go b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/ListBackups/main.go index 7afe49b4e6e3..d99c670f038f 100644 --- a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/ListBackups/main.go +++ b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/ListBackups/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ListBackupsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/ListMetadataImports/main.go b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/ListMetadataImports/main.go index 378418d65a90..2a84db25cb42 100644 --- a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/ListMetadataImports/main.go +++ b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/ListMetadataImports/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ListMetadataImportsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/ListServices/main.go b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/ListServices/main.go index a655d3b3ed45..1dd306283a84 100644 --- a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/ListServices/main.go +++ b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/ListServices/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ListServicesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/RestoreService/main.go b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/RestoreService/main.go index a9f6f12ba8c4..389545b48c60 100644 --- a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/RestoreService/main.go +++ b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/RestoreService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.RestoreServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/UpdateMetadataImport/main.go b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/UpdateMetadataImport/main.go index e351a37f1c7f..33658fce558c 100644 --- a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/UpdateMetadataImport/main.go +++ b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/UpdateMetadataImport/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.UpdateMetadataImportRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/UpdateService/main.go b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/UpdateService/main.go index 04d6b417f44a..c467f91613a3 100644 --- a/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/UpdateService/main.go +++ b/internal/generated/snippets/metastore/apiv1alpha/DataprocMetastoreClient/UpdateService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.UpdateServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/CreateBackup/main.go b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/CreateBackup/main.go index 13b06a29c5a9..cac8fa0acd0f 100644 --- a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/CreateBackup/main.go +++ b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/CreateBackup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.CreateBackupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/CreateMetadataImport/main.go b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/CreateMetadataImport/main.go index 713ebb3d943f..c50787a0b603 100644 --- a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/CreateMetadataImport/main.go +++ b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/CreateMetadataImport/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.CreateMetadataImportRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/CreateService/main.go b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/CreateService/main.go index 54016e7eaa31..a7b85245a72d 100644 --- a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/CreateService/main.go +++ b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/CreateService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.CreateServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/DeleteBackup/main.go b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/DeleteBackup/main.go index 5d4448c51394..4758805d8845 100644 --- a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/DeleteBackup/main.go +++ b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/DeleteBackup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.DeleteBackupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/DeleteService/main.go b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/DeleteService/main.go index 58ea8836bc88..39d64f754b20 100644 --- a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/DeleteService/main.go +++ b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/DeleteService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.DeleteServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/ExportMetadata/main.go b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/ExportMetadata/main.go index b5e85d1bc6d7..a0e85b4fd551 100644 --- a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/ExportMetadata/main.go +++ b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/ExportMetadata/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ExportMetadataRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/GetBackup/main.go b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/GetBackup/main.go index 94939c9a78ef..e3e4f336cc4e 100644 --- a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/GetBackup/main.go +++ b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/GetBackup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.GetBackupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/GetMetadataImport/main.go b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/GetMetadataImport/main.go index 93ef6b542e16..d4483ace4fce 100644 --- a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/GetMetadataImport/main.go +++ b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/GetMetadataImport/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.GetMetadataImportRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/GetService/main.go b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/GetService/main.go index 28166ad15da8..15aee5a3bd36 100644 --- a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/GetService/main.go +++ b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/GetService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.GetServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/ListBackups/main.go b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/ListBackups/main.go index c4d52e0c0128..be0dbc432a5b 100644 --- a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/ListBackups/main.go +++ b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/ListBackups/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ListBackupsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/ListMetadataImports/main.go b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/ListMetadataImports/main.go index eef879eaabc6..0979048bd687 100644 --- a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/ListMetadataImports/main.go +++ b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/ListMetadataImports/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ListMetadataImportsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/ListServices/main.go b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/ListServices/main.go index 9b049d5ff139..2a5db69b4a10 100644 --- a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/ListServices/main.go +++ b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/ListServices/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ListServicesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/RestoreService/main.go b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/RestoreService/main.go index 8c4195c668cb..3efa18d11f38 100644 --- a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/RestoreService/main.go +++ b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/RestoreService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.RestoreServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/UpdateMetadataImport/main.go b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/UpdateMetadataImport/main.go index 3836753deeab..a5affc828077 100644 --- a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/UpdateMetadataImport/main.go +++ b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/UpdateMetadataImport/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.UpdateMetadataImportRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/UpdateService/main.go b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/UpdateService/main.go index 71807a64b8d3..1d8c9367df46 100644 --- a/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/UpdateService/main.go +++ b/internal/generated/snippets/metastore/apiv1beta/DataprocMetastoreClient/UpdateService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.UpdateServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/CreateAlertPolicy/main.go b/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/CreateAlertPolicy/main.go index f251af1f15f2..f9a7a1e011d0 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/CreateAlertPolicy/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/CreateAlertPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewAlertPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.CreateAlertPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/DeleteAlertPolicy/main.go b/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/DeleteAlertPolicy/main.go index 8e79474b0698..92e8e26ea778 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/DeleteAlertPolicy/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/DeleteAlertPolicy/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.DeleteAlertPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/GetAlertPolicy/main.go b/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/GetAlertPolicy/main.go index 4e21d324af12..5b29ccb28ea0 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/GetAlertPolicy/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/GetAlertPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewAlertPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetAlertPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/ListAlertPolicies/main.go b/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/ListAlertPolicies/main.go index 8c41df47df69..76d2cb9c4d52 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/ListAlertPolicies/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/ListAlertPolicies/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewAlertPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListAlertPoliciesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/UpdateAlertPolicy/main.go b/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/UpdateAlertPolicy/main.go index 222a95715a03..d49529c94afb 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/UpdateAlertPolicy/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/AlertPolicyClient/UpdateAlertPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewAlertPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.UpdateAlertPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/CreateGroup/main.go b/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/CreateGroup/main.go index 0e2d7e17391a..f58997ac6297 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/CreateGroup/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/CreateGroup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewGroupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.CreateGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/DeleteGroup/main.go b/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/DeleteGroup/main.go index cbf0781e9224..6cdd4ffce603 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/DeleteGroup/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/DeleteGroup/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.DeleteGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/GetGroup/main.go b/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/GetGroup/main.go index e70e83739395..f88ee1402e07 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/GetGroup/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/GetGroup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewGroupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/ListGroupMembers/main.go b/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/ListGroupMembers/main.go index bda1dc9fea3f..59ae4e63124b 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/ListGroupMembers/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/ListGroupMembers/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewGroupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListGroupMembersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/ListGroups/main.go b/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/ListGroups/main.go index d1bde0336906..1589aa3a6225 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/ListGroups/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/ListGroups/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewGroupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListGroupsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/UpdateGroup/main.go b/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/UpdateGroup/main.go index cd5daa448ac0..d7b175f4c383 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/UpdateGroup/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/GroupClient/UpdateGroup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewGroupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.UpdateGroupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/CreateMetricDescriptor/main.go b/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/CreateMetricDescriptor/main.go index 2d9acf0a079a..748ec353182b 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/CreateMetricDescriptor/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/CreateMetricDescriptor/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewMetricClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.CreateMetricDescriptorRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/CreateTimeSeries/main.go b/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/CreateTimeSeries/main.go index 5887bbb0fe3f..bfe90a27640f 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/CreateTimeSeries/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/CreateTimeSeries/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.CreateTimeSeriesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/DeleteMetricDescriptor/main.go b/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/DeleteMetricDescriptor/main.go index fec289ac41d1..26824bd4e1a3 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/DeleteMetricDescriptor/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/DeleteMetricDescriptor/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.DeleteMetricDescriptorRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/GetMetricDescriptor/main.go b/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/GetMetricDescriptor/main.go index 5d29dcd3a968..ddec29273214 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/GetMetricDescriptor/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/GetMetricDescriptor/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewMetricClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetMetricDescriptorRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/GetMonitoredResourceDescriptor/main.go b/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/GetMonitoredResourceDescriptor/main.go index cd1cd5b8be16..52d0ec814712 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/GetMonitoredResourceDescriptor/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/GetMonitoredResourceDescriptor/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewMetricClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetMonitoredResourceDescriptorRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/ListMetricDescriptors/main.go b/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/ListMetricDescriptors/main.go index fb6f87ac4719..1041c0cf9430 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/ListMetricDescriptors/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/ListMetricDescriptors/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewMetricClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListMetricDescriptorsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/ListMonitoredResourceDescriptors/main.go b/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/ListMonitoredResourceDescriptors/main.go index e9b4b1da3897..48437a87d869 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/ListMonitoredResourceDescriptors/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/ListMonitoredResourceDescriptors/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewMetricClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListMonitoredResourceDescriptorsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/ListTimeSeries/main.go b/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/ListTimeSeries/main.go index 9a31957d34b2..9d65d71a3b15 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/ListTimeSeries/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/MetricClient/ListTimeSeries/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewMetricClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListTimeSeriesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/CreateNotificationChannel/main.go b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/CreateNotificationChannel/main.go index 0507b35e1a0f..bfed9c79899f 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/CreateNotificationChannel/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/CreateNotificationChannel/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewNotificationChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.CreateNotificationChannelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/DeleteNotificationChannel/main.go b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/DeleteNotificationChannel/main.go index b9e275349169..50d08af5f13b 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/DeleteNotificationChannel/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/DeleteNotificationChannel/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.DeleteNotificationChannelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/GetNotificationChannel/main.go b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/GetNotificationChannel/main.go index 3997d2969dd3..09105bae80fd 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/GetNotificationChannel/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/GetNotificationChannel/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewNotificationChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetNotificationChannelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/GetNotificationChannelDescriptor/main.go b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/GetNotificationChannelDescriptor/main.go index 605a070f4865..daadc06340c6 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/GetNotificationChannelDescriptor/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/GetNotificationChannelDescriptor/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewNotificationChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetNotificationChannelDescriptorRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/GetNotificationChannelVerificationCode/main.go b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/GetNotificationChannelVerificationCode/main.go index 57d519f3789e..f38bed5ce815 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/GetNotificationChannelVerificationCode/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/GetNotificationChannelVerificationCode/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewNotificationChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetNotificationChannelVerificationCodeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/ListNotificationChannelDescriptors/main.go b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/ListNotificationChannelDescriptors/main.go index acb973ebbfbc..a0e3665a1156 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/ListNotificationChannelDescriptors/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/ListNotificationChannelDescriptors/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewNotificationChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListNotificationChannelDescriptorsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/ListNotificationChannels/main.go b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/ListNotificationChannels/main.go index 6b25f22e31a0..66fa23981829 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/ListNotificationChannels/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/ListNotificationChannels/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewNotificationChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListNotificationChannelsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/SendNotificationChannelVerificationCode/main.go b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/SendNotificationChannelVerificationCode/main.go index e2381597978a..faf6b2986b86 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/SendNotificationChannelVerificationCode/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/SendNotificationChannelVerificationCode/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.SendNotificationChannelVerificationCodeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/UpdateNotificationChannel/main.go b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/UpdateNotificationChannel/main.go index 59658455db00..3e41ee214fd6 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/UpdateNotificationChannel/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/UpdateNotificationChannel/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewNotificationChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.UpdateNotificationChannelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/VerifyNotificationChannel/main.go b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/VerifyNotificationChannel/main.go index e6fb5c8c211c..e3541b8e6b58 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/VerifyNotificationChannel/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/NotificationChannelClient/VerifyNotificationChannel/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewNotificationChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.VerifyNotificationChannelRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/QueryClient/QueryTimeSeries/main.go b/internal/generated/snippets/monitoring/apiv3/v2/QueryClient/QueryTimeSeries/main.go index 240712a2abce..2187a912e55b 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/QueryClient/QueryTimeSeries/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/QueryClient/QueryTimeSeries/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewQueryClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.QueryTimeSeriesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/CreateService/main.go b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/CreateService/main.go index 34a8a63ae0d5..1f8bacdb45d2 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/CreateService/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/CreateService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewServiceMonitoringClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.CreateServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/CreateServiceLevelObjective/main.go b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/CreateServiceLevelObjective/main.go index 535a85984dea..33f054015f9e 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/CreateServiceLevelObjective/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/CreateServiceLevelObjective/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewServiceMonitoringClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.CreateServiceLevelObjectiveRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/DeleteService/main.go b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/DeleteService/main.go index 993f3e895ff9..ef597eabbbee 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/DeleteService/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/DeleteService/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.DeleteServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/DeleteServiceLevelObjective/main.go b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/DeleteServiceLevelObjective/main.go index ccf6cf56ca4c..6fc5e651e31f 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/DeleteServiceLevelObjective/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/DeleteServiceLevelObjective/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.DeleteServiceLevelObjectiveRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/GetService/main.go b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/GetService/main.go index 1d62a2f93644..ceef20d1070d 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/GetService/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/GetService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewServiceMonitoringClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/GetServiceLevelObjective/main.go b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/GetServiceLevelObjective/main.go index 8f460db5c72a..11ba963ecbf2 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/GetServiceLevelObjective/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/GetServiceLevelObjective/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewServiceMonitoringClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetServiceLevelObjectiveRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/ListServiceLevelObjectives/main.go b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/ListServiceLevelObjectives/main.go index 818b5c5a2d1e..7b4421193613 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/ListServiceLevelObjectives/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/ListServiceLevelObjectives/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewServiceMonitoringClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListServiceLevelObjectivesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/ListServices/main.go b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/ListServices/main.go index 648ead30a71c..6e4b46e49ca9 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/ListServices/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/ListServices/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewServiceMonitoringClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListServicesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/UpdateService/main.go b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/UpdateService/main.go index 7f91151c5f4a..0df61ac83f5c 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/UpdateService/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/UpdateService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewServiceMonitoringClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.UpdateServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/UpdateServiceLevelObjective/main.go b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/UpdateServiceLevelObjective/main.go index d4d5ecda0458..dfe5ce1d85a0 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/UpdateServiceLevelObjective/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/ServiceMonitoringClient/UpdateServiceLevelObjective/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewServiceMonitoringClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.UpdateServiceLevelObjectiveRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/CreateUptimeCheckConfig/main.go b/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/CreateUptimeCheckConfig/main.go index 01761d95a353..34f759bc50a6 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/CreateUptimeCheckConfig/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/CreateUptimeCheckConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewUptimeCheckClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.CreateUptimeCheckConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/DeleteUptimeCheckConfig/main.go b/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/DeleteUptimeCheckConfig/main.go index bd605e5fa148..e2e2596e5abd 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/DeleteUptimeCheckConfig/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/DeleteUptimeCheckConfig/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.DeleteUptimeCheckConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/GetUptimeCheckConfig/main.go b/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/GetUptimeCheckConfig/main.go index 6d231383fbd3..be956f37292e 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/GetUptimeCheckConfig/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/GetUptimeCheckConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewUptimeCheckClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetUptimeCheckConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/ListUptimeCheckConfigs/main.go b/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/ListUptimeCheckConfigs/main.go index ebf69a893e19..4940a780736e 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/ListUptimeCheckConfigs/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/ListUptimeCheckConfigs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewUptimeCheckClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListUptimeCheckConfigsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/ListUptimeCheckIps/main.go b/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/ListUptimeCheckIps/main.go index 9bdd888a185d..17a109884731 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/ListUptimeCheckIps/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/ListUptimeCheckIps/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewUptimeCheckClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListUptimeCheckIpsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/UpdateUptimeCheckConfig/main.go b/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/UpdateUptimeCheckConfig/main.go index 80fd7e5b90da..f5f21da3835d 100644 --- a/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/UpdateUptimeCheckConfig/main.go +++ b/internal/generated/snippets/monitoring/apiv3/v2/UptimeCheckClient/UpdateUptimeCheckConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewUptimeCheckClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.UpdateUptimeCheckConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/CreateDashboard/main.go b/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/CreateDashboard/main.go index 8d14b491d3dc..96d229f9b2ff 100644 --- a/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/CreateDashboard/main.go +++ b/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/CreateDashboard/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dashboardpb "google.golang.org/genproto/googleapis/monitoring/dashboard/v1" - ctx := context.Background() c, err := dashboard.NewDashboardsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dashboardpb.CreateDashboardRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/DeleteDashboard/main.go b/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/DeleteDashboard/main.go index e8cd8e6bce01..69800c638985 100644 --- a/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/DeleteDashboard/main.go +++ b/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/DeleteDashboard/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dashboardpb.DeleteDashboardRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/GetDashboard/main.go b/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/GetDashboard/main.go index d1322310c7c6..8223167e9b4a 100644 --- a/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/GetDashboard/main.go +++ b/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/GetDashboard/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dashboardpb "google.golang.org/genproto/googleapis/monitoring/dashboard/v1" - ctx := context.Background() c, err := dashboard.NewDashboardsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dashboardpb.GetDashboardRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/ListDashboards/main.go b/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/ListDashboards/main.go index e7a6cbf24fef..41f8344320b7 100644 --- a/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/ListDashboards/main.go +++ b/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/ListDashboards/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import dashboardpb "google.golang.org/genproto/googleapis/monitoring/dashboard/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dashboard.NewDashboardsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dashboardpb.ListDashboardsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/UpdateDashboard/main.go b/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/UpdateDashboard/main.go index 601ea48d91d3..f7aefed4293d 100644 --- a/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/UpdateDashboard/main.go +++ b/internal/generated/snippets/monitoring/dashboard/apiv1/DashboardsClient/UpdateDashboard/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import dashboardpb "google.golang.org/genproto/googleapis/monitoring/dashboard/v1" - ctx := context.Background() c, err := dashboard.NewDashboardsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dashboardpb.UpdateDashboardRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/CreateHub/main.go b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/CreateHub/main.go index 4656b2cdbb87..063d6340e90e 100644 --- a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/CreateHub/main.go +++ b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/CreateHub/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.CreateHubRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/CreateSpoke/main.go b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/CreateSpoke/main.go index 0929ec41b345..ec6aa645d020 100644 --- a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/CreateSpoke/main.go +++ b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/CreateSpoke/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.CreateSpokeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/DeleteHub/main.go b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/DeleteHub/main.go index 7cd11abd6f14..e8b236d9e7c2 100644 --- a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/DeleteHub/main.go +++ b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/DeleteHub/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.DeleteHubRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/DeleteSpoke/main.go b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/DeleteSpoke/main.go index c66bf0f5ccb7..35ddf71cda61 100644 --- a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/DeleteSpoke/main.go +++ b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/DeleteSpoke/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.DeleteSpokeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/GetHub/main.go b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/GetHub/main.go index fc9824ea1655..0a653734fa1f 100644 --- a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/GetHub/main.go +++ b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/GetHub/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.GetHubRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/GetSpoke/main.go b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/GetSpoke/main.go index e64cba50cf97..a6504c137b52 100644 --- a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/GetSpoke/main.go +++ b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/GetSpoke/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.GetSpokeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/ListHubs/main.go b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/ListHubs/main.go index b87cadcca8b4..2d96cd0964c8 100644 --- a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/ListHubs/main.go +++ b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/ListHubs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.ListHubsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/ListSpokes/main.go b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/ListSpokes/main.go index 43e4bb345307..a2cc27caf7f2 100644 --- a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/ListSpokes/main.go +++ b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/ListSpokes/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.ListSpokesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/UpdateHub/main.go b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/UpdateHub/main.go index 8b06b4f091e4..96966c378ba0 100644 --- a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/UpdateHub/main.go +++ b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/UpdateHub/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.UpdateHubRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/UpdateSpoke/main.go b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/UpdateSpoke/main.go index 0c3fdbfa1265..7ad29b604717 100644 --- a/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/UpdateSpoke/main.go +++ b/internal/generated/snippets/networkconnectivity/apiv1alpha1/HubClient/UpdateSpoke/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.UpdateSpokeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/CreateEnvironment/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/CreateEnvironment/main.go index 084e538d68a5..2da5cf5f4d79 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/CreateEnvironment/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/CreateEnvironment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.CreateEnvironmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/CreateInstance/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/CreateInstance/main.go index ec535f6c3ca0..124baffbfdb2 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/CreateInstance/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/CreateInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.CreateInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/DeleteEnvironment/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/DeleteEnvironment/main.go index faa87ae40efb..cc220ce8af82 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/DeleteEnvironment/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/DeleteEnvironment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.DeleteEnvironmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/DeleteInstance/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/DeleteInstance/main.go index 66e4955b1db0..7534f07a4841 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/DeleteInstance/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/DeleteInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.DeleteInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/GetEnvironment/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/GetEnvironment/main.go index 3cd0a5d90c17..71a80025102c 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/GetEnvironment/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/GetEnvironment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.GetEnvironmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/GetInstance/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/GetInstance/main.go index cb81d9abaa9e..e572d2df8ee7 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/GetInstance/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/GetInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.GetInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/IsInstanceUpgradeable/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/IsInstanceUpgradeable/main.go index 97c68f8de20c..f1d3efc2eae4 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/IsInstanceUpgradeable/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/IsInstanceUpgradeable/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.IsInstanceUpgradeableRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/ListEnvironments/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/ListEnvironments/main.go index 6674a0cf843b..758c80e3971e 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/ListEnvironments/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/ListEnvironments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.ListEnvironmentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/ListInstances/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/ListInstances/main.go index 84e0978ef4c0..80cee3ebd826 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/ListInstances/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/ListInstances/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.ListInstancesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/RegisterInstance/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/RegisterInstance/main.go index 837aef31b3f5..41d3488f6381 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/RegisterInstance/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/RegisterInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.RegisterInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/ReportInstanceInfo/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/ReportInstanceInfo/main.go index 87494e344804..d68bee21a749 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/ReportInstanceInfo/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/ReportInstanceInfo/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.ReportInstanceInfoRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/ResetInstance/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/ResetInstance/main.go index 740c178117b4..e09c7fccf43f 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/ResetInstance/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/ResetInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.ResetInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/SetInstanceAccelerator/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/SetInstanceAccelerator/main.go index ab91e889148e..82f702f61dae 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/SetInstanceAccelerator/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/SetInstanceAccelerator/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.SetInstanceAcceleratorRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/SetInstanceLabels/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/SetInstanceLabels/main.go index 35f84c28ab8a..4f5cad97c979 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/SetInstanceLabels/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/SetInstanceLabels/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.SetInstanceLabelsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/SetInstanceMachineType/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/SetInstanceMachineType/main.go index 78f9104130ec..e6a3ae4adbcd 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/SetInstanceMachineType/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/SetInstanceMachineType/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.SetInstanceMachineTypeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/StartInstance/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/StartInstance/main.go index 8ed3026a417b..d8bd20eaf5cd 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/StartInstance/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/StartInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.StartInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/StopInstance/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/StopInstance/main.go index 859376ead210..d5ec711ff720 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/StopInstance/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/StopInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.StopInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/UpgradeInstance/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/UpgradeInstance/main.go index 0a3d8500f54a..85c8df98dbd4 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/UpgradeInstance/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/UpgradeInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.UpgradeInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/UpgradeInstanceInternal/main.go b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/UpgradeInstanceInternal/main.go index 6f1539fbaced..d25859515d2d 100644 --- a/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/UpgradeInstanceInternal/main.go +++ b/internal/generated/snippets/notebooks/apiv1beta1/NotebookClient/UpgradeInstanceInternal/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.UpgradeInstanceInternalRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/orgpolicy/apiv2/Client/CreatePolicy/main.go b/internal/generated/snippets/orgpolicy/apiv2/Client/CreatePolicy/main.go index b0886f023646..8a7d747e2273 100644 --- a/internal/generated/snippets/orgpolicy/apiv2/Client/CreatePolicy/main.go +++ b/internal/generated/snippets/orgpolicy/apiv2/Client/CreatePolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import orgpolicypb "google.golang.org/genproto/googleapis/cloud/orgpolicy/v2" - ctx := context.Background() c, err := orgpolicy.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &orgpolicypb.CreatePolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/orgpolicy/apiv2/Client/DeletePolicy/main.go b/internal/generated/snippets/orgpolicy/apiv2/Client/DeletePolicy/main.go index 352334f88634..7cd1511b66e9 100644 --- a/internal/generated/snippets/orgpolicy/apiv2/Client/DeletePolicy/main.go +++ b/internal/generated/snippets/orgpolicy/apiv2/Client/DeletePolicy/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &orgpolicypb.DeletePolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/orgpolicy/apiv2/Client/GetEffectivePolicy/main.go b/internal/generated/snippets/orgpolicy/apiv2/Client/GetEffectivePolicy/main.go index 62384b9d338a..2c1ff45631e2 100644 --- a/internal/generated/snippets/orgpolicy/apiv2/Client/GetEffectivePolicy/main.go +++ b/internal/generated/snippets/orgpolicy/apiv2/Client/GetEffectivePolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import orgpolicypb "google.golang.org/genproto/googleapis/cloud/orgpolicy/v2" - ctx := context.Background() c, err := orgpolicy.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &orgpolicypb.GetEffectivePolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/orgpolicy/apiv2/Client/GetPolicy/main.go b/internal/generated/snippets/orgpolicy/apiv2/Client/GetPolicy/main.go index 0aa70408c889..c32e7fae2fc1 100644 --- a/internal/generated/snippets/orgpolicy/apiv2/Client/GetPolicy/main.go +++ b/internal/generated/snippets/orgpolicy/apiv2/Client/GetPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import orgpolicypb "google.golang.org/genproto/googleapis/cloud/orgpolicy/v2" - ctx := context.Background() c, err := orgpolicy.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &orgpolicypb.GetPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/orgpolicy/apiv2/Client/ListConstraints/main.go b/internal/generated/snippets/orgpolicy/apiv2/Client/ListConstraints/main.go index dcc95389fe4d..7047dd002aca 100644 --- a/internal/generated/snippets/orgpolicy/apiv2/Client/ListConstraints/main.go +++ b/internal/generated/snippets/orgpolicy/apiv2/Client/ListConstraints/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import orgpolicypb "google.golang.org/genproto/googleapis/cloud/orgpolicy/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := orgpolicy.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &orgpolicypb.ListConstraintsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/orgpolicy/apiv2/Client/ListPolicies/main.go b/internal/generated/snippets/orgpolicy/apiv2/Client/ListPolicies/main.go index b6bee49c0cf2..a1a6c2f16f58 100644 --- a/internal/generated/snippets/orgpolicy/apiv2/Client/ListPolicies/main.go +++ b/internal/generated/snippets/orgpolicy/apiv2/Client/ListPolicies/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import orgpolicypb "google.golang.org/genproto/googleapis/cloud/orgpolicy/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := orgpolicy.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &orgpolicypb.ListPoliciesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/orgpolicy/apiv2/Client/UpdatePolicy/main.go b/internal/generated/snippets/orgpolicy/apiv2/Client/UpdatePolicy/main.go index 8c2536bcf0f8..c27e9f0eac81 100644 --- a/internal/generated/snippets/orgpolicy/apiv2/Client/UpdatePolicy/main.go +++ b/internal/generated/snippets/orgpolicy/apiv2/Client/UpdatePolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import orgpolicypb "google.golang.org/genproto/googleapis/cloud/orgpolicy/v2" - ctx := context.Background() c, err := orgpolicy.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &orgpolicypb.UpdatePolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/RegisterAgent/main.go b/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/RegisterAgent/main.go index c377802ad345..deb5459deee0 100644 --- a/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/RegisterAgent/main.go +++ b/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/RegisterAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.RegisterAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/ReportInventory/main.go b/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/ReportInventory/main.go index 0b498e07f2e5..e8a0173a1999 100644 --- a/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/ReportInventory/main.go +++ b/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/ReportInventory/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.ReportInventoryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/ReportTaskComplete/main.go b/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/ReportTaskComplete/main.go index fdb0de8ae018..c6289e9e336d 100644 --- a/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/ReportTaskComplete/main.go +++ b/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/ReportTaskComplete/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.ReportTaskCompleteRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/ReportTaskProgress/main.go b/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/ReportTaskProgress/main.go index ce8e5e90fa4d..01b68138b292 100644 --- a/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/ReportTaskProgress/main.go +++ b/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/ReportTaskProgress/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.ReportTaskProgressRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/StartNextTask/main.go b/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/StartNextTask/main.go index d58bfbea0e43..aed0c0e08270 100644 --- a/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/StartNextTask/main.go +++ b/internal/generated/snippets/osconfig/agentendpoint/apiv1/Client/StartNextTask/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.StartNextTaskRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/LookupEffectiveGuestPolicy/main.go b/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/LookupEffectiveGuestPolicy/main.go index 114502b7b552..24a74fde6eed 100644 --- a/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/LookupEffectiveGuestPolicy/main.go +++ b/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/LookupEffectiveGuestPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1beta" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.LookupEffectiveGuestPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/RegisterAgent/main.go b/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/RegisterAgent/main.go index 29c8e47ee8ca..d9d0b3fdfe1b 100644 --- a/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/RegisterAgent/main.go +++ b/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/RegisterAgent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1beta" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.RegisterAgentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/ReportTaskComplete/main.go b/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/ReportTaskComplete/main.go index d140e8a4b351..f7fe3fd68c3f 100644 --- a/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/ReportTaskComplete/main.go +++ b/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/ReportTaskComplete/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1beta" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.ReportTaskCompleteRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/ReportTaskProgress/main.go b/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/ReportTaskProgress/main.go index 1c2f07ad9b8c..8d20813db74c 100644 --- a/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/ReportTaskProgress/main.go +++ b/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/ReportTaskProgress/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1beta" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.ReportTaskProgressRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/StartNextTask/main.go b/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/StartNextTask/main.go index 262dfb9f5227..b0f478ff7104 100644 --- a/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/StartNextTask/main.go +++ b/internal/generated/snippets/osconfig/agentendpoint/apiv1beta/Client/StartNextTask/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1beta" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.StartNextTaskRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1/Client/CancelPatchJob/main.go b/internal/generated/snippets/osconfig/apiv1/Client/CancelPatchJob/main.go index 46adbcb5ca23..dadc7378ab58 100644 --- a/internal/generated/snippets/osconfig/apiv1/Client/CancelPatchJob/main.go +++ b/internal/generated/snippets/osconfig/apiv1/Client/CancelPatchJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.CancelPatchJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1/Client/CreatePatchDeployment/main.go b/internal/generated/snippets/osconfig/apiv1/Client/CreatePatchDeployment/main.go index 3f31112ac73e..60f8d209699c 100644 --- a/internal/generated/snippets/osconfig/apiv1/Client/CreatePatchDeployment/main.go +++ b/internal/generated/snippets/osconfig/apiv1/Client/CreatePatchDeployment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.CreatePatchDeploymentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1/Client/DeletePatchDeployment/main.go b/internal/generated/snippets/osconfig/apiv1/Client/DeletePatchDeployment/main.go index 0f85ee57d1b7..e26570fa955c 100644 --- a/internal/generated/snippets/osconfig/apiv1/Client/DeletePatchDeployment/main.go +++ b/internal/generated/snippets/osconfig/apiv1/Client/DeletePatchDeployment/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.DeletePatchDeploymentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1/Client/ExecutePatchJob/main.go b/internal/generated/snippets/osconfig/apiv1/Client/ExecutePatchJob/main.go index 5f5a645e6d16..87d7b60bac05 100644 --- a/internal/generated/snippets/osconfig/apiv1/Client/ExecutePatchJob/main.go +++ b/internal/generated/snippets/osconfig/apiv1/Client/ExecutePatchJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ExecutePatchJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1/Client/GetPatchDeployment/main.go b/internal/generated/snippets/osconfig/apiv1/Client/GetPatchDeployment/main.go index 8c8cdc680171..142279d07a56 100644 --- a/internal/generated/snippets/osconfig/apiv1/Client/GetPatchDeployment/main.go +++ b/internal/generated/snippets/osconfig/apiv1/Client/GetPatchDeployment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.GetPatchDeploymentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1/Client/GetPatchJob/main.go b/internal/generated/snippets/osconfig/apiv1/Client/GetPatchJob/main.go index 6f2a8b722c98..446f408cf216 100644 --- a/internal/generated/snippets/osconfig/apiv1/Client/GetPatchJob/main.go +++ b/internal/generated/snippets/osconfig/apiv1/Client/GetPatchJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.GetPatchJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1/Client/ListPatchDeployments/main.go b/internal/generated/snippets/osconfig/apiv1/Client/ListPatchDeployments/main.go index d38b0d91404b..183a2dbf9699 100644 --- a/internal/generated/snippets/osconfig/apiv1/Client/ListPatchDeployments/main.go +++ b/internal/generated/snippets/osconfig/apiv1/Client/ListPatchDeployments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListPatchDeploymentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1/Client/ListPatchJobInstanceDetails/main.go b/internal/generated/snippets/osconfig/apiv1/Client/ListPatchJobInstanceDetails/main.go index a4c9f245c5d8..d29c5795bd81 100644 --- a/internal/generated/snippets/osconfig/apiv1/Client/ListPatchJobInstanceDetails/main.go +++ b/internal/generated/snippets/osconfig/apiv1/Client/ListPatchJobInstanceDetails/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListPatchJobInstanceDetailsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1/Client/ListPatchJobs/main.go b/internal/generated/snippets/osconfig/apiv1/Client/ListPatchJobs/main.go index 6918ea972c3f..6f28029105bf 100644 --- a/internal/generated/snippets/osconfig/apiv1/Client/ListPatchJobs/main.go +++ b/internal/generated/snippets/osconfig/apiv1/Client/ListPatchJobs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListPatchJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/CreateOSPolicyAssignment/main.go b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/CreateOSPolicyAssignment/main.go new file mode 100644 index 000000000000..85d09aa7c6a1 --- /dev/null +++ b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/CreateOSPolicyAssignment/main.go @@ -0,0 +1,50 @@ +// Copyright 2021 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. + +// [START osconfig_v1alpha_generated_OsConfigZonalService_CreateOSPolicyAssignment_sync] + +package main + +import ( + "context" + + osconfig "cloud.google.com/go/osconfig/apiv1alpha" + osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" +) + +func main() { + ctx := context.Background() + c, err := osconfig.NewOsConfigZonalClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &osconfigpb.CreateOSPolicyAssignmentRequest{ + // TODO: Fill request struct fields. + } + op, err := c.CreateOSPolicyAssignment(ctx, req) + if err != nil { + // TODO: Handle error. + } + + resp, err := op.Wait(ctx) + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp +} + +// [END osconfig_v1alpha_generated_OsConfigZonalService_CreateOSPolicyAssignment_sync] diff --git a/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/DeleteOSPolicyAssignment/main.go b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/DeleteOSPolicyAssignment/main.go new file mode 100644 index 000000000000..c5fc97f82760 --- /dev/null +++ b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/DeleteOSPolicyAssignment/main.go @@ -0,0 +1,48 @@ +// Copyright 2021 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. + +// [START osconfig_v1alpha_generated_OsConfigZonalService_DeleteOSPolicyAssignment_sync] + +package main + +import ( + "context" + + osconfig "cloud.google.com/go/osconfig/apiv1alpha" + osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" +) + +func main() { + ctx := context.Background() + c, err := osconfig.NewOsConfigZonalClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &osconfigpb.DeleteOSPolicyAssignmentRequest{ + // TODO: Fill request struct fields. + } + op, err := c.DeleteOSPolicyAssignment(ctx, req) + if err != nil { + // TODO: Handle error. + } + + err = op.Wait(ctx) + if err != nil { + // TODO: Handle error. + } +} + +// [END osconfig_v1alpha_generated_OsConfigZonalService_DeleteOSPolicyAssignment_sync] diff --git a/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/GetInstanceOSPoliciesCompliance/main.go b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/GetInstanceOSPoliciesCompliance/main.go new file mode 100644 index 000000000000..12fd92a09206 --- /dev/null +++ b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/GetInstanceOSPoliciesCompliance/main.go @@ -0,0 +1,45 @@ +// Copyright 2021 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. + +// [START osconfig_v1alpha_generated_OsConfigZonalService_GetInstanceOSPoliciesCompliance_sync] + +package main + +import ( + "context" + + osconfig "cloud.google.com/go/osconfig/apiv1alpha" + osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" +) + +func main() { + ctx := context.Background() + c, err := osconfig.NewOsConfigZonalClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &osconfigpb.GetInstanceOSPoliciesComplianceRequest{ + // TODO: Fill request struct fields. + } + resp, err := c.GetInstanceOSPoliciesCompliance(ctx, req) + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp +} + +// [END osconfig_v1alpha_generated_OsConfigZonalService_GetInstanceOSPoliciesCompliance_sync] diff --git a/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/GetInventory/main.go b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/GetInventory/main.go new file mode 100644 index 000000000000..798f17e2960d --- /dev/null +++ b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/GetInventory/main.go @@ -0,0 +1,45 @@ +// Copyright 2021 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. + +// [START osconfig_v1alpha_generated_OsConfigZonalService_GetInventory_sync] + +package main + +import ( + "context" + + osconfig "cloud.google.com/go/osconfig/apiv1alpha" + osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" +) + +func main() { + ctx := context.Background() + c, err := osconfig.NewOsConfigZonalClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &osconfigpb.GetInventoryRequest{ + // TODO: Fill request struct fields. + } + resp, err := c.GetInventory(ctx, req) + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp +} + +// [END osconfig_v1alpha_generated_OsConfigZonalService_GetInventory_sync] diff --git a/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/GetOSPolicyAssignment/main.go b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/GetOSPolicyAssignment/main.go new file mode 100644 index 000000000000..5f880648a947 --- /dev/null +++ b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/GetOSPolicyAssignment/main.go @@ -0,0 +1,45 @@ +// Copyright 2021 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. + +// [START osconfig_v1alpha_generated_OsConfigZonalService_GetOSPolicyAssignment_sync] + +package main + +import ( + "context" + + osconfig "cloud.google.com/go/osconfig/apiv1alpha" + osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" +) + +func main() { + ctx := context.Background() + c, err := osconfig.NewOsConfigZonalClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &osconfigpb.GetOSPolicyAssignmentRequest{ + // TODO: Fill request struct fields. + } + resp, err := c.GetOSPolicyAssignment(ctx, req) + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp +} + +// [END osconfig_v1alpha_generated_OsConfigZonalService_GetOSPolicyAssignment_sync] diff --git a/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/GetVulnerabilityReport/main.go b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/GetVulnerabilityReport/main.go new file mode 100644 index 000000000000..72db847f84dc --- /dev/null +++ b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/GetVulnerabilityReport/main.go @@ -0,0 +1,45 @@ +// Copyright 2021 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. + +// [START osconfig_v1alpha_generated_OsConfigZonalService_GetVulnerabilityReport_sync] + +package main + +import ( + "context" + + osconfig "cloud.google.com/go/osconfig/apiv1alpha" + osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" +) + +func main() { + ctx := context.Background() + c, err := osconfig.NewOsConfigZonalClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &osconfigpb.GetVulnerabilityReportRequest{ + // TODO: Fill request struct fields. + } + resp, err := c.GetVulnerabilityReport(ctx, req) + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp +} + +// [END osconfig_v1alpha_generated_OsConfigZonalService_GetVulnerabilityReport_sync] diff --git a/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/ListInstanceOSPoliciesCompliances/main.go b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/ListInstanceOSPoliciesCompliances/main.go new file mode 100644 index 000000000000..40acca57ff8b --- /dev/null +++ b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/ListInstanceOSPoliciesCompliances/main.go @@ -0,0 +1,52 @@ +// Copyright 2021 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. + +// [START osconfig_v1alpha_generated_OsConfigZonalService_ListInstanceOSPoliciesCompliances_sync] + +package main + +import ( + "context" + + osconfig "cloud.google.com/go/osconfig/apiv1alpha" + "google.golang.org/api/iterator" + osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" +) + +func main() { + ctx := context.Background() + c, err := osconfig.NewOsConfigZonalClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &osconfigpb.ListInstanceOSPoliciesCompliancesRequest{ + // TODO: Fill request struct fields. + } + it := c.ListInstanceOSPoliciesCompliances(ctx, req) + for { + resp, err := it.Next() + if err == iterator.Done { + break + } + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp + } +} + +// [END osconfig_v1alpha_generated_OsConfigZonalService_ListInstanceOSPoliciesCompliances_sync] diff --git a/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/ListInventories/main.go b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/ListInventories/main.go new file mode 100644 index 000000000000..5719adc1e48b --- /dev/null +++ b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/ListInventories/main.go @@ -0,0 +1,52 @@ +// Copyright 2021 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. + +// [START osconfig_v1alpha_generated_OsConfigZonalService_ListInventories_sync] + +package main + +import ( + "context" + + osconfig "cloud.google.com/go/osconfig/apiv1alpha" + "google.golang.org/api/iterator" + osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" +) + +func main() { + ctx := context.Background() + c, err := osconfig.NewOsConfigZonalClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &osconfigpb.ListInventoriesRequest{ + // TODO: Fill request struct fields. + } + it := c.ListInventories(ctx, req) + for { + resp, err := it.Next() + if err == iterator.Done { + break + } + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp + } +} + +// [END osconfig_v1alpha_generated_OsConfigZonalService_ListInventories_sync] diff --git a/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/ListOSPolicyAssignmentRevisions/main.go b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/ListOSPolicyAssignmentRevisions/main.go new file mode 100644 index 000000000000..dd78871254c5 --- /dev/null +++ b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/ListOSPolicyAssignmentRevisions/main.go @@ -0,0 +1,52 @@ +// Copyright 2021 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. + +// [START osconfig_v1alpha_generated_OsConfigZonalService_ListOSPolicyAssignmentRevisions_sync] + +package main + +import ( + "context" + + osconfig "cloud.google.com/go/osconfig/apiv1alpha" + "google.golang.org/api/iterator" + osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" +) + +func main() { + ctx := context.Background() + c, err := osconfig.NewOsConfigZonalClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &osconfigpb.ListOSPolicyAssignmentRevisionsRequest{ + // TODO: Fill request struct fields. + } + it := c.ListOSPolicyAssignmentRevisions(ctx, req) + for { + resp, err := it.Next() + if err == iterator.Done { + break + } + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp + } +} + +// [END osconfig_v1alpha_generated_OsConfigZonalService_ListOSPolicyAssignmentRevisions_sync] diff --git a/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/ListOSPolicyAssignments/main.go b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/ListOSPolicyAssignments/main.go new file mode 100644 index 000000000000..af84f042847e --- /dev/null +++ b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/ListOSPolicyAssignments/main.go @@ -0,0 +1,52 @@ +// Copyright 2021 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. + +// [START osconfig_v1alpha_generated_OsConfigZonalService_ListOSPolicyAssignments_sync] + +package main + +import ( + "context" + + osconfig "cloud.google.com/go/osconfig/apiv1alpha" + "google.golang.org/api/iterator" + osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" +) + +func main() { + ctx := context.Background() + c, err := osconfig.NewOsConfigZonalClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &osconfigpb.ListOSPolicyAssignmentsRequest{ + // TODO: Fill request struct fields. + } + it := c.ListOSPolicyAssignments(ctx, req) + for { + resp, err := it.Next() + if err == iterator.Done { + break + } + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp + } +} + +// [END osconfig_v1alpha_generated_OsConfigZonalService_ListOSPolicyAssignments_sync] diff --git a/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/ListVulnerabilityReports/main.go b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/ListVulnerabilityReports/main.go new file mode 100644 index 000000000000..f75f7b970fd2 --- /dev/null +++ b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/ListVulnerabilityReports/main.go @@ -0,0 +1,52 @@ +// Copyright 2021 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. + +// [START osconfig_v1alpha_generated_OsConfigZonalService_ListVulnerabilityReports_sync] + +package main + +import ( + "context" + + osconfig "cloud.google.com/go/osconfig/apiv1alpha" + "google.golang.org/api/iterator" + osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" +) + +func main() { + ctx := context.Background() + c, err := osconfig.NewOsConfigZonalClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &osconfigpb.ListVulnerabilityReportsRequest{ + // TODO: Fill request struct fields. + } + it := c.ListVulnerabilityReports(ctx, req) + for { + resp, err := it.Next() + if err == iterator.Done { + break + } + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp + } +} + +// [END osconfig_v1alpha_generated_OsConfigZonalService_ListVulnerabilityReports_sync] diff --git a/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/UpdateOSPolicyAssignment/main.go b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/UpdateOSPolicyAssignment/main.go new file mode 100644 index 000000000000..d69938275bed --- /dev/null +++ b/internal/generated/snippets/osconfig/apiv1alpha/OsConfigZonalClient/UpdateOSPolicyAssignment/main.go @@ -0,0 +1,50 @@ +// Copyright 2021 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. + +// [START osconfig_v1alpha_generated_OsConfigZonalService_UpdateOSPolicyAssignment_sync] + +package main + +import ( + "context" + + osconfig "cloud.google.com/go/osconfig/apiv1alpha" + osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" +) + +func main() { + ctx := context.Background() + c, err := osconfig.NewOsConfigZonalClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &osconfigpb.UpdateOSPolicyAssignmentRequest{ + // TODO: Fill request struct fields. + } + op, err := c.UpdateOSPolicyAssignment(ctx, req) + if err != nil { + // TODO: Handle error. + } + + resp, err := op.Wait(ctx) + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp +} + +// [END osconfig_v1alpha_generated_OsConfigZonalService_UpdateOSPolicyAssignment_sync] diff --git a/internal/generated/snippets/osconfig/apiv1beta/Client/CancelPatchJob/main.go b/internal/generated/snippets/osconfig/apiv1beta/Client/CancelPatchJob/main.go index c5326b7658ac..9758936e8f24 100644 --- a/internal/generated/snippets/osconfig/apiv1beta/Client/CancelPatchJob/main.go +++ b/internal/generated/snippets/osconfig/apiv1beta/Client/CancelPatchJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.CancelPatchJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1beta/Client/CreateGuestPolicy/main.go b/internal/generated/snippets/osconfig/apiv1beta/Client/CreateGuestPolicy/main.go index 8c04c6090583..0851b9db416b 100644 --- a/internal/generated/snippets/osconfig/apiv1beta/Client/CreateGuestPolicy/main.go +++ b/internal/generated/snippets/osconfig/apiv1beta/Client/CreateGuestPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.CreateGuestPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1beta/Client/CreatePatchDeployment/main.go b/internal/generated/snippets/osconfig/apiv1beta/Client/CreatePatchDeployment/main.go index ca4687239f45..efd14c165281 100644 --- a/internal/generated/snippets/osconfig/apiv1beta/Client/CreatePatchDeployment/main.go +++ b/internal/generated/snippets/osconfig/apiv1beta/Client/CreatePatchDeployment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.CreatePatchDeploymentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1beta/Client/DeleteGuestPolicy/main.go b/internal/generated/snippets/osconfig/apiv1beta/Client/DeleteGuestPolicy/main.go index 89c015ce02a8..f1e31269ae3f 100644 --- a/internal/generated/snippets/osconfig/apiv1beta/Client/DeleteGuestPolicy/main.go +++ b/internal/generated/snippets/osconfig/apiv1beta/Client/DeleteGuestPolicy/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.DeleteGuestPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1beta/Client/DeletePatchDeployment/main.go b/internal/generated/snippets/osconfig/apiv1beta/Client/DeletePatchDeployment/main.go index 2c68ef748edb..053a379d4588 100644 --- a/internal/generated/snippets/osconfig/apiv1beta/Client/DeletePatchDeployment/main.go +++ b/internal/generated/snippets/osconfig/apiv1beta/Client/DeletePatchDeployment/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.DeletePatchDeploymentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1beta/Client/ExecutePatchJob/main.go b/internal/generated/snippets/osconfig/apiv1beta/Client/ExecutePatchJob/main.go index e72359620e05..7da54646311d 100644 --- a/internal/generated/snippets/osconfig/apiv1beta/Client/ExecutePatchJob/main.go +++ b/internal/generated/snippets/osconfig/apiv1beta/Client/ExecutePatchJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ExecutePatchJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1beta/Client/GetGuestPolicy/main.go b/internal/generated/snippets/osconfig/apiv1beta/Client/GetGuestPolicy/main.go index d6dbd0d1e19d..846bcafacac3 100644 --- a/internal/generated/snippets/osconfig/apiv1beta/Client/GetGuestPolicy/main.go +++ b/internal/generated/snippets/osconfig/apiv1beta/Client/GetGuestPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.GetGuestPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1beta/Client/GetPatchDeployment/main.go b/internal/generated/snippets/osconfig/apiv1beta/Client/GetPatchDeployment/main.go index 829a3009d501..8a54fccaf6cf 100644 --- a/internal/generated/snippets/osconfig/apiv1beta/Client/GetPatchDeployment/main.go +++ b/internal/generated/snippets/osconfig/apiv1beta/Client/GetPatchDeployment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.GetPatchDeploymentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1beta/Client/GetPatchJob/main.go b/internal/generated/snippets/osconfig/apiv1beta/Client/GetPatchJob/main.go index 77b477bd5c0a..af087732f283 100644 --- a/internal/generated/snippets/osconfig/apiv1beta/Client/GetPatchJob/main.go +++ b/internal/generated/snippets/osconfig/apiv1beta/Client/GetPatchJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.GetPatchJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1beta/Client/ListGuestPolicies/main.go b/internal/generated/snippets/osconfig/apiv1beta/Client/ListGuestPolicies/main.go index f3cdd62647db..c6a0d487216c 100644 --- a/internal/generated/snippets/osconfig/apiv1beta/Client/ListGuestPolicies/main.go +++ b/internal/generated/snippets/osconfig/apiv1beta/Client/ListGuestPolicies/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListGuestPoliciesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1beta/Client/ListPatchDeployments/main.go b/internal/generated/snippets/osconfig/apiv1beta/Client/ListPatchDeployments/main.go index 9463d2a08b27..9b3d293aed2d 100644 --- a/internal/generated/snippets/osconfig/apiv1beta/Client/ListPatchDeployments/main.go +++ b/internal/generated/snippets/osconfig/apiv1beta/Client/ListPatchDeployments/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListPatchDeploymentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1beta/Client/ListPatchJobInstanceDetails/main.go b/internal/generated/snippets/osconfig/apiv1beta/Client/ListPatchJobInstanceDetails/main.go index ce33b0cbee33..63a7bf177ee7 100644 --- a/internal/generated/snippets/osconfig/apiv1beta/Client/ListPatchJobInstanceDetails/main.go +++ b/internal/generated/snippets/osconfig/apiv1beta/Client/ListPatchJobInstanceDetails/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListPatchJobInstanceDetailsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1beta/Client/ListPatchJobs/main.go b/internal/generated/snippets/osconfig/apiv1beta/Client/ListPatchJobs/main.go index f733596eca8f..d4bbebad796d 100644 --- a/internal/generated/snippets/osconfig/apiv1beta/Client/ListPatchJobs/main.go +++ b/internal/generated/snippets/osconfig/apiv1beta/Client/ListPatchJobs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListPatchJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1beta/Client/LookupEffectiveGuestPolicy/main.go b/internal/generated/snippets/osconfig/apiv1beta/Client/LookupEffectiveGuestPolicy/main.go index 9f69a34eb606..4ecf6ecc1e0e 100644 --- a/internal/generated/snippets/osconfig/apiv1beta/Client/LookupEffectiveGuestPolicy/main.go +++ b/internal/generated/snippets/osconfig/apiv1beta/Client/LookupEffectiveGuestPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.LookupEffectiveGuestPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/osconfig/apiv1beta/Client/UpdateGuestPolicy/main.go b/internal/generated/snippets/osconfig/apiv1beta/Client/UpdateGuestPolicy/main.go index e9c47b05dada..86f1d0c94077 100644 --- a/internal/generated/snippets/osconfig/apiv1beta/Client/UpdateGuestPolicy/main.go +++ b/internal/generated/snippets/osconfig/apiv1beta/Client/UpdateGuestPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.UpdateGuestPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/oslogin/apiv1/Client/DeletePosixAccount/main.go b/internal/generated/snippets/oslogin/apiv1/Client/DeletePosixAccount/main.go index e4a4a38b907d..9d0d0784049a 100644 --- a/internal/generated/snippets/oslogin/apiv1/Client/DeletePosixAccount/main.go +++ b/internal/generated/snippets/oslogin/apiv1/Client/DeletePosixAccount/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.DeletePosixAccountRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/oslogin/apiv1/Client/DeleteSshPublicKey/main.go b/internal/generated/snippets/oslogin/apiv1/Client/DeleteSshPublicKey/main.go index df467dcb5fb0..9c80b99636a1 100644 --- a/internal/generated/snippets/oslogin/apiv1/Client/DeleteSshPublicKey/main.go +++ b/internal/generated/snippets/oslogin/apiv1/Client/DeleteSshPublicKey/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.DeleteSshPublicKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/oslogin/apiv1/Client/GetLoginProfile/main.go b/internal/generated/snippets/oslogin/apiv1/Client/GetLoginProfile/main.go index 0fbf4738b9f9..3eb3148e7183 100644 --- a/internal/generated/snippets/oslogin/apiv1/Client/GetLoginProfile/main.go +++ b/internal/generated/snippets/oslogin/apiv1/Client/GetLoginProfile/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osloginpb "google.golang.org/genproto/googleapis/cloud/oslogin/v1" - ctx := context.Background() c, err := oslogin.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.GetLoginProfileRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/oslogin/apiv1/Client/GetSshPublicKey/main.go b/internal/generated/snippets/oslogin/apiv1/Client/GetSshPublicKey/main.go index 15d948b2b64e..4a02c782e8e9 100644 --- a/internal/generated/snippets/oslogin/apiv1/Client/GetSshPublicKey/main.go +++ b/internal/generated/snippets/oslogin/apiv1/Client/GetSshPublicKey/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osloginpb "google.golang.org/genproto/googleapis/cloud/oslogin/v1" - ctx := context.Background() c, err := oslogin.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.GetSshPublicKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/oslogin/apiv1/Client/ImportSshPublicKey/main.go b/internal/generated/snippets/oslogin/apiv1/Client/ImportSshPublicKey/main.go index 3ae204d661e7..621dd1dce201 100644 --- a/internal/generated/snippets/oslogin/apiv1/Client/ImportSshPublicKey/main.go +++ b/internal/generated/snippets/oslogin/apiv1/Client/ImportSshPublicKey/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osloginpb "google.golang.org/genproto/googleapis/cloud/oslogin/v1" - ctx := context.Background() c, err := oslogin.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.ImportSshPublicKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/oslogin/apiv1/Client/UpdateSshPublicKey/main.go b/internal/generated/snippets/oslogin/apiv1/Client/UpdateSshPublicKey/main.go index 3c3219c22829..2632aa9e1837 100644 --- a/internal/generated/snippets/oslogin/apiv1/Client/UpdateSshPublicKey/main.go +++ b/internal/generated/snippets/oslogin/apiv1/Client/UpdateSshPublicKey/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osloginpb "google.golang.org/genproto/googleapis/cloud/oslogin/v1" - ctx := context.Background() c, err := oslogin.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.UpdateSshPublicKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/oslogin/apiv1beta/Client/DeletePosixAccount/main.go b/internal/generated/snippets/oslogin/apiv1beta/Client/DeletePosixAccount/main.go index a34f045fcfb0..0745a51d3544 100644 --- a/internal/generated/snippets/oslogin/apiv1beta/Client/DeletePosixAccount/main.go +++ b/internal/generated/snippets/oslogin/apiv1beta/Client/DeletePosixAccount/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.DeletePosixAccountRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/oslogin/apiv1beta/Client/DeleteSshPublicKey/main.go b/internal/generated/snippets/oslogin/apiv1beta/Client/DeleteSshPublicKey/main.go index 3be36c107ffa..5be842f25caa 100644 --- a/internal/generated/snippets/oslogin/apiv1beta/Client/DeleteSshPublicKey/main.go +++ b/internal/generated/snippets/oslogin/apiv1beta/Client/DeleteSshPublicKey/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.DeleteSshPublicKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/oslogin/apiv1beta/Client/GetLoginProfile/main.go b/internal/generated/snippets/oslogin/apiv1beta/Client/GetLoginProfile/main.go index 4ee77eff95c0..8e3dfa908016 100644 --- a/internal/generated/snippets/oslogin/apiv1beta/Client/GetLoginProfile/main.go +++ b/internal/generated/snippets/oslogin/apiv1beta/Client/GetLoginProfile/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osloginpb "google.golang.org/genproto/googleapis/cloud/oslogin/v1beta" - ctx := context.Background() c, err := oslogin.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.GetLoginProfileRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/oslogin/apiv1beta/Client/GetSshPublicKey/main.go b/internal/generated/snippets/oslogin/apiv1beta/Client/GetSshPublicKey/main.go index 5cc5461c4dec..7d69fb334d05 100644 --- a/internal/generated/snippets/oslogin/apiv1beta/Client/GetSshPublicKey/main.go +++ b/internal/generated/snippets/oslogin/apiv1beta/Client/GetSshPublicKey/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osloginpb "google.golang.org/genproto/googleapis/cloud/oslogin/v1beta" - ctx := context.Background() c, err := oslogin.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.GetSshPublicKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/oslogin/apiv1beta/Client/ImportSshPublicKey/main.go b/internal/generated/snippets/oslogin/apiv1beta/Client/ImportSshPublicKey/main.go index 75ab4c315cbf..25fa137be0d8 100644 --- a/internal/generated/snippets/oslogin/apiv1beta/Client/ImportSshPublicKey/main.go +++ b/internal/generated/snippets/oslogin/apiv1beta/Client/ImportSshPublicKey/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osloginpb "google.golang.org/genproto/googleapis/cloud/oslogin/v1beta" - ctx := context.Background() c, err := oslogin.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.ImportSshPublicKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/oslogin/apiv1beta/Client/UpdateSshPublicKey/main.go b/internal/generated/snippets/oslogin/apiv1beta/Client/UpdateSshPublicKey/main.go index e555e4f5b66a..057ec32d7a57 100644 --- a/internal/generated/snippets/oslogin/apiv1beta/Client/UpdateSshPublicKey/main.go +++ b/internal/generated/snippets/oslogin/apiv1beta/Client/UpdateSshPublicKey/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import osloginpb "google.golang.org/genproto/googleapis/cloud/oslogin/v1beta" - ctx := context.Background() c, err := oslogin.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.UpdateSshPublicKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/phishingprotection/apiv1beta1/PhishingProtectionServiceV1Beta1Client/ReportPhishing/main.go b/internal/generated/snippets/phishingprotection/apiv1beta1/PhishingProtectionServiceV1Beta1Client/ReportPhishing/main.go index 7a7318ccd644..06eb01c1ff07 100644 --- a/internal/generated/snippets/phishingprotection/apiv1beta1/PhishingProtectionServiceV1Beta1Client/ReportPhishing/main.go +++ b/internal/generated/snippets/phishingprotection/apiv1beta1/PhishingProtectionServiceV1Beta1Client/ReportPhishing/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import phishingprotectionpb "google.golang.org/genproto/googleapis/cloud/phishingprotection/v1beta1" - ctx := context.Background() c, err := phishingprotection.NewPhishingProtectionServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &phishingprotectionpb.ReportPhishingRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/policytroubleshooter/apiv1/IamCheckerClient/TroubleshootIamPolicy/main.go b/internal/generated/snippets/policytroubleshooter/apiv1/IamCheckerClient/TroubleshootIamPolicy/main.go index 608fa76a0c59..bde43fd2f47c 100644 --- a/internal/generated/snippets/policytroubleshooter/apiv1/IamCheckerClient/TroubleshootIamPolicy/main.go +++ b/internal/generated/snippets/policytroubleshooter/apiv1/IamCheckerClient/TroubleshootIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import policytroubleshooterpb "google.golang.org/genproto/googleapis/cloud/policytroubleshooter/v1" - ctx := context.Background() c, err := policytroubleshooter.NewIamCheckerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &policytroubleshooterpb.TroubleshootIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/PublisherClient/CreateTopic/main.go b/internal/generated/snippets/pubsub/apiv1/PublisherClient/CreateTopic/main.go index 43b36a94d685..7376c93c99d8 100644 --- a/internal/generated/snippets/pubsub/apiv1/PublisherClient/CreateTopic/main.go +++ b/internal/generated/snippets/pubsub/apiv1/PublisherClient/CreateTopic/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.Topic{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/PublisherClient/DeleteTopic/main.go b/internal/generated/snippets/pubsub/apiv1/PublisherClient/DeleteTopic/main.go index 43021fe1d29d..979b2c4dd5c4 100644 --- a/internal/generated/snippets/pubsub/apiv1/PublisherClient/DeleteTopic/main.go +++ b/internal/generated/snippets/pubsub/apiv1/PublisherClient/DeleteTopic/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.DeleteTopicRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/PublisherClient/DetachSubscription/main.go b/internal/generated/snippets/pubsub/apiv1/PublisherClient/DetachSubscription/main.go index e60162239222..4f969043dedb 100644 --- a/internal/generated/snippets/pubsub/apiv1/PublisherClient/DetachSubscription/main.go +++ b/internal/generated/snippets/pubsub/apiv1/PublisherClient/DetachSubscription/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.DetachSubscriptionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/PublisherClient/GetTopic/main.go b/internal/generated/snippets/pubsub/apiv1/PublisherClient/GetTopic/main.go index 2585752bd57e..927d2f99b364 100644 --- a/internal/generated/snippets/pubsub/apiv1/PublisherClient/GetTopic/main.go +++ b/internal/generated/snippets/pubsub/apiv1/PublisherClient/GetTopic/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.GetTopicRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/PublisherClient/ListTopicSnapshots/main.go b/internal/generated/snippets/pubsub/apiv1/PublisherClient/ListTopicSnapshots/main.go index 0dafdd7292ab..373325576ed8 100644 --- a/internal/generated/snippets/pubsub/apiv1/PublisherClient/ListTopicSnapshots/main.go +++ b/internal/generated/snippets/pubsub/apiv1/PublisherClient/ListTopicSnapshots/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsub.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ListTopicSnapshotsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/PublisherClient/ListTopicSubscriptions/main.go b/internal/generated/snippets/pubsub/apiv1/PublisherClient/ListTopicSubscriptions/main.go index f4d1ab0d17d0..40fc6ac21cd8 100644 --- a/internal/generated/snippets/pubsub/apiv1/PublisherClient/ListTopicSubscriptions/main.go +++ b/internal/generated/snippets/pubsub/apiv1/PublisherClient/ListTopicSubscriptions/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsub.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ListTopicSubscriptionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/PublisherClient/ListTopics/main.go b/internal/generated/snippets/pubsub/apiv1/PublisherClient/ListTopics/main.go index 3fe17ad83781..d0549eb8d56e 100644 --- a/internal/generated/snippets/pubsub/apiv1/PublisherClient/ListTopics/main.go +++ b/internal/generated/snippets/pubsub/apiv1/PublisherClient/ListTopics/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsub.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ListTopicsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/PublisherClient/Publish/main.go b/internal/generated/snippets/pubsub/apiv1/PublisherClient/Publish/main.go index a0d16a4e4b36..6a433944f775 100644 --- a/internal/generated/snippets/pubsub/apiv1/PublisherClient/Publish/main.go +++ b/internal/generated/snippets/pubsub/apiv1/PublisherClient/Publish/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.PublishRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/PublisherClient/UpdateTopic/main.go b/internal/generated/snippets/pubsub/apiv1/PublisherClient/UpdateTopic/main.go index f6c845a3aa6f..3911cae8cb21 100644 --- a/internal/generated/snippets/pubsub/apiv1/PublisherClient/UpdateTopic/main.go +++ b/internal/generated/snippets/pubsub/apiv1/PublisherClient/UpdateTopic/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.UpdateTopicRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SchemaClient/CreateSchema/main.go b/internal/generated/snippets/pubsub/apiv1/SchemaClient/CreateSchema/main.go index f93ff5f2fbd5..360bd74ece04 100644 --- a/internal/generated/snippets/pubsub/apiv1/SchemaClient/CreateSchema/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SchemaClient/CreateSchema/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSchemaClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.CreateSchemaRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SchemaClient/DeleteSchema/main.go b/internal/generated/snippets/pubsub/apiv1/SchemaClient/DeleteSchema/main.go index 5bdcf9394f6e..8d65f23c4504 100644 --- a/internal/generated/snippets/pubsub/apiv1/SchemaClient/DeleteSchema/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SchemaClient/DeleteSchema/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.DeleteSchemaRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SchemaClient/GetSchema/main.go b/internal/generated/snippets/pubsub/apiv1/SchemaClient/GetSchema/main.go index 0003772f9d01..ad731e6dd11a 100644 --- a/internal/generated/snippets/pubsub/apiv1/SchemaClient/GetSchema/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SchemaClient/GetSchema/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSchemaClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.GetSchemaRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SchemaClient/ListSchemas/main.go b/internal/generated/snippets/pubsub/apiv1/SchemaClient/ListSchemas/main.go index f723bca64f65..9c988ff0dcd9 100644 --- a/internal/generated/snippets/pubsub/apiv1/SchemaClient/ListSchemas/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SchemaClient/ListSchemas/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsub.NewSchemaClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ListSchemasRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SchemaClient/ValidateMessage/main.go b/internal/generated/snippets/pubsub/apiv1/SchemaClient/ValidateMessage/main.go index 348167bc1c72..e412dc46ab2d 100644 --- a/internal/generated/snippets/pubsub/apiv1/SchemaClient/ValidateMessage/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SchemaClient/ValidateMessage/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSchemaClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ValidateMessageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SchemaClient/ValidateSchema/main.go b/internal/generated/snippets/pubsub/apiv1/SchemaClient/ValidateSchema/main.go index 4b804d0d42fa..ab756e73f578 100644 --- a/internal/generated/snippets/pubsub/apiv1/SchemaClient/ValidateSchema/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SchemaClient/ValidateSchema/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSchemaClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ValidateSchemaRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/Acknowledge/main.go b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/Acknowledge/main.go index d52aaa0a71bf..149be3677d08 100644 --- a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/Acknowledge/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/Acknowledge/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.AcknowledgeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/CreateSnapshot/main.go b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/CreateSnapshot/main.go index 6804508e68d1..cb5622d29714 100644 --- a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/CreateSnapshot/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/CreateSnapshot/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.CreateSnapshotRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/CreateSubscription/main.go b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/CreateSubscription/main.go index 50dc6372d286..1430440a1a02 100644 --- a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/CreateSubscription/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/CreateSubscription/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.Subscription{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/DeleteSnapshot/main.go b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/DeleteSnapshot/main.go index 0b694b2d17a2..922c245921c3 100644 --- a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/DeleteSnapshot/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/DeleteSnapshot/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.DeleteSnapshotRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/DeleteSubscription/main.go b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/DeleteSubscription/main.go index 4e944f4aa0eb..d094f31d029b 100644 --- a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/DeleteSubscription/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/DeleteSubscription/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.DeleteSubscriptionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/GetSnapshot/main.go b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/GetSnapshot/main.go index 2fe8ee41a713..56da486520a8 100644 --- a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/GetSnapshot/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/GetSnapshot/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.GetSnapshotRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/GetSubscription/main.go b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/GetSubscription/main.go index 090d2e9859c4..bed512d7126f 100644 --- a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/GetSubscription/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/GetSubscription/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.GetSubscriptionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/ListSnapshots/main.go b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/ListSnapshots/main.go index 14aa0193011e..871a4085d520 100644 --- a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/ListSnapshots/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/ListSnapshots/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ListSnapshotsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/ListSubscriptions/main.go b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/ListSubscriptions/main.go index 45e5ab2bbee9..4fd76f02c6d8 100644 --- a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/ListSubscriptions/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/ListSubscriptions/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ListSubscriptionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/ModifyAckDeadline/main.go b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/ModifyAckDeadline/main.go index 99f8d0397912..5aa94a00eed9 100644 --- a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/ModifyAckDeadline/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/ModifyAckDeadline/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ModifyAckDeadlineRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/ModifyPushConfig/main.go b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/ModifyPushConfig/main.go index 54ba434ce722..cdd0db181671 100644 --- a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/ModifyPushConfig/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/ModifyPushConfig/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ModifyPushConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/Pull/main.go b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/Pull/main.go index aeae521581be..c18c1a199c95 100644 --- a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/Pull/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/Pull/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.PullRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/Seek/main.go b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/Seek/main.go index 0c9ef4a43eeb..58f2c81516fb 100644 --- a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/Seek/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/Seek/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.SeekRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/StreamingPull/main.go b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/StreamingPull/main.go index 0e34d2cac1ae..4a244f2a88f3 100644 --- a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/StreamingPull/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/StreamingPull/main.go @@ -25,13 +25,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.StreamingPull(ctx) if err != nil { // TODO: Handle error. diff --git a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/UpdateSnapshot/main.go b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/UpdateSnapshot/main.go index 320eb2dab178..8559c10e6749 100644 --- a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/UpdateSnapshot/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/UpdateSnapshot/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.UpdateSnapshotRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/UpdateSubscription/main.go b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/UpdateSubscription/main.go index 6cd118504cd4..ca51a42a647b 100644 --- a/internal/generated/snippets/pubsub/apiv1/SubscriberClient/UpdateSubscription/main.go +++ b/internal/generated/snippets/pubsub/apiv1/SubscriberClient/UpdateSubscription/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.UpdateSubscriptionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsublite/apiv1/AdminClient/CreateSubscription/main.go b/internal/generated/snippets/pubsublite/apiv1/AdminClient/CreateSubscription/main.go index 977d16e85d9c..901f60a363b0 100644 --- a/internal/generated/snippets/pubsublite/apiv1/AdminClient/CreateSubscription/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/AdminClient/CreateSubscription/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.CreateSubscriptionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsublite/apiv1/AdminClient/CreateTopic/main.go b/internal/generated/snippets/pubsublite/apiv1/AdminClient/CreateTopic/main.go index f1fe395cff60..f8d208b57e33 100644 --- a/internal/generated/snippets/pubsublite/apiv1/AdminClient/CreateTopic/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/AdminClient/CreateTopic/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.CreateTopicRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsublite/apiv1/AdminClient/DeleteSubscription/main.go b/internal/generated/snippets/pubsublite/apiv1/AdminClient/DeleteSubscription/main.go index 26ccc721b543..79a8bfc2b1d7 100644 --- a/internal/generated/snippets/pubsublite/apiv1/AdminClient/DeleteSubscription/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/AdminClient/DeleteSubscription/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.DeleteSubscriptionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsublite/apiv1/AdminClient/DeleteTopic/main.go b/internal/generated/snippets/pubsublite/apiv1/AdminClient/DeleteTopic/main.go index 3cd5f11719ee..2fc7c59cf45c 100644 --- a/internal/generated/snippets/pubsublite/apiv1/AdminClient/DeleteTopic/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/AdminClient/DeleteTopic/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.DeleteTopicRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsublite/apiv1/AdminClient/GetSubscription/main.go b/internal/generated/snippets/pubsublite/apiv1/AdminClient/GetSubscription/main.go index 904dc4ddf607..b2bb3fed5569 100644 --- a/internal/generated/snippets/pubsublite/apiv1/AdminClient/GetSubscription/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/AdminClient/GetSubscription/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.GetSubscriptionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsublite/apiv1/AdminClient/GetTopic/main.go b/internal/generated/snippets/pubsublite/apiv1/AdminClient/GetTopic/main.go index 1d54a3499f4a..f6ada1d6d258 100644 --- a/internal/generated/snippets/pubsublite/apiv1/AdminClient/GetTopic/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/AdminClient/GetTopic/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.GetTopicRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsublite/apiv1/AdminClient/GetTopicPartitions/main.go b/internal/generated/snippets/pubsublite/apiv1/AdminClient/GetTopicPartitions/main.go index 28538e1c008a..74fad5d03f4c 100644 --- a/internal/generated/snippets/pubsublite/apiv1/AdminClient/GetTopicPartitions/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/AdminClient/GetTopicPartitions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.GetTopicPartitionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsublite/apiv1/AdminClient/ListSubscriptions/main.go b/internal/generated/snippets/pubsublite/apiv1/AdminClient/ListSubscriptions/main.go index 385759a20f82..3c805c63f2a2 100644 --- a/internal/generated/snippets/pubsublite/apiv1/AdminClient/ListSubscriptions/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/AdminClient/ListSubscriptions/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.ListSubscriptionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsublite/apiv1/AdminClient/ListTopicSubscriptions/main.go b/internal/generated/snippets/pubsublite/apiv1/AdminClient/ListTopicSubscriptions/main.go index 00948f47bbeb..06fe5f51cff4 100644 --- a/internal/generated/snippets/pubsublite/apiv1/AdminClient/ListTopicSubscriptions/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/AdminClient/ListTopicSubscriptions/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.ListTopicSubscriptionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsublite/apiv1/AdminClient/ListTopics/main.go b/internal/generated/snippets/pubsublite/apiv1/AdminClient/ListTopics/main.go index d673f784e1ab..dfef8c3e150e 100644 --- a/internal/generated/snippets/pubsublite/apiv1/AdminClient/ListTopics/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/AdminClient/ListTopics/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.ListTopicsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsublite/apiv1/AdminClient/UpdateSubscription/main.go b/internal/generated/snippets/pubsublite/apiv1/AdminClient/UpdateSubscription/main.go index d16a83347b5a..100d14ffca4c 100644 --- a/internal/generated/snippets/pubsublite/apiv1/AdminClient/UpdateSubscription/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/AdminClient/UpdateSubscription/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.UpdateSubscriptionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsublite/apiv1/AdminClient/UpdateTopic/main.go b/internal/generated/snippets/pubsublite/apiv1/AdminClient/UpdateTopic/main.go index c241aa434f19..4248cfbda08d 100644 --- a/internal/generated/snippets/pubsublite/apiv1/AdminClient/UpdateTopic/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/AdminClient/UpdateTopic/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.UpdateTopicRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsublite/apiv1/CursorClient/CommitCursor/main.go b/internal/generated/snippets/pubsublite/apiv1/CursorClient/CommitCursor/main.go index 8029bc5236db..3698a4964ee5 100644 --- a/internal/generated/snippets/pubsublite/apiv1/CursorClient/CommitCursor/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/CursorClient/CommitCursor/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewCursorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.CommitCursorRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsublite/apiv1/CursorClient/ListPartitionCursors/main.go b/internal/generated/snippets/pubsublite/apiv1/CursorClient/ListPartitionCursors/main.go index 1446c60ef5cc..1dbf563e549f 100644 --- a/internal/generated/snippets/pubsublite/apiv1/CursorClient/ListPartitionCursors/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/CursorClient/ListPartitionCursors/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsublite.NewCursorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.ListPartitionCursorsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsublite/apiv1/CursorClient/StreamingCommitCursor/main.go b/internal/generated/snippets/pubsublite/apiv1/CursorClient/StreamingCommitCursor/main.go index a52a9cbb74ba..712f4bec7779 100644 --- a/internal/generated/snippets/pubsublite/apiv1/CursorClient/StreamingCommitCursor/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/CursorClient/StreamingCommitCursor/main.go @@ -25,13 +25,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewCursorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.StreamingCommitCursor(ctx) if err != nil { // TODO: Handle error. diff --git a/internal/generated/snippets/pubsublite/apiv1/PartitionAssignmentClient/AssignPartitions/main.go b/internal/generated/snippets/pubsublite/apiv1/PartitionAssignmentClient/AssignPartitions/main.go index 49adf2a074d2..a72b652f83f1 100644 --- a/internal/generated/snippets/pubsublite/apiv1/PartitionAssignmentClient/AssignPartitions/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/PartitionAssignmentClient/AssignPartitions/main.go @@ -25,13 +25,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewPartitionAssignmentClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.AssignPartitions(ctx) if err != nil { // TODO: Handle error. diff --git a/internal/generated/snippets/pubsublite/apiv1/PublisherClient/Publish/main.go b/internal/generated/snippets/pubsublite/apiv1/PublisherClient/Publish/main.go index 09b95b15e34f..ecd712cb3fd0 100644 --- a/internal/generated/snippets/pubsublite/apiv1/PublisherClient/Publish/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/PublisherClient/Publish/main.go @@ -25,13 +25,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.Publish(ctx) if err != nil { // TODO: Handle error. diff --git a/internal/generated/snippets/pubsublite/apiv1/SubscriberClient/Subscribe/main.go b/internal/generated/snippets/pubsublite/apiv1/SubscriberClient/Subscribe/main.go index 505ccb749d03..e7f508fec209 100644 --- a/internal/generated/snippets/pubsublite/apiv1/SubscriberClient/Subscribe/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/SubscriberClient/Subscribe/main.go @@ -25,13 +25,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.Subscribe(ctx) if err != nil { // TODO: Handle error. diff --git a/internal/generated/snippets/pubsublite/apiv1/TopicStatsClient/ComputeHeadCursor/main.go b/internal/generated/snippets/pubsublite/apiv1/TopicStatsClient/ComputeHeadCursor/main.go index 9fe38cdb1964..79d16ebbbd17 100644 --- a/internal/generated/snippets/pubsublite/apiv1/TopicStatsClient/ComputeHeadCursor/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/TopicStatsClient/ComputeHeadCursor/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewTopicStatsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.ComputeHeadCursorRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsublite/apiv1/TopicStatsClient/ComputeMessageStats/main.go b/internal/generated/snippets/pubsublite/apiv1/TopicStatsClient/ComputeMessageStats/main.go index 22fa3a11e052..c4725a36869b 100644 --- a/internal/generated/snippets/pubsublite/apiv1/TopicStatsClient/ComputeMessageStats/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/TopicStatsClient/ComputeMessageStats/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewTopicStatsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.ComputeMessageStatsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/pubsublite/apiv1/TopicStatsClient/ComputeTimeCursor/main.go b/internal/generated/snippets/pubsublite/apiv1/TopicStatsClient/ComputeTimeCursor/main.go index 1f2e31d88c60..5b53ba5500d7 100644 --- a/internal/generated/snippets/pubsublite/apiv1/TopicStatsClient/ComputeTimeCursor/main.go +++ b/internal/generated/snippets/pubsublite/apiv1/TopicStatsClient/ComputeTimeCursor/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewTopicStatsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.ComputeTimeCursorRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recaptchaenterprise/apiv1/Client/AnnotateAssessment/main.go b/internal/generated/snippets/recaptchaenterprise/apiv1/Client/AnnotateAssessment/main.go index c2c4907473c4..d5e14f03db20 100644 --- a/internal/generated/snippets/recaptchaenterprise/apiv1/Client/AnnotateAssessment/main.go +++ b/internal/generated/snippets/recaptchaenterprise/apiv1/Client/AnnotateAssessment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1" - ctx := context.Background() c, err := recaptchaenterprise.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.AnnotateAssessmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recaptchaenterprise/apiv1/Client/CreateAssessment/main.go b/internal/generated/snippets/recaptchaenterprise/apiv1/Client/CreateAssessment/main.go index 29a057509b02..45226e95c0b9 100644 --- a/internal/generated/snippets/recaptchaenterprise/apiv1/Client/CreateAssessment/main.go +++ b/internal/generated/snippets/recaptchaenterprise/apiv1/Client/CreateAssessment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1" - ctx := context.Background() c, err := recaptchaenterprise.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.CreateAssessmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recaptchaenterprise/apiv1/Client/CreateKey/main.go b/internal/generated/snippets/recaptchaenterprise/apiv1/Client/CreateKey/main.go index aa2b93b4131c..35ff4bef7ea8 100644 --- a/internal/generated/snippets/recaptchaenterprise/apiv1/Client/CreateKey/main.go +++ b/internal/generated/snippets/recaptchaenterprise/apiv1/Client/CreateKey/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1" - ctx := context.Background() c, err := recaptchaenterprise.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.CreateKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recaptchaenterprise/apiv1/Client/DeleteKey/main.go b/internal/generated/snippets/recaptchaenterprise/apiv1/Client/DeleteKey/main.go index c70cba2c5d2c..9c5c81cbfd25 100644 --- a/internal/generated/snippets/recaptchaenterprise/apiv1/Client/DeleteKey/main.go +++ b/internal/generated/snippets/recaptchaenterprise/apiv1/Client/DeleteKey/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.DeleteKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recaptchaenterprise/apiv1/Client/GetKey/main.go b/internal/generated/snippets/recaptchaenterprise/apiv1/Client/GetKey/main.go index ee4ef161a1b3..3ce5f3d87c3f 100644 --- a/internal/generated/snippets/recaptchaenterprise/apiv1/Client/GetKey/main.go +++ b/internal/generated/snippets/recaptchaenterprise/apiv1/Client/GetKey/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1" - ctx := context.Background() c, err := recaptchaenterprise.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.GetKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recaptchaenterprise/apiv1/Client/ListKeys/main.go b/internal/generated/snippets/recaptchaenterprise/apiv1/Client/ListKeys/main.go index 44f6a73857fe..97c1066e93b6 100644 --- a/internal/generated/snippets/recaptchaenterprise/apiv1/Client/ListKeys/main.go +++ b/internal/generated/snippets/recaptchaenterprise/apiv1/Client/ListKeys/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recaptchaenterprise.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.ListKeysRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recaptchaenterprise/apiv1/Client/UpdateKey/main.go b/internal/generated/snippets/recaptchaenterprise/apiv1/Client/UpdateKey/main.go index 576c2d031e50..129c2c6167d3 100644 --- a/internal/generated/snippets/recaptchaenterprise/apiv1/Client/UpdateKey/main.go +++ b/internal/generated/snippets/recaptchaenterprise/apiv1/Client/UpdateKey/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1" - ctx := context.Background() c, err := recaptchaenterprise.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.UpdateKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/AnnotateAssessment/main.go b/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/AnnotateAssessment/main.go index 81a1ac3bc54f..7fd2c8863fe7 100644 --- a/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/AnnotateAssessment/main.go +++ b/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/AnnotateAssessment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1beta1" - ctx := context.Background() c, err := recaptchaenterprise.NewRecaptchaEnterpriseServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.AnnotateAssessmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/CreateAssessment/main.go b/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/CreateAssessment/main.go index 6b17e35340a7..bab329de4546 100644 --- a/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/CreateAssessment/main.go +++ b/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/CreateAssessment/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1beta1" - ctx := context.Background() c, err := recaptchaenterprise.NewRecaptchaEnterpriseServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.CreateAssessmentRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/CreateKey/main.go b/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/CreateKey/main.go index 49903678c47d..6c3bccdc9026 100644 --- a/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/CreateKey/main.go +++ b/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/CreateKey/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1beta1" - ctx := context.Background() c, err := recaptchaenterprise.NewRecaptchaEnterpriseServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.CreateKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/DeleteKey/main.go b/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/DeleteKey/main.go index 1164237eb4be..d924a9cda228 100644 --- a/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/DeleteKey/main.go +++ b/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/DeleteKey/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.DeleteKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/GetKey/main.go b/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/GetKey/main.go index 2628e2175b29..411f531a2e92 100644 --- a/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/GetKey/main.go +++ b/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/GetKey/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1beta1" - ctx := context.Background() c, err := recaptchaenterprise.NewRecaptchaEnterpriseServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.GetKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/ListKeys/main.go b/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/ListKeys/main.go index 13964b2b490b..112d766f5e42 100644 --- a/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/ListKeys/main.go +++ b/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/ListKeys/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recaptchaenterprise.NewRecaptchaEnterpriseServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.ListKeysRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/UpdateKey/main.go b/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/UpdateKey/main.go index 488cad5637ba..c73f4df17239 100644 --- a/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/UpdateKey/main.go +++ b/internal/generated/snippets/recaptchaenterprise/apiv1beta1/RecaptchaEnterpriseServiceV1Beta1Client/UpdateKey/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1beta1" - ctx := context.Background() c, err := recaptchaenterprise.NewRecaptchaEnterpriseServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.UpdateKeyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/CreateCatalogItem/main.go b/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/CreateCatalogItem/main.go index 3b87cb11b77e..252894d5b370 100644 --- a/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/CreateCatalogItem/main.go +++ b/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/CreateCatalogItem/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.CreateCatalogItemRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/DeleteCatalogItem/main.go b/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/DeleteCatalogItem/main.go index d07d1678df2d..603d0e24875e 100644 --- a/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/DeleteCatalogItem/main.go +++ b/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/DeleteCatalogItem/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.DeleteCatalogItemRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/GetCatalogItem/main.go b/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/GetCatalogItem/main.go index bd8c92bda554..903d65b357ec 100644 --- a/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/GetCatalogItem/main.go +++ b/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/GetCatalogItem/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.GetCatalogItemRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/ImportCatalogItems/main.go b/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/ImportCatalogItems/main.go index 087e24ec0969..174817e224fc 100644 --- a/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/ImportCatalogItems/main.go +++ b/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/ImportCatalogItems/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.ImportCatalogItemsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/ListCatalogItems/main.go b/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/ListCatalogItems/main.go index 9a8b83d35ff5..449c295a4a98 100644 --- a/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/ListCatalogItems/main.go +++ b/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/ListCatalogItems/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recommendationengine.NewCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.ListCatalogItemsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/UpdateCatalogItem/main.go b/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/UpdateCatalogItem/main.go index 412aef41f305..b2b91de6a703 100644 --- a/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/UpdateCatalogItem/main.go +++ b/internal/generated/snippets/recommendationengine/apiv1beta1/CatalogClient/UpdateCatalogItem/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.UpdateCatalogItemRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommendationengine/apiv1beta1/PredictionApiKeyRegistryClient/CreatePredictionApiKeyRegistration/main.go b/internal/generated/snippets/recommendationengine/apiv1beta1/PredictionApiKeyRegistryClient/CreatePredictionApiKeyRegistration/main.go index 4ba4b5e0eb3a..671515be99c4 100644 --- a/internal/generated/snippets/recommendationengine/apiv1beta1/PredictionApiKeyRegistryClient/CreatePredictionApiKeyRegistration/main.go +++ b/internal/generated/snippets/recommendationengine/apiv1beta1/PredictionApiKeyRegistryClient/CreatePredictionApiKeyRegistration/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewPredictionApiKeyRegistryClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.CreatePredictionApiKeyRegistrationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommendationengine/apiv1beta1/PredictionApiKeyRegistryClient/DeletePredictionApiKeyRegistration/main.go b/internal/generated/snippets/recommendationengine/apiv1beta1/PredictionApiKeyRegistryClient/DeletePredictionApiKeyRegistration/main.go index 37fc02e8720b..90e3127ec1fc 100644 --- a/internal/generated/snippets/recommendationengine/apiv1beta1/PredictionApiKeyRegistryClient/DeletePredictionApiKeyRegistration/main.go +++ b/internal/generated/snippets/recommendationengine/apiv1beta1/PredictionApiKeyRegistryClient/DeletePredictionApiKeyRegistration/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.DeletePredictionApiKeyRegistrationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommendationengine/apiv1beta1/PredictionApiKeyRegistryClient/ListPredictionApiKeyRegistrations/main.go b/internal/generated/snippets/recommendationengine/apiv1beta1/PredictionApiKeyRegistryClient/ListPredictionApiKeyRegistrations/main.go index 0ca7608c21a3..be90d7d30727 100644 --- a/internal/generated/snippets/recommendationengine/apiv1beta1/PredictionApiKeyRegistryClient/ListPredictionApiKeyRegistrations/main.go +++ b/internal/generated/snippets/recommendationengine/apiv1beta1/PredictionApiKeyRegistryClient/ListPredictionApiKeyRegistrations/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recommendationengine.NewPredictionApiKeyRegistryClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.ListPredictionApiKeyRegistrationsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommendationengine/apiv1beta1/PredictionClient/Predict/main.go b/internal/generated/snippets/recommendationengine/apiv1beta1/PredictionClient/Predict/main.go index c71c5ac217d0..3c9af84cf82d 100644 --- a/internal/generated/snippets/recommendationengine/apiv1beta1/PredictionClient/Predict/main.go +++ b/internal/generated/snippets/recommendationengine/apiv1beta1/PredictionClient/Predict/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recommendationengine.NewPredictionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.PredictRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/CollectUserEvent/main.go b/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/CollectUserEvent/main.go index a248f5ae9dd7..0ef569b0194a 100644 --- a/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/CollectUserEvent/main.go +++ b/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/CollectUserEvent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.CollectUserEventRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/ImportUserEvents/main.go b/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/ImportUserEvents/main.go index 63c57f2a8ef9..0efeebe67d07 100644 --- a/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/ImportUserEvents/main.go +++ b/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/ImportUserEvents/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.ImportUserEventsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/ListUserEvents/main.go b/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/ListUserEvents/main.go index a589e846468b..ddafe856b999 100644 --- a/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/ListUserEvents/main.go +++ b/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/ListUserEvents/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recommendationengine.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.ListUserEventsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/PurgeUserEvents/main.go b/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/PurgeUserEvents/main.go index f1441aceee58..ef26aae3e280 100644 --- a/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/PurgeUserEvents/main.go +++ b/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/PurgeUserEvents/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.PurgeUserEventsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/WriteUserEvent/main.go b/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/WriteUserEvent/main.go index f754e1bb98c6..d2f29e368058 100644 --- a/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/WriteUserEvent/main.go +++ b/internal/generated/snippets/recommendationengine/apiv1beta1/UserEventClient/WriteUserEvent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.WriteUserEventRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommender/apiv1/Client/GetInsight/main.go b/internal/generated/snippets/recommender/apiv1/Client/GetInsight/main.go index 5a20e350ecbd..889773f4fc28 100644 --- a/internal/generated/snippets/recommender/apiv1/Client/GetInsight/main.go +++ b/internal/generated/snippets/recommender/apiv1/Client/GetInsight/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.GetInsightRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommender/apiv1/Client/GetRecommendation/main.go b/internal/generated/snippets/recommender/apiv1/Client/GetRecommendation/main.go index 22ebe8e02809..c338f7a5fc10 100644 --- a/internal/generated/snippets/recommender/apiv1/Client/GetRecommendation/main.go +++ b/internal/generated/snippets/recommender/apiv1/Client/GetRecommendation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.GetRecommendationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommender/apiv1/Client/ListInsights/main.go b/internal/generated/snippets/recommender/apiv1/Client/ListInsights/main.go index d9faf410e123..e81a406cd3c6 100644 --- a/internal/generated/snippets/recommender/apiv1/Client/ListInsights/main.go +++ b/internal/generated/snippets/recommender/apiv1/Client/ListInsights/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.ListInsightsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommender/apiv1/Client/ListRecommendations/main.go b/internal/generated/snippets/recommender/apiv1/Client/ListRecommendations/main.go index d80a7f6a8d38..48fab8e6cb47 100644 --- a/internal/generated/snippets/recommender/apiv1/Client/ListRecommendations/main.go +++ b/internal/generated/snippets/recommender/apiv1/Client/ListRecommendations/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.ListRecommendationsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommender/apiv1/Client/MarkInsightAccepted/main.go b/internal/generated/snippets/recommender/apiv1/Client/MarkInsightAccepted/main.go index 380b1e324ec3..bd1219e4be27 100644 --- a/internal/generated/snippets/recommender/apiv1/Client/MarkInsightAccepted/main.go +++ b/internal/generated/snippets/recommender/apiv1/Client/MarkInsightAccepted/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.MarkInsightAcceptedRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommender/apiv1/Client/MarkRecommendationClaimed/main.go b/internal/generated/snippets/recommender/apiv1/Client/MarkRecommendationClaimed/main.go index 17893f6cf583..ac860e0bd67e 100644 --- a/internal/generated/snippets/recommender/apiv1/Client/MarkRecommendationClaimed/main.go +++ b/internal/generated/snippets/recommender/apiv1/Client/MarkRecommendationClaimed/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.MarkRecommendationClaimedRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommender/apiv1/Client/MarkRecommendationFailed/main.go b/internal/generated/snippets/recommender/apiv1/Client/MarkRecommendationFailed/main.go index a896284ddea5..7649f4ede9b6 100644 --- a/internal/generated/snippets/recommender/apiv1/Client/MarkRecommendationFailed/main.go +++ b/internal/generated/snippets/recommender/apiv1/Client/MarkRecommendationFailed/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.MarkRecommendationFailedRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommender/apiv1/Client/MarkRecommendationSucceeded/main.go b/internal/generated/snippets/recommender/apiv1/Client/MarkRecommendationSucceeded/main.go index 6301751690ac..58c9626db615 100644 --- a/internal/generated/snippets/recommender/apiv1/Client/MarkRecommendationSucceeded/main.go +++ b/internal/generated/snippets/recommender/apiv1/Client/MarkRecommendationSucceeded/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.MarkRecommendationSucceededRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommender/apiv1beta1/Client/GetInsight/main.go b/internal/generated/snippets/recommender/apiv1beta1/Client/GetInsight/main.go index e90c52b572c1..b2ec15637a53 100644 --- a/internal/generated/snippets/recommender/apiv1beta1/Client/GetInsight/main.go +++ b/internal/generated/snippets/recommender/apiv1beta1/Client/GetInsight/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.GetInsightRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommender/apiv1beta1/Client/GetRecommendation/main.go b/internal/generated/snippets/recommender/apiv1beta1/Client/GetRecommendation/main.go index 89d555360fed..36268af529c3 100644 --- a/internal/generated/snippets/recommender/apiv1beta1/Client/GetRecommendation/main.go +++ b/internal/generated/snippets/recommender/apiv1beta1/Client/GetRecommendation/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.GetRecommendationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommender/apiv1beta1/Client/ListInsights/main.go b/internal/generated/snippets/recommender/apiv1beta1/Client/ListInsights/main.go index 2f8a22ff1452..3f58865fcaa7 100644 --- a/internal/generated/snippets/recommender/apiv1beta1/Client/ListInsights/main.go +++ b/internal/generated/snippets/recommender/apiv1beta1/Client/ListInsights/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.ListInsightsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommender/apiv1beta1/Client/ListRecommendations/main.go b/internal/generated/snippets/recommender/apiv1beta1/Client/ListRecommendations/main.go index f1cdf8e64bf4..e99796f81778 100644 --- a/internal/generated/snippets/recommender/apiv1beta1/Client/ListRecommendations/main.go +++ b/internal/generated/snippets/recommender/apiv1beta1/Client/ListRecommendations/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.ListRecommendationsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommender/apiv1beta1/Client/MarkInsightAccepted/main.go b/internal/generated/snippets/recommender/apiv1beta1/Client/MarkInsightAccepted/main.go index 204e70882fba..3521062ab488 100644 --- a/internal/generated/snippets/recommender/apiv1beta1/Client/MarkInsightAccepted/main.go +++ b/internal/generated/snippets/recommender/apiv1beta1/Client/MarkInsightAccepted/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.MarkInsightAcceptedRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommender/apiv1beta1/Client/MarkRecommendationClaimed/main.go b/internal/generated/snippets/recommender/apiv1beta1/Client/MarkRecommendationClaimed/main.go index 33eab37f6009..b250789f61ae 100644 --- a/internal/generated/snippets/recommender/apiv1beta1/Client/MarkRecommendationClaimed/main.go +++ b/internal/generated/snippets/recommender/apiv1beta1/Client/MarkRecommendationClaimed/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.MarkRecommendationClaimedRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommender/apiv1beta1/Client/MarkRecommendationFailed/main.go b/internal/generated/snippets/recommender/apiv1beta1/Client/MarkRecommendationFailed/main.go index cd9bc7457782..276c6c5ad9f0 100644 --- a/internal/generated/snippets/recommender/apiv1beta1/Client/MarkRecommendationFailed/main.go +++ b/internal/generated/snippets/recommender/apiv1beta1/Client/MarkRecommendationFailed/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.MarkRecommendationFailedRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/recommender/apiv1beta1/Client/MarkRecommendationSucceeded/main.go b/internal/generated/snippets/recommender/apiv1beta1/Client/MarkRecommendationSucceeded/main.go index fcaa3bb6593a..75c295e770d5 100644 --- a/internal/generated/snippets/recommender/apiv1beta1/Client/MarkRecommendationSucceeded/main.go +++ b/internal/generated/snippets/recommender/apiv1beta1/Client/MarkRecommendationSucceeded/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.MarkRecommendationSucceededRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1/CloudRedisClient/CreateInstance/main.go b/internal/generated/snippets/redis/apiv1/CloudRedisClient/CreateInstance/main.go index 3a95be19879b..0dcbebfd1f74 100644 --- a/internal/generated/snippets/redis/apiv1/CloudRedisClient/CreateInstance/main.go +++ b/internal/generated/snippets/redis/apiv1/CloudRedisClient/CreateInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.CreateInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1/CloudRedisClient/DeleteInstance/main.go b/internal/generated/snippets/redis/apiv1/CloudRedisClient/DeleteInstance/main.go index 1fe6b7fdf83c..822620170fd6 100644 --- a/internal/generated/snippets/redis/apiv1/CloudRedisClient/DeleteInstance/main.go +++ b/internal/generated/snippets/redis/apiv1/CloudRedisClient/DeleteInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.DeleteInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1/CloudRedisClient/ExportInstance/main.go b/internal/generated/snippets/redis/apiv1/CloudRedisClient/ExportInstance/main.go index 7997a47278cc..daba23167392 100644 --- a/internal/generated/snippets/redis/apiv1/CloudRedisClient/ExportInstance/main.go +++ b/internal/generated/snippets/redis/apiv1/CloudRedisClient/ExportInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.ExportInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1/CloudRedisClient/FailoverInstance/main.go b/internal/generated/snippets/redis/apiv1/CloudRedisClient/FailoverInstance/main.go index 32b579857f2b..bc18a2fb9f44 100644 --- a/internal/generated/snippets/redis/apiv1/CloudRedisClient/FailoverInstance/main.go +++ b/internal/generated/snippets/redis/apiv1/CloudRedisClient/FailoverInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.FailoverInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1/CloudRedisClient/GetInstance/main.go b/internal/generated/snippets/redis/apiv1/CloudRedisClient/GetInstance/main.go index 7be4fef23094..dc4f36f57e54 100644 --- a/internal/generated/snippets/redis/apiv1/CloudRedisClient/GetInstance/main.go +++ b/internal/generated/snippets/redis/apiv1/CloudRedisClient/GetInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.GetInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1/CloudRedisClient/ImportInstance/main.go b/internal/generated/snippets/redis/apiv1/CloudRedisClient/ImportInstance/main.go index 99c48021b17c..615cf0a489eb 100644 --- a/internal/generated/snippets/redis/apiv1/CloudRedisClient/ImportInstance/main.go +++ b/internal/generated/snippets/redis/apiv1/CloudRedisClient/ImportInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.ImportInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1/CloudRedisClient/ListInstances/main.go b/internal/generated/snippets/redis/apiv1/CloudRedisClient/ListInstances/main.go index 0fd534f06b8b..74853443aafd 100644 --- a/internal/generated/snippets/redis/apiv1/CloudRedisClient/ListInstances/main.go +++ b/internal/generated/snippets/redis/apiv1/CloudRedisClient/ListInstances/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.ListInstancesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1/CloudRedisClient/UpdateInstance/main.go b/internal/generated/snippets/redis/apiv1/CloudRedisClient/UpdateInstance/main.go index ced7a3780c0b..72ebc4fb65ad 100644 --- a/internal/generated/snippets/redis/apiv1/CloudRedisClient/UpdateInstance/main.go +++ b/internal/generated/snippets/redis/apiv1/CloudRedisClient/UpdateInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.UpdateInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1/CloudRedisClient/UpgradeInstance/main.go b/internal/generated/snippets/redis/apiv1/CloudRedisClient/UpgradeInstance/main.go index fd8e21b6d681..cc704f16849a 100644 --- a/internal/generated/snippets/redis/apiv1/CloudRedisClient/UpgradeInstance/main.go +++ b/internal/generated/snippets/redis/apiv1/CloudRedisClient/UpgradeInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.UpgradeInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/CreateInstance/main.go b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/CreateInstance/main.go index 8ad244ef3ade..4ba443908b04 100644 --- a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/CreateInstance/main.go +++ b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/CreateInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.CreateInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/DeleteInstance/main.go b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/DeleteInstance/main.go index 7c230c1560d4..0fe519bca373 100644 --- a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/DeleteInstance/main.go +++ b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/DeleteInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.DeleteInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/ExportInstance/main.go b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/ExportInstance/main.go index 40f55ef6fc8a..3b7c38b0f67e 100644 --- a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/ExportInstance/main.go +++ b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/ExportInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.ExportInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/FailoverInstance/main.go b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/FailoverInstance/main.go index e43455ce9b2c..7fb4a2c66662 100644 --- a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/FailoverInstance/main.go +++ b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/FailoverInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.FailoverInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/GetInstance/main.go b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/GetInstance/main.go index 72fc95e33ace..00b44eb383b2 100644 --- a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/GetInstance/main.go +++ b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/GetInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.GetInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/ImportInstance/main.go b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/ImportInstance/main.go index e05e433b7135..97b9d2a865b5 100644 --- a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/ImportInstance/main.go +++ b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/ImportInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.ImportInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/ListInstances/main.go b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/ListInstances/main.go index fd1ec1bc7ffa..ccb9482b9776 100644 --- a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/ListInstances/main.go +++ b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/ListInstances/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.ListInstancesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/UpdateInstance/main.go b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/UpdateInstance/main.go index 603d351f1af3..02d47758c605 100644 --- a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/UpdateInstance/main.go +++ b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/UpdateInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.UpdateInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/UpgradeInstance/main.go b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/UpgradeInstance/main.go index 1f186caf54ea..f40f31d56661 100644 --- a/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/UpgradeInstance/main.go +++ b/internal/generated/snippets/redis/apiv1beta1/CloudRedisClient/UpgradeInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.UpgradeInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/CreateFolder/main.go b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/CreateFolder/main.go index 4be92a8f1fbc..319837c56c4f 100644 --- a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/CreateFolder/main.go +++ b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/CreateFolder/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v2" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcemanagerpb.CreateFolderRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/DeleteFolder/main.go b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/DeleteFolder/main.go index 7e16df0feb51..4c5fd26ba77e 100644 --- a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/DeleteFolder/main.go +++ b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/DeleteFolder/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v2" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcemanagerpb.DeleteFolderRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/GetFolder/main.go b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/GetFolder/main.go index 62d4a2dae7c9..4e2fea569136 100644 --- a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/GetFolder/main.go +++ b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/GetFolder/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v2" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcemanagerpb.GetFolderRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/GetIamPolicy/main.go b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/GetIamPolicy/main.go index dc283e8a84ce..de91b0632ea1 100644 --- a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/GetIamPolicy/main.go +++ b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/ListFolders/main.go b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/ListFolders/main.go index 096d8578e400..fcc69d10cea4 100644 --- a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/ListFolders/main.go +++ b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/ListFolders/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcemanagerpb.ListFoldersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/MoveFolder/main.go b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/MoveFolder/main.go index a85613b4a64d..7cd2ae9e8e5d 100644 --- a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/MoveFolder/main.go +++ b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/MoveFolder/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v2" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcemanagerpb.MoveFolderRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/SearchFolders/main.go b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/SearchFolders/main.go index 9bf103d4d4da..2fe798484699 100644 --- a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/SearchFolders/main.go +++ b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/SearchFolders/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcemanagerpb.SearchFoldersRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/SetIamPolicy/main.go b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/SetIamPolicy/main.go index de00cdda0f46..c191267f120b 100644 --- a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/SetIamPolicy/main.go +++ b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/TestIamPermissions/main.go b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/TestIamPermissions/main.go index 4adf0a04f4b5..10ae5d2e4715 100644 --- a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/TestIamPermissions/main.go +++ b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/UndeleteFolder/main.go b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/UndeleteFolder/main.go index 2ba2a0368c90..e7c65b5e1b1b 100644 --- a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/UndeleteFolder/main.go +++ b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/UndeleteFolder/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v2" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcemanagerpb.UndeleteFolderRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/UpdateFolder/main.go b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/UpdateFolder/main.go index b758cb33d064..a215aaac7536 100644 --- a/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/UpdateFolder/main.go +++ b/internal/generated/snippets/resourcemanager/apiv2/FoldersClient/UpdateFolder/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v2" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcemanagerpb.UpdateFolderRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/resourcesettings/apiv1/Client/GetSetting/main.go b/internal/generated/snippets/resourcesettings/apiv1/Client/GetSetting/main.go index fe357faebd4e..6568d0367f25 100644 --- a/internal/generated/snippets/resourcesettings/apiv1/Client/GetSetting/main.go +++ b/internal/generated/snippets/resourcesettings/apiv1/Client/GetSetting/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import resourcesettingspb "google.golang.org/genproto/googleapis/cloud/resourcesettings/v1" - ctx := context.Background() c, err := resourcesettings.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcesettingspb.GetSettingRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/resourcesettings/apiv1/Client/ListSettings/main.go b/internal/generated/snippets/resourcesettings/apiv1/Client/ListSettings/main.go index a04b2e02533f..27418f0b00be 100644 --- a/internal/generated/snippets/resourcesettings/apiv1/Client/ListSettings/main.go +++ b/internal/generated/snippets/resourcesettings/apiv1/Client/ListSettings/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import resourcesettingspb "google.golang.org/genproto/googleapis/cloud/resourcesettings/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := resourcesettings.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcesettingspb.ListSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/resourcesettings/apiv1/Client/UpdateSetting/main.go b/internal/generated/snippets/resourcesettings/apiv1/Client/UpdateSetting/main.go index b5fb971e6f5d..da8a33aa4bda 100644 --- a/internal/generated/snippets/resourcesettings/apiv1/Client/UpdateSetting/main.go +++ b/internal/generated/snippets/resourcesettings/apiv1/Client/UpdateSetting/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import resourcesettingspb "google.golang.org/genproto/googleapis/cloud/resourcesettings/v1" - ctx := context.Background() c, err := resourcesettings.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcesettingspb.UpdateSettingRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/retail/apiv2/CatalogClient/ListCatalogs/main.go b/internal/generated/snippets/retail/apiv2/CatalogClient/ListCatalogs/main.go index 681fa87d6d82..2d9a34f36a84 100644 --- a/internal/generated/snippets/retail/apiv2/CatalogClient/ListCatalogs/main.go +++ b/internal/generated/snippets/retail/apiv2/CatalogClient/ListCatalogs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := retail.NewCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.ListCatalogsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/retail/apiv2/CatalogClient/UpdateCatalog/main.go b/internal/generated/snippets/retail/apiv2/CatalogClient/UpdateCatalog/main.go index 41647143cf70..081e946b6a32 100644 --- a/internal/generated/snippets/retail/apiv2/CatalogClient/UpdateCatalog/main.go +++ b/internal/generated/snippets/retail/apiv2/CatalogClient/UpdateCatalog/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.UpdateCatalogRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/retail/apiv2/PredictionClient/Predict/main.go b/internal/generated/snippets/retail/apiv2/PredictionClient/Predict/main.go index 6e001673e25e..2b0fb9f04718 100644 --- a/internal/generated/snippets/retail/apiv2/PredictionClient/Predict/main.go +++ b/internal/generated/snippets/retail/apiv2/PredictionClient/Predict/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewPredictionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.PredictRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/retail/apiv2/ProductClient/CreateProduct/main.go b/internal/generated/snippets/retail/apiv2/ProductClient/CreateProduct/main.go index 4fba12dadc84..34d0c5f3cba8 100644 --- a/internal/generated/snippets/retail/apiv2/ProductClient/CreateProduct/main.go +++ b/internal/generated/snippets/retail/apiv2/ProductClient/CreateProduct/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewProductClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.CreateProductRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/retail/apiv2/ProductClient/DeleteProduct/main.go b/internal/generated/snippets/retail/apiv2/ProductClient/DeleteProduct/main.go index 7f6d3c0023bd..5a66e2f5cc66 100644 --- a/internal/generated/snippets/retail/apiv2/ProductClient/DeleteProduct/main.go +++ b/internal/generated/snippets/retail/apiv2/ProductClient/DeleteProduct/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.DeleteProductRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/retail/apiv2/ProductClient/GetProduct/main.go b/internal/generated/snippets/retail/apiv2/ProductClient/GetProduct/main.go index d39195501199..0b88fb2da490 100644 --- a/internal/generated/snippets/retail/apiv2/ProductClient/GetProduct/main.go +++ b/internal/generated/snippets/retail/apiv2/ProductClient/GetProduct/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewProductClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.GetProductRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/retail/apiv2/ProductClient/ImportProducts/main.go b/internal/generated/snippets/retail/apiv2/ProductClient/ImportProducts/main.go index a0fc7fa72870..f6ef521e17e5 100644 --- a/internal/generated/snippets/retail/apiv2/ProductClient/ImportProducts/main.go +++ b/internal/generated/snippets/retail/apiv2/ProductClient/ImportProducts/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewProductClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.ImportProductsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/retail/apiv2/ProductClient/UpdateProduct/main.go b/internal/generated/snippets/retail/apiv2/ProductClient/UpdateProduct/main.go index 73c03616f466..b2984800da4c 100644 --- a/internal/generated/snippets/retail/apiv2/ProductClient/UpdateProduct/main.go +++ b/internal/generated/snippets/retail/apiv2/ProductClient/UpdateProduct/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewProductClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.UpdateProductRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/retail/apiv2/UserEventClient/CollectUserEvent/main.go b/internal/generated/snippets/retail/apiv2/UserEventClient/CollectUserEvent/main.go index cf91388312c6..13bb504890cd 100644 --- a/internal/generated/snippets/retail/apiv2/UserEventClient/CollectUserEvent/main.go +++ b/internal/generated/snippets/retail/apiv2/UserEventClient/CollectUserEvent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.CollectUserEventRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/retail/apiv2/UserEventClient/ImportUserEvents/main.go b/internal/generated/snippets/retail/apiv2/UserEventClient/ImportUserEvents/main.go index 44d12c574f47..168056b66de3 100644 --- a/internal/generated/snippets/retail/apiv2/UserEventClient/ImportUserEvents/main.go +++ b/internal/generated/snippets/retail/apiv2/UserEventClient/ImportUserEvents/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.ImportUserEventsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/retail/apiv2/UserEventClient/PurgeUserEvents/main.go b/internal/generated/snippets/retail/apiv2/UserEventClient/PurgeUserEvents/main.go index 0198513d2119..17fde02fd9e6 100644 --- a/internal/generated/snippets/retail/apiv2/UserEventClient/PurgeUserEvents/main.go +++ b/internal/generated/snippets/retail/apiv2/UserEventClient/PurgeUserEvents/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.PurgeUserEventsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/retail/apiv2/UserEventClient/RejoinUserEvents/main.go b/internal/generated/snippets/retail/apiv2/UserEventClient/RejoinUserEvents/main.go index 634bede92308..3d0d732addfa 100644 --- a/internal/generated/snippets/retail/apiv2/UserEventClient/RejoinUserEvents/main.go +++ b/internal/generated/snippets/retail/apiv2/UserEventClient/RejoinUserEvents/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.RejoinUserEventsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/retail/apiv2/UserEventClient/WriteUserEvent/main.go b/internal/generated/snippets/retail/apiv2/UserEventClient/WriteUserEvent/main.go index 34c3744e429f..7514cc8f99c0 100644 --- a/internal/generated/snippets/retail/apiv2/UserEventClient/WriteUserEvent/main.go +++ b/internal/generated/snippets/retail/apiv2/UserEventClient/WriteUserEvent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.WriteUserEventRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/CreateJob/main.go b/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/CreateJob/main.go index 20354459491a..e7769f0b1772 100644 --- a/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/CreateJob/main.go +++ b/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/CreateJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.CreateJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/DeleteJob/main.go b/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/DeleteJob/main.go index 74c88200d108..c13581ddb360 100644 --- a/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/DeleteJob/main.go +++ b/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/DeleteJob/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.DeleteJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/GetJob/main.go b/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/GetJob/main.go index ce28400f7e36..fddc8b6dbcb4 100644 --- a/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/GetJob/main.go +++ b/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/GetJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.GetJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/ListJobs/main.go b/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/ListJobs/main.go index d66d7576c412..9b06297cf250 100644 --- a/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/ListJobs/main.go +++ b/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/ListJobs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.ListJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/PauseJob/main.go b/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/PauseJob/main.go index 448a3c42b2d0..222164cbb04b 100644 --- a/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/PauseJob/main.go +++ b/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/PauseJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.PauseJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/ResumeJob/main.go b/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/ResumeJob/main.go index e6e8888ef190..3f67c5ffdcd6 100644 --- a/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/ResumeJob/main.go +++ b/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/ResumeJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.ResumeJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/RunJob/main.go b/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/RunJob/main.go index 216d8b32ef07..4ccfa2a07256 100644 --- a/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/RunJob/main.go +++ b/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/RunJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.RunJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/UpdateJob/main.go b/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/UpdateJob/main.go index b745a0b4ae8d..2c3074048a35 100644 --- a/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/UpdateJob/main.go +++ b/internal/generated/snippets/scheduler/apiv1/CloudSchedulerClient/UpdateJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.UpdateJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/CreateJob/main.go b/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/CreateJob/main.go index b7eb5a502248..672126066d1d 100644 --- a/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/CreateJob/main.go +++ b/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/CreateJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1beta1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.CreateJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/DeleteJob/main.go b/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/DeleteJob/main.go index 7838477169ca..322b12fcbe77 100644 --- a/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/DeleteJob/main.go +++ b/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/DeleteJob/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.DeleteJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/GetJob/main.go b/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/GetJob/main.go index f875ad976dec..dd4c8a1edbd3 100644 --- a/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/GetJob/main.go +++ b/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/GetJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1beta1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.GetJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/ListJobs/main.go b/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/ListJobs/main.go index b846661efb0b..28dc45a95fd7 100644 --- a/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/ListJobs/main.go +++ b/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/ListJobs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.ListJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/PauseJob/main.go b/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/PauseJob/main.go index e561d78065d8..932b21c2e643 100644 --- a/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/PauseJob/main.go +++ b/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/PauseJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1beta1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.PauseJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/ResumeJob/main.go b/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/ResumeJob/main.go index 79f450f5cf4f..9e69e481162e 100644 --- a/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/ResumeJob/main.go +++ b/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/ResumeJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1beta1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.ResumeJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/RunJob/main.go b/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/RunJob/main.go index 01ce06237555..bd9216dd4155 100644 --- a/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/RunJob/main.go +++ b/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/RunJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1beta1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.RunJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/UpdateJob/main.go b/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/UpdateJob/main.go index 5d34e186b076..87d6c0bd934e 100644 --- a/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/UpdateJob/main.go +++ b/internal/generated/snippets/scheduler/apiv1beta1/CloudSchedulerClient/UpdateJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1beta1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.UpdateJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1/Client/AccessSecretVersion/main.go b/internal/generated/snippets/secretmanager/apiv1/Client/AccessSecretVersion/main.go index 54034a92f47b..76b846e1a0f5 100644 --- a/internal/generated/snippets/secretmanager/apiv1/Client/AccessSecretVersion/main.go +++ b/internal/generated/snippets/secretmanager/apiv1/Client/AccessSecretVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.AccessSecretVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1/Client/AddSecretVersion/main.go b/internal/generated/snippets/secretmanager/apiv1/Client/AddSecretVersion/main.go index fc4663a7dfac..170506bf09f2 100644 --- a/internal/generated/snippets/secretmanager/apiv1/Client/AddSecretVersion/main.go +++ b/internal/generated/snippets/secretmanager/apiv1/Client/AddSecretVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.AddSecretVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1/Client/CreateSecret/main.go b/internal/generated/snippets/secretmanager/apiv1/Client/CreateSecret/main.go index 8524ca551b79..a0082d50e1bf 100644 --- a/internal/generated/snippets/secretmanager/apiv1/Client/CreateSecret/main.go +++ b/internal/generated/snippets/secretmanager/apiv1/Client/CreateSecret/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.CreateSecretRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1/Client/DeleteSecret/main.go b/internal/generated/snippets/secretmanager/apiv1/Client/DeleteSecret/main.go index b775054f1866..84d9ad387e53 100644 --- a/internal/generated/snippets/secretmanager/apiv1/Client/DeleteSecret/main.go +++ b/internal/generated/snippets/secretmanager/apiv1/Client/DeleteSecret/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.DeleteSecretRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1/Client/DestroySecretVersion/main.go b/internal/generated/snippets/secretmanager/apiv1/Client/DestroySecretVersion/main.go index 4dc95bc612e7..b4c9731a1e15 100644 --- a/internal/generated/snippets/secretmanager/apiv1/Client/DestroySecretVersion/main.go +++ b/internal/generated/snippets/secretmanager/apiv1/Client/DestroySecretVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.DestroySecretVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1/Client/DisableSecretVersion/main.go b/internal/generated/snippets/secretmanager/apiv1/Client/DisableSecretVersion/main.go index c4308ffe205e..0e0478883097 100644 --- a/internal/generated/snippets/secretmanager/apiv1/Client/DisableSecretVersion/main.go +++ b/internal/generated/snippets/secretmanager/apiv1/Client/DisableSecretVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.DisableSecretVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1/Client/EnableSecretVersion/main.go b/internal/generated/snippets/secretmanager/apiv1/Client/EnableSecretVersion/main.go index 29cb3fd83919..c5a272838a44 100644 --- a/internal/generated/snippets/secretmanager/apiv1/Client/EnableSecretVersion/main.go +++ b/internal/generated/snippets/secretmanager/apiv1/Client/EnableSecretVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.EnableSecretVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1/Client/GetIamPolicy/main.go b/internal/generated/snippets/secretmanager/apiv1/Client/GetIamPolicy/main.go index d65ef605cedc..7288e51ac1e6 100644 --- a/internal/generated/snippets/secretmanager/apiv1/Client/GetIamPolicy/main.go +++ b/internal/generated/snippets/secretmanager/apiv1/Client/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1/Client/GetSecret/main.go b/internal/generated/snippets/secretmanager/apiv1/Client/GetSecret/main.go index a6b5d024d0f8..d3c1bf98aa7a 100644 --- a/internal/generated/snippets/secretmanager/apiv1/Client/GetSecret/main.go +++ b/internal/generated/snippets/secretmanager/apiv1/Client/GetSecret/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.GetSecretRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1/Client/GetSecretVersion/main.go b/internal/generated/snippets/secretmanager/apiv1/Client/GetSecretVersion/main.go index 8961a67986f9..78b2ff83202b 100644 --- a/internal/generated/snippets/secretmanager/apiv1/Client/GetSecretVersion/main.go +++ b/internal/generated/snippets/secretmanager/apiv1/Client/GetSecretVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.GetSecretVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1/Client/ListSecretVersions/main.go b/internal/generated/snippets/secretmanager/apiv1/Client/ListSecretVersions/main.go index 10dd589cce7c..2eba4f52abe7 100644 --- a/internal/generated/snippets/secretmanager/apiv1/Client/ListSecretVersions/main.go +++ b/internal/generated/snippets/secretmanager/apiv1/Client/ListSecretVersions/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.ListSecretVersionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1/Client/ListSecrets/main.go b/internal/generated/snippets/secretmanager/apiv1/Client/ListSecrets/main.go index a079dd58af1e..dc04c15bd0f4 100644 --- a/internal/generated/snippets/secretmanager/apiv1/Client/ListSecrets/main.go +++ b/internal/generated/snippets/secretmanager/apiv1/Client/ListSecrets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.ListSecretsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1/Client/SetIamPolicy/main.go b/internal/generated/snippets/secretmanager/apiv1/Client/SetIamPolicy/main.go index ebcc22912a02..e8a06cafc355 100644 --- a/internal/generated/snippets/secretmanager/apiv1/Client/SetIamPolicy/main.go +++ b/internal/generated/snippets/secretmanager/apiv1/Client/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1/Client/TestIamPermissions/main.go b/internal/generated/snippets/secretmanager/apiv1/Client/TestIamPermissions/main.go index a8491ad5dfba..b9883fa69491 100644 --- a/internal/generated/snippets/secretmanager/apiv1/Client/TestIamPermissions/main.go +++ b/internal/generated/snippets/secretmanager/apiv1/Client/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1/Client/UpdateSecret/main.go b/internal/generated/snippets/secretmanager/apiv1/Client/UpdateSecret/main.go index 79b279674948..46a8c2b40bb1 100644 --- a/internal/generated/snippets/secretmanager/apiv1/Client/UpdateSecret/main.go +++ b/internal/generated/snippets/secretmanager/apiv1/Client/UpdateSecret/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.UpdateSecretRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1beta1/Client/AccessSecretVersion/main.go b/internal/generated/snippets/secretmanager/apiv1beta1/Client/AccessSecretVersion/main.go index e7be66f319ea..88ab2a29c798 100644 --- a/internal/generated/snippets/secretmanager/apiv1beta1/Client/AccessSecretVersion/main.go +++ b/internal/generated/snippets/secretmanager/apiv1beta1/Client/AccessSecretVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.AccessSecretVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1beta1/Client/AddSecretVersion/main.go b/internal/generated/snippets/secretmanager/apiv1beta1/Client/AddSecretVersion/main.go index 7a9e8fe0e46c..c4d36934c841 100644 --- a/internal/generated/snippets/secretmanager/apiv1beta1/Client/AddSecretVersion/main.go +++ b/internal/generated/snippets/secretmanager/apiv1beta1/Client/AddSecretVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.AddSecretVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1beta1/Client/CreateSecret/main.go b/internal/generated/snippets/secretmanager/apiv1beta1/Client/CreateSecret/main.go index fa4549e5a975..227697729cfc 100644 --- a/internal/generated/snippets/secretmanager/apiv1beta1/Client/CreateSecret/main.go +++ b/internal/generated/snippets/secretmanager/apiv1beta1/Client/CreateSecret/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.CreateSecretRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1beta1/Client/DeleteSecret/main.go b/internal/generated/snippets/secretmanager/apiv1beta1/Client/DeleteSecret/main.go index 56a42cda3d93..ed06dde85499 100644 --- a/internal/generated/snippets/secretmanager/apiv1beta1/Client/DeleteSecret/main.go +++ b/internal/generated/snippets/secretmanager/apiv1beta1/Client/DeleteSecret/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.DeleteSecretRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1beta1/Client/DestroySecretVersion/main.go b/internal/generated/snippets/secretmanager/apiv1beta1/Client/DestroySecretVersion/main.go index 3f3f5dd19294..44ec8dad7fd7 100644 --- a/internal/generated/snippets/secretmanager/apiv1beta1/Client/DestroySecretVersion/main.go +++ b/internal/generated/snippets/secretmanager/apiv1beta1/Client/DestroySecretVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.DestroySecretVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1beta1/Client/DisableSecretVersion/main.go b/internal/generated/snippets/secretmanager/apiv1beta1/Client/DisableSecretVersion/main.go index 006c351b760e..496fad0802a9 100644 --- a/internal/generated/snippets/secretmanager/apiv1beta1/Client/DisableSecretVersion/main.go +++ b/internal/generated/snippets/secretmanager/apiv1beta1/Client/DisableSecretVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.DisableSecretVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1beta1/Client/EnableSecretVersion/main.go b/internal/generated/snippets/secretmanager/apiv1beta1/Client/EnableSecretVersion/main.go index f2234852125c..b8f3bb117130 100644 --- a/internal/generated/snippets/secretmanager/apiv1beta1/Client/EnableSecretVersion/main.go +++ b/internal/generated/snippets/secretmanager/apiv1beta1/Client/EnableSecretVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.EnableSecretVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1beta1/Client/GetIamPolicy/main.go b/internal/generated/snippets/secretmanager/apiv1beta1/Client/GetIamPolicy/main.go index 2426ce50411d..545ab47212cd 100644 --- a/internal/generated/snippets/secretmanager/apiv1beta1/Client/GetIamPolicy/main.go +++ b/internal/generated/snippets/secretmanager/apiv1beta1/Client/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1beta1/Client/GetSecret/main.go b/internal/generated/snippets/secretmanager/apiv1beta1/Client/GetSecret/main.go index 905c045e09f5..5cf796c2d6b5 100644 --- a/internal/generated/snippets/secretmanager/apiv1beta1/Client/GetSecret/main.go +++ b/internal/generated/snippets/secretmanager/apiv1beta1/Client/GetSecret/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.GetSecretRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1beta1/Client/GetSecretVersion/main.go b/internal/generated/snippets/secretmanager/apiv1beta1/Client/GetSecretVersion/main.go index 244c088a638c..c11342029072 100644 --- a/internal/generated/snippets/secretmanager/apiv1beta1/Client/GetSecretVersion/main.go +++ b/internal/generated/snippets/secretmanager/apiv1beta1/Client/GetSecretVersion/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.GetSecretVersionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1beta1/Client/ListSecretVersions/main.go b/internal/generated/snippets/secretmanager/apiv1beta1/Client/ListSecretVersions/main.go index 198cbe131b93..ab8b459a0ae9 100644 --- a/internal/generated/snippets/secretmanager/apiv1beta1/Client/ListSecretVersions/main.go +++ b/internal/generated/snippets/secretmanager/apiv1beta1/Client/ListSecretVersions/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.ListSecretVersionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1beta1/Client/ListSecrets/main.go b/internal/generated/snippets/secretmanager/apiv1beta1/Client/ListSecrets/main.go index d230550fa393..7b3ac6b49f73 100644 --- a/internal/generated/snippets/secretmanager/apiv1beta1/Client/ListSecrets/main.go +++ b/internal/generated/snippets/secretmanager/apiv1beta1/Client/ListSecrets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.ListSecretsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1beta1/Client/SetIamPolicy/main.go b/internal/generated/snippets/secretmanager/apiv1beta1/Client/SetIamPolicy/main.go index d25e626d52e2..39cfcbfb28d1 100644 --- a/internal/generated/snippets/secretmanager/apiv1beta1/Client/SetIamPolicy/main.go +++ b/internal/generated/snippets/secretmanager/apiv1beta1/Client/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1beta1/Client/TestIamPermissions/main.go b/internal/generated/snippets/secretmanager/apiv1beta1/Client/TestIamPermissions/main.go index 66e101322bfa..60b8b616d287 100644 --- a/internal/generated/snippets/secretmanager/apiv1beta1/Client/TestIamPermissions/main.go +++ b/internal/generated/snippets/secretmanager/apiv1beta1/Client/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/secretmanager/apiv1beta1/Client/UpdateSecret/main.go b/internal/generated/snippets/secretmanager/apiv1beta1/Client/UpdateSecret/main.go index 07d367f48d39..3344b60d7ea0 100644 --- a/internal/generated/snippets/secretmanager/apiv1beta1/Client/UpdateSecret/main.go +++ b/internal/generated/snippets/secretmanager/apiv1beta1/Client/UpdateSecret/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.UpdateSecretRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ActivateCertificateAuthority/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ActivateCertificateAuthority/main.go index e933455565ac..7b7f9be7934a 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ActivateCertificateAuthority/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ActivateCertificateAuthority/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ActivateCertificateAuthorityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/CreateCaPool/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/CreateCaPool/main.go index 977b0bf20b3b..48ad65274547 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/CreateCaPool/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/CreateCaPool/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.CreateCaPoolRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/CreateCertificate/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/CreateCertificate/main.go index bacd07f56716..793269a6388f 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/CreateCertificate/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/CreateCertificate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.CreateCertificateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/CreateCertificateAuthority/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/CreateCertificateAuthority/main.go index c092dbc3048e..703d61d61bff 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/CreateCertificateAuthority/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/CreateCertificateAuthority/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.CreateCertificateAuthorityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/CreateCertificateTemplate/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/CreateCertificateTemplate/main.go index 106986df4c70..7c8ab77951bf 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/CreateCertificateTemplate/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/CreateCertificateTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.CreateCertificateTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/DeleteCaPool/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/DeleteCaPool/main.go index 5d74e2469cf6..55d75015d71d 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/DeleteCaPool/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/DeleteCaPool/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.DeleteCaPoolRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/DeleteCertificateAuthority/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/DeleteCertificateAuthority/main.go index ddca50741548..bfbefa2235a8 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/DeleteCertificateAuthority/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/DeleteCertificateAuthority/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.DeleteCertificateAuthorityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/DeleteCertificateTemplate/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/DeleteCertificateTemplate/main.go index add107af9061..ce2839b1ebf5 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/DeleteCertificateTemplate/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/DeleteCertificateTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.DeleteCertificateTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/DisableCertificateAuthority/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/DisableCertificateAuthority/main.go index 8ea45c37d6a7..596a3d071b02 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/DisableCertificateAuthority/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/DisableCertificateAuthority/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.DisableCertificateAuthorityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/EnableCertificateAuthority/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/EnableCertificateAuthority/main.go index ba3efb01cb6c..dfdcd47ef2e7 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/EnableCertificateAuthority/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/EnableCertificateAuthority/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.EnableCertificateAuthorityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/FetchCaCerts/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/FetchCaCerts/main.go index 17c399025815..b6891b233501 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/FetchCaCerts/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/FetchCaCerts/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.FetchCaCertsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/FetchCertificateAuthorityCsr/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/FetchCertificateAuthorityCsr/main.go index 89e47665b042..63644208755f 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/FetchCertificateAuthorityCsr/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/FetchCertificateAuthorityCsr/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.FetchCertificateAuthorityCsrRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCaPool/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCaPool/main.go index ed64e941235d..e088efd766b0 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCaPool/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCaPool/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetCaPoolRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCertificate/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCertificate/main.go index f1238cfdcb7d..f7edf218c8d0 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCertificate/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCertificate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetCertificateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCertificateAuthority/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCertificateAuthority/main.go index c294d43b5e9b..17c8fe80e386 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCertificateAuthority/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCertificateAuthority/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetCertificateAuthorityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCertificateRevocationList/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCertificateRevocationList/main.go index 90159f6247dd..b4fe56cb5f32 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCertificateRevocationList/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCertificateRevocationList/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetCertificateRevocationListRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCertificateTemplate/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCertificateTemplate/main.go index 0592d0781f6d..24e3948a2ce4 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCertificateTemplate/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/GetCertificateTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetCertificateTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCaPools/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCaPools/main.go index 77008625450f..e768f7c0da74 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCaPools/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCaPools/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListCaPoolsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCertificateAuthorities/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCertificateAuthorities/main.go index 44d119978e5d..175ff82356ce 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCertificateAuthorities/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCertificateAuthorities/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListCertificateAuthoritiesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCertificateRevocationLists/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCertificateRevocationLists/main.go index f6823c0d9519..1a6694164eb7 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCertificateRevocationLists/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCertificateRevocationLists/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListCertificateRevocationListsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCertificateTemplates/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCertificateTemplates/main.go index 5b6087d77e9c..98c2bdb65552 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCertificateTemplates/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCertificateTemplates/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListCertificateTemplatesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCertificates/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCertificates/main.go index d1abbf60bd65..e2e22a9792fb 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCertificates/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/ListCertificates/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListCertificatesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/RevokeCertificate/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/RevokeCertificate/main.go index 7fc634d28c14..bcc8212b6c32 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/RevokeCertificate/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/RevokeCertificate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.RevokeCertificateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UndeleteCertificateAuthority/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UndeleteCertificateAuthority/main.go index 52b30beed5ce..a26e1812a026 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UndeleteCertificateAuthority/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UndeleteCertificateAuthority/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UndeleteCertificateAuthorityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCaPool/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCaPool/main.go index 7a9653e514b8..998a73b9c8b3 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCaPool/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCaPool/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UpdateCaPoolRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCertificate/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCertificate/main.go index 09c5073c26db..7ee014917fc9 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCertificate/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCertificate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UpdateCertificateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCertificateAuthority/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCertificateAuthority/main.go index 0ccce3c463da..da20ea99c0ec 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCertificateAuthority/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCertificateAuthority/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UpdateCertificateAuthorityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCertificateRevocationList/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCertificateRevocationList/main.go index 527b8f4162a1..54320c3099c9 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCertificateRevocationList/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCertificateRevocationList/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UpdateCertificateRevocationListRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCertificateTemplate/main.go b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCertificateTemplate/main.go index e46d50e83721..53761e6e677f 100644 --- a/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCertificateTemplate/main.go +++ b/internal/generated/snippets/security/privateca/apiv1/CertificateAuthorityClient/UpdateCertificateTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UpdateCertificateTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ActivateCertificateAuthority/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ActivateCertificateAuthority/main.go index e69ca3fb9949..53610affbf7a 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ActivateCertificateAuthority/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ActivateCertificateAuthority/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ActivateCertificateAuthorityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/CreateCertificate/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/CreateCertificate/main.go index 0d6d4486e959..6a4d20012e34 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/CreateCertificate/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/CreateCertificate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.CreateCertificateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/CreateCertificateAuthority/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/CreateCertificateAuthority/main.go index ab5af6c755f9..d5028f47b7c4 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/CreateCertificateAuthority/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/CreateCertificateAuthority/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.CreateCertificateAuthorityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/DisableCertificateAuthority/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/DisableCertificateAuthority/main.go index b243384345d8..79da8fa92fa0 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/DisableCertificateAuthority/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/DisableCertificateAuthority/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.DisableCertificateAuthorityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/EnableCertificateAuthority/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/EnableCertificateAuthority/main.go index 03b18c31b642..df39bf92ea22 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/EnableCertificateAuthority/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/EnableCertificateAuthority/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.EnableCertificateAuthorityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/FetchCertificateAuthorityCsr/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/FetchCertificateAuthorityCsr/main.go index d80dffbc0575..699301a60550 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/FetchCertificateAuthorityCsr/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/FetchCertificateAuthorityCsr/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.FetchCertificateAuthorityCsrRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/GetCertificate/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/GetCertificate/main.go index 334fc0415889..d3f19a67eff8 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/GetCertificate/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/GetCertificate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetCertificateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/GetCertificateAuthority/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/GetCertificateAuthority/main.go index c9f65e5029f8..3df4de0ca1db 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/GetCertificateAuthority/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/GetCertificateAuthority/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetCertificateAuthorityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/GetCertificateRevocationList/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/GetCertificateRevocationList/main.go index 98646239b058..68368bb5a60e 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/GetCertificateRevocationList/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/GetCertificateRevocationList/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetCertificateRevocationListRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/GetReusableConfig/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/GetReusableConfig/main.go index fdad71bcf2af..50493b9c3d3b 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/GetReusableConfig/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/GetReusableConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetReusableConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ListCertificateAuthorities/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ListCertificateAuthorities/main.go index 25d5a4458fad..aba53447ef9a 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ListCertificateAuthorities/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ListCertificateAuthorities/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListCertificateAuthoritiesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ListCertificateRevocationLists/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ListCertificateRevocationLists/main.go index f20098568605..7011b57eeff7 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ListCertificateRevocationLists/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ListCertificateRevocationLists/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListCertificateRevocationListsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ListCertificates/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ListCertificates/main.go index 62237e1a2da6..e7e8f2e4d5fd 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ListCertificates/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ListCertificates/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListCertificatesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ListReusableConfigs/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ListReusableConfigs/main.go index 1c86fb17993d..e4172ba833ac 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ListReusableConfigs/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ListReusableConfigs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListReusableConfigsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/RestoreCertificateAuthority/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/RestoreCertificateAuthority/main.go index 58f5ac655f7b..0956abf51567 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/RestoreCertificateAuthority/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/RestoreCertificateAuthority/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.RestoreCertificateAuthorityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/RevokeCertificate/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/RevokeCertificate/main.go index cf150c548644..809416b33bab 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/RevokeCertificate/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/RevokeCertificate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.RevokeCertificateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ScheduleDeleteCertificateAuthority/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ScheduleDeleteCertificateAuthority/main.go index 65a18601669d..5013f6b8859a 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ScheduleDeleteCertificateAuthority/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/ScheduleDeleteCertificateAuthority/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ScheduleDeleteCertificateAuthorityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/UpdateCertificate/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/UpdateCertificate/main.go index 0735d63039ee..84f5c287867c 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/UpdateCertificate/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/UpdateCertificate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UpdateCertificateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/UpdateCertificateAuthority/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/UpdateCertificateAuthority/main.go index dafe825ffbc6..ec84193d1a1e 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/UpdateCertificateAuthority/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/UpdateCertificateAuthority/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UpdateCertificateAuthorityRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/UpdateCertificateRevocationList/main.go b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/UpdateCertificateRevocationList/main.go index 529b5c892671..044ffe38a60f 100644 --- a/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/UpdateCertificateRevocationList/main.go +++ b/internal/generated/snippets/security/privateca/apiv1beta1/CertificateAuthorityClient/UpdateCertificateRevocationList/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UpdateCertificateRevocationListRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/CreateFinding/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/CreateFinding/main.go index edbdd5ab6cb2..75b60b2b6bcf 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/CreateFinding/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/CreateFinding/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.CreateFindingRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/CreateNotificationConfig/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/CreateNotificationConfig/main.go index 2a7e6e7edfa6..16ec192f7cea 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/CreateNotificationConfig/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/CreateNotificationConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.CreateNotificationConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/CreateSource/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/CreateSource/main.go index 77f45afe4b08..bf5462229915 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/CreateSource/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/CreateSource/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.CreateSourceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/DeleteNotificationConfig/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/DeleteNotificationConfig/main.go index 43db64059d88..58d3c38e8c81 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/DeleteNotificationConfig/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/DeleteNotificationConfig/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.DeleteNotificationConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/GetIamPolicy/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/GetIamPolicy/main.go index 4dc75a29f909..fae18e7fddb8 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/GetIamPolicy/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/GetNotificationConfig/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/GetNotificationConfig/main.go index 8636f5d1698e..97a73d02d0af 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/GetNotificationConfig/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/GetNotificationConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GetNotificationConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/GetOrganizationSettings/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/GetOrganizationSettings/main.go index a133e67005c9..4a3790ce8091 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/GetOrganizationSettings/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/GetOrganizationSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GetOrganizationSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/GetSource/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/GetSource/main.go index b6b31a6e0273..5fc86f03dfa8 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/GetSource/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/GetSource/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GetSourceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/GroupAssets/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/GroupAssets/main.go index 50e63faaf05a..1b0a7a99734f 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/GroupAssets/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/GroupAssets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GroupAssetsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/GroupFindings/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/GroupFindings/main.go index 8842943c6fd3..19f99f2e9e94 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/GroupFindings/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/GroupFindings/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GroupFindingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/ListAssets/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/ListAssets/main.go index 14a226dc9052..7ccb2e99265b 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/ListAssets/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/ListAssets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListAssetsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/ListFindings/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/ListFindings/main.go index 21e0b5c13af0..9237cb762dec 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/ListFindings/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/ListFindings/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListFindingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/ListNotificationConfigs/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/ListNotificationConfigs/main.go index e3b5924ac8ca..ae6bc52789dc 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/ListNotificationConfigs/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/ListNotificationConfigs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListNotificationConfigsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/ListSources/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/ListSources/main.go index 7bb785123b6f..51911697747b 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/ListSources/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/ListSources/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListSourcesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/RunAssetDiscovery/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/RunAssetDiscovery/main.go index 5e0cb4050084..ec35c1f757ed 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/RunAssetDiscovery/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/RunAssetDiscovery/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.RunAssetDiscoveryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/SetFindingState/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/SetFindingState/main.go index 9f2e2d2425b9..9e0832622152 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/SetFindingState/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/SetFindingState/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.SetFindingStateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/SetIamPolicy/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/SetIamPolicy/main.go index c4008b1833d9..414898c13f98 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/SetIamPolicy/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/TestIamPermissions/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/TestIamPermissions/main.go index 8baf71d4374d..8e28042c3b72 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/TestIamPermissions/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/UpdateFinding/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/UpdateFinding/main.go index c9b45e8caf6b..2ed26bacb222 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/UpdateFinding/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/UpdateFinding/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateFindingRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/UpdateNotificationConfig/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/UpdateNotificationConfig/main.go index 4e6dbffac49e..71942016f234 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/UpdateNotificationConfig/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/UpdateNotificationConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateNotificationConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/UpdateOrganizationSettings/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/UpdateOrganizationSettings/main.go index db855aea75ac..e5d76f7ed2ba 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/UpdateOrganizationSettings/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/UpdateOrganizationSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateOrganizationSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/UpdateSecurityMarks/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/UpdateSecurityMarks/main.go index b5c5e6851415..f150f25ce5fb 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/UpdateSecurityMarks/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/UpdateSecurityMarks/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateSecurityMarksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1/Client/UpdateSource/main.go b/internal/generated/snippets/securitycenter/apiv1/Client/UpdateSource/main.go index 3efc3223e88a..f25908cfdb88 100644 --- a/internal/generated/snippets/securitycenter/apiv1/Client/UpdateSource/main.go +++ b/internal/generated/snippets/securitycenter/apiv1/Client/UpdateSource/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateSourceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/CreateFinding/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/CreateFinding/main.go index 2d0e2bb400c9..bfea19c6febd 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/CreateFinding/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/CreateFinding/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.CreateFindingRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/CreateSource/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/CreateSource/main.go index c2738b402142..52359559719a 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/CreateSource/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/CreateSource/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.CreateSourceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/GetIamPolicy/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/GetIamPolicy/main.go index 760fba21ce31..af929e51e15b 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/GetIamPolicy/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/GetOrganizationSettings/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/GetOrganizationSettings/main.go index 430ae4b323cd..cbf03a5d4d46 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/GetOrganizationSettings/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/GetOrganizationSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GetOrganizationSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/GetSource/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/GetSource/main.go index bd73eec7066c..3b0226fc61a8 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/GetSource/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/GetSource/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GetSourceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/GroupAssets/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/GroupAssets/main.go index 76ef441cac00..317ff9b22701 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/GroupAssets/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/GroupAssets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GroupAssetsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/GroupFindings/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/GroupFindings/main.go index 01cab2b216af..ee62dcc04e4e 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/GroupFindings/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/GroupFindings/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GroupFindingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/ListAssets/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/ListAssets/main.go index 0d3aac1884e4..3283e0dee92b 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/ListAssets/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/ListAssets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListAssetsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/ListFindings/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/ListFindings/main.go index cd09aef3373d..bca59742c17b 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/ListFindings/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/ListFindings/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListFindingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/ListSources/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/ListSources/main.go index 52b42eb22f38..8fbb816b306c 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/ListSources/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/ListSources/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListSourcesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/RunAssetDiscovery/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/RunAssetDiscovery/main.go index 2fe80f8d4c51..2fb12b24b6f3 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/RunAssetDiscovery/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/RunAssetDiscovery/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.RunAssetDiscoveryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/SetFindingState/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/SetFindingState/main.go index 6e53d201048d..676082d27c44 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/SetFindingState/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/SetFindingState/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.SetFindingStateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/SetIamPolicy/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/SetIamPolicy/main.go index 2b9c2e163ac8..3eca3467cadf 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/SetIamPolicy/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/TestIamPermissions/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/TestIamPermissions/main.go index e1daebfddfdb..40857544545e 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/TestIamPermissions/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/UpdateFinding/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/UpdateFinding/main.go index 2ad5505c6d9c..abc3924285d0 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/UpdateFinding/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/UpdateFinding/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateFindingRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/UpdateOrganizationSettings/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/UpdateOrganizationSettings/main.go index 52212e95a6e5..a5805f39b497 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/UpdateOrganizationSettings/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/UpdateOrganizationSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateOrganizationSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/UpdateSecurityMarks/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/UpdateSecurityMarks/main.go index d2726fa7abda..92a5470fb438 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/UpdateSecurityMarks/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/UpdateSecurityMarks/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateSecurityMarksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1beta1/Client/UpdateSource/main.go b/internal/generated/snippets/securitycenter/apiv1beta1/Client/UpdateSource/main.go index 1ca7eea50b78..532b66e0b5bf 100644 --- a/internal/generated/snippets/securitycenter/apiv1beta1/Client/UpdateSource/main.go +++ b/internal/generated/snippets/securitycenter/apiv1beta1/Client/UpdateSource/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateSourceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/CreateFinding/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/CreateFinding/main.go index bca4a3b89c32..64d99c7cb712 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/CreateFinding/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/CreateFinding/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.CreateFindingRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/CreateNotificationConfig/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/CreateNotificationConfig/main.go index bd5708ef37f8..8e071210494d 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/CreateNotificationConfig/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/CreateNotificationConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.CreateNotificationConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/CreateSource/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/CreateSource/main.go index 4d2f578172a9..51c8e976639e 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/CreateSource/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/CreateSource/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.CreateSourceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/DeleteNotificationConfig/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/DeleteNotificationConfig/main.go index f9c35ace0b83..22b1522cb982 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/DeleteNotificationConfig/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/DeleteNotificationConfig/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.DeleteNotificationConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GetIamPolicy/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GetIamPolicy/main.go index 80e7c421d967..70fd8e42c75e 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GetIamPolicy/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GetNotificationConfig/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GetNotificationConfig/main.go index 6ad369fa6e24..f1f60706bc78 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GetNotificationConfig/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GetNotificationConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GetNotificationConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GetOrganizationSettings/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GetOrganizationSettings/main.go index aad6a4f36ce5..aa93a19c9321 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GetOrganizationSettings/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GetOrganizationSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GetOrganizationSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GetSource/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GetSource/main.go index 5fdad56ce15c..86ceef4cb2a4 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GetSource/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GetSource/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GetSourceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GroupAssets/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GroupAssets/main.go index 0d6230f7464e..629889850fb8 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GroupAssets/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GroupAssets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GroupAssetsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GroupFindings/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GroupFindings/main.go index a731ff40d874..d2d34a26a334 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GroupFindings/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/GroupFindings/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GroupFindingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/ListAssets/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/ListAssets/main.go index a3d41a70a799..3246813192c2 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/ListAssets/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/ListAssets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListAssetsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/ListFindings/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/ListFindings/main.go index 2365fdeca334..2c083582166c 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/ListFindings/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/ListFindings/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListFindingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/ListNotificationConfigs/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/ListNotificationConfigs/main.go index f84d97c1b998..81fe851dfca2 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/ListNotificationConfigs/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/ListNotificationConfigs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListNotificationConfigsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/ListSources/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/ListSources/main.go index dc35afb5802d..35a11ab148de 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/ListSources/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/ListSources/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListSourcesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/RunAssetDiscovery/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/RunAssetDiscovery/main.go index 1748b8914545..6d7a174d3386 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/RunAssetDiscovery/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/RunAssetDiscovery/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.RunAssetDiscoveryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/SetFindingState/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/SetFindingState/main.go index 9801275e9e14..b55ab91bf39f 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/SetFindingState/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/SetFindingState/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.SetFindingStateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/SetIamPolicy/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/SetIamPolicy/main.go index b4212e42e0bb..01ed69dd26e8 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/SetIamPolicy/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/TestIamPermissions/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/TestIamPermissions/main.go index 5b65639ee629..09916e1e957c 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/TestIamPermissions/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateFinding/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateFinding/main.go index ec8b71f820f3..7f49e91ad3e2 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateFinding/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateFinding/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateFindingRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateNotificationConfig/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateNotificationConfig/main.go index 14f5b6c6d573..8a075e3868ed 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateNotificationConfig/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateNotificationConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateNotificationConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateOrganizationSettings/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateOrganizationSettings/main.go index f52c18afec2b..a50fdda831f2 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateOrganizationSettings/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateOrganizationSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateOrganizationSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateSecurityMarks/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateSecurityMarks/main.go index 491d4a8e11b9..033652f2cc30 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateSecurityMarks/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateSecurityMarks/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateSecurityMarksRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateSource/main.go b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateSource/main.go index 758229931261..3a094c01d031 100644 --- a/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateSource/main.go +++ b/internal/generated/snippets/securitycenter/apiv1p1beta1/Client/UpdateSource/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateSourceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/BatchCalculateEffectiveSettings/main.go b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/BatchCalculateEffectiveSettings/main.go index 9f8bbbb23f56..9b39d6b7a5c0 100644 --- a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/BatchCalculateEffectiveSettings/main.go +++ b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/BatchCalculateEffectiveSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.BatchCalculateEffectiveSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/BatchGetSettings/main.go b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/BatchGetSettings/main.go index 1c07df5606c7..872be1aeafc4 100644 --- a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/BatchGetSettings/main.go +++ b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/BatchGetSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.BatchGetSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/CalculateEffectiveComponentSettings/main.go b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/CalculateEffectiveComponentSettings/main.go index d3678d1e3218..91a5b0900272 100644 --- a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/CalculateEffectiveComponentSettings/main.go +++ b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/CalculateEffectiveComponentSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.CalculateEffectiveComponentSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/CalculateEffectiveSettings/main.go b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/CalculateEffectiveSettings/main.go index 8d686e9774ad..63f4236615f3 100644 --- a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/CalculateEffectiveSettings/main.go +++ b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/CalculateEffectiveSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.CalculateEffectiveSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/GetComponentSettings/main.go b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/GetComponentSettings/main.go index 0966be75765f..87fed0a7cf27 100644 --- a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/GetComponentSettings/main.go +++ b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/GetComponentSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.GetComponentSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/GetServiceAccount/main.go b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/GetServiceAccount/main.go index 3e1b08682ab8..b897bb4287ec 100644 --- a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/GetServiceAccount/main.go +++ b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/GetServiceAccount/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.GetServiceAccountRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/GetSettings/main.go b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/GetSettings/main.go index f4153c0a6c7e..34ef17da7d82 100644 --- a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/GetSettings/main.go +++ b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/GetSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.GetSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/ListComponents/main.go b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/ListComponents/main.go index 57d433baeed4..e004fc562374 100644 --- a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/ListComponents/main.go +++ b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/ListComponents/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.ListComponentsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/ListDetectors/main.go b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/ListDetectors/main.go index d51a16b77e2d..5ec9e38bb3db 100644 --- a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/ListDetectors/main.go +++ b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/ListDetectors/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.ListDetectorsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/ResetComponentSettings/main.go b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/ResetComponentSettings/main.go index 0194c40c49f3..5c4ba1ae68d3 100644 --- a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/ResetComponentSettings/main.go +++ b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/ResetComponentSettings/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.ResetComponentSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/ResetSettings/main.go b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/ResetSettings/main.go index 0d66be62ff1b..13956ef9306c 100644 --- a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/ResetSettings/main.go +++ b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/ResetSettings/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.ResetSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/UpdateComponentSettings/main.go b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/UpdateComponentSettings/main.go index f01e355950c0..49dc2339c183 100644 --- a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/UpdateComponentSettings/main.go +++ b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/UpdateComponentSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.UpdateComponentSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/UpdateSettings/main.go b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/UpdateSettings/main.go index 4c2bd0801b7d..e8b88603c7c2 100644 --- a/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/UpdateSettings/main.go +++ b/internal/generated/snippets/securitycenter/settings/apiv1beta1/SecurityCenterSettingsClient/UpdateSettings/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.UpdateSettingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicecontrol/apiv1/QuotaControllerClient/AllocateQuota/main.go b/internal/generated/snippets/servicecontrol/apiv1/QuotaControllerClient/AllocateQuota/main.go index 6a3b4400f1db..b23547deb205 100644 --- a/internal/generated/snippets/servicecontrol/apiv1/QuotaControllerClient/AllocateQuota/main.go +++ b/internal/generated/snippets/servicecontrol/apiv1/QuotaControllerClient/AllocateQuota/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicecontrolpb "google.golang.org/genproto/googleapis/api/servicecontrol/v1" - ctx := context.Background() c, err := servicecontrol.NewQuotaControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicecontrolpb.AllocateQuotaRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicecontrol/apiv1/ServiceControllerClient/Check/main.go b/internal/generated/snippets/servicecontrol/apiv1/ServiceControllerClient/Check/main.go index de845e00c597..001a5d214917 100644 --- a/internal/generated/snippets/servicecontrol/apiv1/ServiceControllerClient/Check/main.go +++ b/internal/generated/snippets/servicecontrol/apiv1/ServiceControllerClient/Check/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicecontrolpb "google.golang.org/genproto/googleapis/api/servicecontrol/v1" - ctx := context.Background() c, err := servicecontrol.NewServiceControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicecontrolpb.CheckRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicecontrol/apiv1/ServiceControllerClient/Report/main.go b/internal/generated/snippets/servicecontrol/apiv1/ServiceControllerClient/Report/main.go index ddb5423c6663..9810f6fae5e6 100644 --- a/internal/generated/snippets/servicecontrol/apiv1/ServiceControllerClient/Report/main.go +++ b/internal/generated/snippets/servicecontrol/apiv1/ServiceControllerClient/Report/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicecontrolpb "google.golang.org/genproto/googleapis/api/servicecontrol/v1" - ctx := context.Background() c, err := servicecontrol.NewServiceControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicecontrolpb.ReportRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/LookupClient/ResolveService/main.go b/internal/generated/snippets/servicedirectory/apiv1/LookupClient/ResolveService/main.go index 713801fdd1a3..96ac6e92f209 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/LookupClient/ResolveService/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/LookupClient/ResolveService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewLookupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.ResolveServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/CreateEndpoint/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/CreateEndpoint/main.go index 9cb5ed7758df..f207df67492b 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/CreateEndpoint/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/CreateEndpoint/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.CreateEndpointRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/CreateNamespace/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/CreateNamespace/main.go index de29a0105781..91ff47cf1332 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/CreateNamespace/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/CreateNamespace/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.CreateNamespaceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/CreateService/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/CreateService/main.go index 723a0479662f..f0675661a011 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/CreateService/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/CreateService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.CreateServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/DeleteEndpoint/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/DeleteEndpoint/main.go index 43a4a156e01a..a4b9bb7a6cc0 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/DeleteEndpoint/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/DeleteEndpoint/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.DeleteEndpointRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/DeleteNamespace/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/DeleteNamespace/main.go index 7b98381057f5..08f424cf5ceb 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/DeleteNamespace/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/DeleteNamespace/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.DeleteNamespaceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/DeleteService/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/DeleteService/main.go index 341d36e6858c..8e83e27985dc 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/DeleteService/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/DeleteService/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.DeleteServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/GetEndpoint/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/GetEndpoint/main.go index 2d61a334158b..d498afdb1dbb 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/GetEndpoint/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/GetEndpoint/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.GetEndpointRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/GetIamPolicy/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/GetIamPolicy/main.go index 3aa49c0426d4..ae6fe654ce99 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/GetIamPolicy/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/GetNamespace/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/GetNamespace/main.go index 536dd1a20241..748b6ee8a6e9 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/GetNamespace/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/GetNamespace/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.GetNamespaceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/GetService/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/GetService/main.go index 15579dbcdce4..807e79eb114b 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/GetService/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/GetService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.GetServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/ListEndpoints/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/ListEndpoints/main.go index 08d5c842d2e7..9166f964b11a 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/ListEndpoints/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/ListEndpoints/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.ListEndpointsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/ListNamespaces/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/ListNamespaces/main.go index e3c1115317f2..be965d248725 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/ListNamespaces/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/ListNamespaces/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.ListNamespacesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/ListServices/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/ListServices/main.go index 85663aeee510..0f4c7b687ef0 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/ListServices/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/ListServices/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.ListServicesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/SetIamPolicy/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/SetIamPolicy/main.go index 9872c04803c0..cbd6879c308e 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/SetIamPolicy/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/TestIamPermissions/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/TestIamPermissions/main.go index 85e9279f113c..4aa572f471c8 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/TestIamPermissions/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/UpdateEndpoint/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/UpdateEndpoint/main.go index ab380dfdf177..6b0c43bbb629 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/UpdateEndpoint/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/UpdateEndpoint/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.UpdateEndpointRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/UpdateNamespace/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/UpdateNamespace/main.go index e6efe6059960..e5b05d203435 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/UpdateNamespace/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/UpdateNamespace/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.UpdateNamespaceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/UpdateService/main.go b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/UpdateService/main.go index 75c828701ff5..55463ca7eda1 100644 --- a/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/UpdateService/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1/RegistrationClient/UpdateService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.UpdateServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/LookupClient/ResolveService/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/LookupClient/ResolveService/main.go index cf53a5eddbb4..1ccb510b65f0 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/LookupClient/ResolveService/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/LookupClient/ResolveService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewLookupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.ResolveServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/CreateEndpoint/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/CreateEndpoint/main.go index 0db19b8d5c0a..0906ec62b9a9 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/CreateEndpoint/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/CreateEndpoint/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.CreateEndpointRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/CreateNamespace/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/CreateNamespace/main.go index d36259384c81..292d7c598975 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/CreateNamespace/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/CreateNamespace/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.CreateNamespaceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/CreateService/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/CreateService/main.go index 81fcd0698144..66a5fa6fa41e 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/CreateService/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/CreateService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.CreateServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/DeleteEndpoint/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/DeleteEndpoint/main.go index 17385d47658b..3e3836b43217 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/DeleteEndpoint/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/DeleteEndpoint/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.DeleteEndpointRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/DeleteNamespace/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/DeleteNamespace/main.go index 823d9b12903e..55e801a220c4 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/DeleteNamespace/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/DeleteNamespace/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.DeleteNamespaceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/DeleteService/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/DeleteService/main.go index 6405a2727f18..4beb4127de69 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/DeleteService/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/DeleteService/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.DeleteServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/GetEndpoint/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/GetEndpoint/main.go index 94078c3f9b39..4692679d8845 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/GetEndpoint/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/GetEndpoint/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.GetEndpointRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/GetIamPolicy/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/GetIamPolicy/main.go index a3edad7819c2..f5ee4af51746 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/GetIamPolicy/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/GetNamespace/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/GetNamespace/main.go index e252aad4f39f..fb830e5ccd87 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/GetNamespace/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/GetNamespace/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.GetNamespaceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/GetService/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/GetService/main.go index baee0dff2bde..4b11d6e11d7b 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/GetService/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/GetService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.GetServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/ListEndpoints/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/ListEndpoints/main.go index 6f0309e50628..66e4c58dec9a 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/ListEndpoints/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/ListEndpoints/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.ListEndpointsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/ListNamespaces/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/ListNamespaces/main.go index f242f5547dff..b13417eb4516 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/ListNamespaces/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/ListNamespaces/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.ListNamespacesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/ListServices/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/ListServices/main.go index 7942cd870099..aa24912cfa7f 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/ListServices/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/ListServices/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.ListServicesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/SetIamPolicy/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/SetIamPolicy/main.go index fd9d25470fbd..460c1d7d588d 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/SetIamPolicy/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/TestIamPermissions/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/TestIamPermissions/main.go index 11a772df6064..8a5661d8ac52 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/TestIamPermissions/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/UpdateEndpoint/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/UpdateEndpoint/main.go index 30fd910fc8e6..a722844efaca 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/UpdateEndpoint/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/UpdateEndpoint/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.UpdateEndpointRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/UpdateNamespace/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/UpdateNamespace/main.go index b2fe3e9f874b..baa0fd44bae8 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/UpdateNamespace/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/UpdateNamespace/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.UpdateNamespaceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/UpdateService/main.go b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/UpdateService/main.go index 773e095359dc..0ba80b5f2f58 100644 --- a/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/UpdateService/main.go +++ b/internal/generated/snippets/servicedirectory/apiv1beta1/RegistrationClient/UpdateService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.UpdateServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/CreateService/main.go b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/CreateService/main.go index f3324a4c0a15..58867691fa39 100644 --- a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/CreateService/main.go +++ b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/CreateService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.CreateServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/CreateServiceConfig/main.go b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/CreateServiceConfig/main.go index 0eef66c13cba..32578999dc35 100644 --- a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/CreateServiceConfig/main.go +++ b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/CreateServiceConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.CreateServiceConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/CreateServiceRollout/main.go b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/CreateServiceRollout/main.go index ed836ecccf2e..842e7ca1171d 100644 --- a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/CreateServiceRollout/main.go +++ b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/CreateServiceRollout/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.CreateServiceRolloutRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/DeleteService/main.go b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/DeleteService/main.go index cdcff289d2d5..679457357bf0 100644 --- a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/DeleteService/main.go +++ b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/DeleteService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.DeleteServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/DisableService/main.go b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/DisableService/main.go index 1a49a3de07f3..3ef83e017e7a 100644 --- a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/DisableService/main.go +++ b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/DisableService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.DisableServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/EnableService/main.go b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/EnableService/main.go index 34eb2abab5e5..eaa6ef781dc2 100644 --- a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/EnableService/main.go +++ b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/EnableService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.EnableServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/GenerateConfigReport/main.go b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/GenerateConfigReport/main.go index 8b0b67c51c6b..1b14db280378 100644 --- a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/GenerateConfigReport/main.go +++ b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/GenerateConfigReport/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.GenerateConfigReportRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/GetService/main.go b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/GetService/main.go index f6b85c4bc1d8..ae0eca069277 100644 --- a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/GetService/main.go +++ b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/GetService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.GetServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/GetServiceConfig/main.go b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/GetServiceConfig/main.go index d869c0e90293..2c26dc7cf4e3 100644 --- a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/GetServiceConfig/main.go +++ b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/GetServiceConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.GetServiceConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/GetServiceRollout/main.go b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/GetServiceRollout/main.go index 1d7a1101cafe..a78aacd6b20e 100644 --- a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/GetServiceRollout/main.go +++ b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/GetServiceRollout/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.GetServiceRolloutRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/ListServiceConfigs/main.go b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/ListServiceConfigs/main.go index 2c72d9b808ec..7eec05843301 100644 --- a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/ListServiceConfigs/main.go +++ b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/ListServiceConfigs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.ListServiceConfigsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/ListServiceRollouts/main.go b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/ListServiceRollouts/main.go index d0b6461ebe65..4e1585cde5ff 100644 --- a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/ListServiceRollouts/main.go +++ b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/ListServiceRollouts/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.ListServiceRolloutsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/ListServices/main.go b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/ListServices/main.go index aceac2569932..0effdf46ee51 100644 --- a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/ListServices/main.go +++ b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/ListServices/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.ListServicesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/SubmitConfigSource/main.go b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/SubmitConfigSource/main.go index bec06b114ae0..a8e03f30a343 100644 --- a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/SubmitConfigSource/main.go +++ b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/SubmitConfigSource/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.SubmitConfigSourceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/UndeleteService/main.go b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/UndeleteService/main.go index aa5331fd3e2b..6b7a0dcaa0d3 100644 --- a/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/UndeleteService/main.go +++ b/internal/generated/snippets/servicemanagement/apiv1/ServiceManagerClient/UndeleteService/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.UndeleteServiceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/serviceusage/apiv1/Client/BatchEnableServices/main.go b/internal/generated/snippets/serviceusage/apiv1/Client/BatchEnableServices/main.go new file mode 100644 index 000000000000..0bae8be65207 --- /dev/null +++ b/internal/generated/snippets/serviceusage/apiv1/Client/BatchEnableServices/main.go @@ -0,0 +1,50 @@ +// Copyright 2021 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. + +// [START serviceusage_v1_generated_ServiceUsage_BatchEnableServices_sync] + +package main + +import ( + "context" + + serviceusage "cloud.google.com/go/serviceusage/apiv1" + serviceusagepb "google.golang.org/genproto/googleapis/api/serviceusage/v1" +) + +func main() { + ctx := context.Background() + c, err := serviceusage.NewClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &serviceusagepb.BatchEnableServicesRequest{ + // TODO: Fill request struct fields. + } + op, err := c.BatchEnableServices(ctx, req) + if err != nil { + // TODO: Handle error. + } + + resp, err := op.Wait(ctx) + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp +} + +// [END serviceusage_v1_generated_ServiceUsage_BatchEnableServices_sync] diff --git a/internal/generated/snippets/serviceusage/apiv1/Client/BatchGetServices/main.go b/internal/generated/snippets/serviceusage/apiv1/Client/BatchGetServices/main.go new file mode 100644 index 000000000000..fd6fa486806a --- /dev/null +++ b/internal/generated/snippets/serviceusage/apiv1/Client/BatchGetServices/main.go @@ -0,0 +1,45 @@ +// Copyright 2021 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. + +// [START serviceusage_v1_generated_ServiceUsage_BatchGetServices_sync] + +package main + +import ( + "context" + + serviceusage "cloud.google.com/go/serviceusage/apiv1" + serviceusagepb "google.golang.org/genproto/googleapis/api/serviceusage/v1" +) + +func main() { + ctx := context.Background() + c, err := serviceusage.NewClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &serviceusagepb.BatchGetServicesRequest{ + // TODO: Fill request struct fields. + } + resp, err := c.BatchGetServices(ctx, req) + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp +} + +// [END serviceusage_v1_generated_ServiceUsage_BatchGetServices_sync] diff --git a/internal/generated/snippets/serviceusage/apiv1/Client/DisableService/main.go b/internal/generated/snippets/serviceusage/apiv1/Client/DisableService/main.go new file mode 100644 index 000000000000..8cba69936998 --- /dev/null +++ b/internal/generated/snippets/serviceusage/apiv1/Client/DisableService/main.go @@ -0,0 +1,50 @@ +// Copyright 2021 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. + +// [START serviceusage_v1_generated_ServiceUsage_DisableService_sync] + +package main + +import ( + "context" + + serviceusage "cloud.google.com/go/serviceusage/apiv1" + serviceusagepb "google.golang.org/genproto/googleapis/api/serviceusage/v1" +) + +func main() { + ctx := context.Background() + c, err := serviceusage.NewClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &serviceusagepb.DisableServiceRequest{ + // TODO: Fill request struct fields. + } + op, err := c.DisableService(ctx, req) + if err != nil { + // TODO: Handle error. + } + + resp, err := op.Wait(ctx) + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp +} + +// [END serviceusage_v1_generated_ServiceUsage_DisableService_sync] diff --git a/internal/generated/snippets/serviceusage/apiv1/Client/EnableService/main.go b/internal/generated/snippets/serviceusage/apiv1/Client/EnableService/main.go new file mode 100644 index 000000000000..8945721a404b --- /dev/null +++ b/internal/generated/snippets/serviceusage/apiv1/Client/EnableService/main.go @@ -0,0 +1,50 @@ +// Copyright 2021 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. + +// [START serviceusage_v1_generated_ServiceUsage_EnableService_sync] + +package main + +import ( + "context" + + serviceusage "cloud.google.com/go/serviceusage/apiv1" + serviceusagepb "google.golang.org/genproto/googleapis/api/serviceusage/v1" +) + +func main() { + ctx := context.Background() + c, err := serviceusage.NewClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &serviceusagepb.EnableServiceRequest{ + // TODO: Fill request struct fields. + } + op, err := c.EnableService(ctx, req) + if err != nil { + // TODO: Handle error. + } + + resp, err := op.Wait(ctx) + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp +} + +// [END serviceusage_v1_generated_ServiceUsage_EnableService_sync] diff --git a/internal/generated/snippets/serviceusage/apiv1/Client/GetService/main.go b/internal/generated/snippets/serviceusage/apiv1/Client/GetService/main.go new file mode 100644 index 000000000000..df500e600c81 --- /dev/null +++ b/internal/generated/snippets/serviceusage/apiv1/Client/GetService/main.go @@ -0,0 +1,45 @@ +// Copyright 2021 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. + +// [START serviceusage_v1_generated_ServiceUsage_GetService_sync] + +package main + +import ( + "context" + + serviceusage "cloud.google.com/go/serviceusage/apiv1" + serviceusagepb "google.golang.org/genproto/googleapis/api/serviceusage/v1" +) + +func main() { + ctx := context.Background() + c, err := serviceusage.NewClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &serviceusagepb.GetServiceRequest{ + // TODO: Fill request struct fields. + } + resp, err := c.GetService(ctx, req) + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp +} + +// [END serviceusage_v1_generated_ServiceUsage_GetService_sync] diff --git a/internal/generated/snippets/serviceusage/apiv1/Client/ListServices/main.go b/internal/generated/snippets/serviceusage/apiv1/Client/ListServices/main.go new file mode 100644 index 000000000000..e22e13e34413 --- /dev/null +++ b/internal/generated/snippets/serviceusage/apiv1/Client/ListServices/main.go @@ -0,0 +1,52 @@ +// Copyright 2021 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. + +// [START serviceusage_v1_generated_ServiceUsage_ListServices_sync] + +package main + +import ( + "context" + + serviceusage "cloud.google.com/go/serviceusage/apiv1" + "google.golang.org/api/iterator" + serviceusagepb "google.golang.org/genproto/googleapis/api/serviceusage/v1" +) + +func main() { + ctx := context.Background() + c, err := serviceusage.NewClient(ctx) + if err != nil { + // TODO: Handle error. + } + defer c.Close() + + req := &serviceusagepb.ListServicesRequest{ + // TODO: Fill request struct fields. + } + it := c.ListServices(ctx, req) + for { + resp, err := it.Next() + if err == iterator.Done { + break + } + if err != nil { + // TODO: Handle error. + } + // TODO: Use resp. + _ = resp + } +} + +// [END serviceusage_v1_generated_ServiceUsage_ListServices_sync] diff --git a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/CreateBackup/main.go b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/CreateBackup/main.go index 8144e6dadf28..a69b2bc8b0c7 100644 --- a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/CreateBackup/main.go +++ b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/CreateBackup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.CreateBackupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/CreateDatabase/main.go b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/CreateDatabase/main.go index 7699dfcbab51..324c2dcb7b4c 100644 --- a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/CreateDatabase/main.go +++ b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/CreateDatabase/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.CreateDatabaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/DeleteBackup/main.go b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/DeleteBackup/main.go index 9ea3501a3b83..6cd1788e00dc 100644 --- a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/DeleteBackup/main.go +++ b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/DeleteBackup/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.DeleteBackupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/DropDatabase/main.go b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/DropDatabase/main.go index 26ac8f20acde..52218bf746a0 100644 --- a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/DropDatabase/main.go +++ b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/DropDatabase/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.DropDatabaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/GetBackup/main.go b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/GetBackup/main.go index 399534012cbb..d5884ff24e5b 100644 --- a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/GetBackup/main.go +++ b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/GetBackup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.GetBackupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/GetDatabase/main.go b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/GetDatabase/main.go index 615408cf4596..0dde0600fcd1 100644 --- a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/GetDatabase/main.go +++ b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/GetDatabase/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.GetDatabaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/GetDatabaseDdl/main.go b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/GetDatabaseDdl/main.go index b7499d2a1c88..2d555b7eea68 100644 --- a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/GetDatabaseDdl/main.go +++ b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/GetDatabaseDdl/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.GetDatabaseDdlRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/GetIamPolicy/main.go b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/GetIamPolicy/main.go index 07e74cda1269..0b8e082a8809 100644 --- a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/GetIamPolicy/main.go +++ b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/ListBackupOperations/main.go b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/ListBackupOperations/main.go index 3bd418ecab87..2cab3dd69aee 100644 --- a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/ListBackupOperations/main.go +++ b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/ListBackupOperations/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.ListBackupOperationsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/ListBackups/main.go b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/ListBackups/main.go index 8d46c893af49..e9d18d4ada00 100644 --- a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/ListBackups/main.go +++ b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/ListBackups/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.ListBackupsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/ListDatabaseOperations/main.go b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/ListDatabaseOperations/main.go index f0c25c7c4b2f..f893eaa7f0cd 100644 --- a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/ListDatabaseOperations/main.go +++ b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/ListDatabaseOperations/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.ListDatabaseOperationsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/ListDatabases/main.go b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/ListDatabases/main.go index e72939706cc0..0dbd7862c93f 100644 --- a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/ListDatabases/main.go +++ b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/ListDatabases/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.ListDatabasesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/RestoreDatabase/main.go b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/RestoreDatabase/main.go index eb82e9559bb2..1014df260588 100644 --- a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/RestoreDatabase/main.go +++ b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/RestoreDatabase/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.RestoreDatabaseRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/SetIamPolicy/main.go b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/SetIamPolicy/main.go index 6eca90c89853..32a9e1956b2a 100644 --- a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/SetIamPolicy/main.go +++ b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/TestIamPermissions/main.go b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/TestIamPermissions/main.go index 6e67cf27a464..f0956949f0d7 100644 --- a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/TestIamPermissions/main.go +++ b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/UpdateBackup/main.go b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/UpdateBackup/main.go index ccc3a916f59a..f8c107671543 100644 --- a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/UpdateBackup/main.go +++ b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/UpdateBackup/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.UpdateBackupRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/UpdateDatabaseDdl/main.go b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/UpdateDatabaseDdl/main.go index e2114705f1f2..cf66ee860319 100644 --- a/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/UpdateDatabaseDdl/main.go +++ b/internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/UpdateDatabaseDdl/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.UpdateDatabaseDdlRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/CreateInstance/main.go b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/CreateInstance/main.go index eadfca8642af..42ab41f09d06 100644 --- a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/CreateInstance/main.go +++ b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/CreateInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &instancepb.CreateInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/DeleteInstance/main.go b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/DeleteInstance/main.go index fd3511c85959..89ca1ed2abfc 100644 --- a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/DeleteInstance/main.go +++ b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/DeleteInstance/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &instancepb.DeleteInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/GetIamPolicy/main.go b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/GetIamPolicy/main.go index 54953195769e..905bb41033e6 100644 --- a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/GetIamPolicy/main.go +++ b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/GetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/GetInstance/main.go b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/GetInstance/main.go index 14db5ff04669..762d75124723 100644 --- a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/GetInstance/main.go +++ b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/GetInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &instancepb.GetInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/GetInstanceConfig/main.go b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/GetInstanceConfig/main.go index 236b561f02b6..7e9593aa79ee 100644 --- a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/GetInstanceConfig/main.go +++ b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/GetInstanceConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &instancepb.GetInstanceConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/ListInstanceConfigs/main.go b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/ListInstanceConfigs/main.go index e94db5e8ccb0..093ca0077a6c 100644 --- a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/ListInstanceConfigs/main.go +++ b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/ListInstanceConfigs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &instancepb.ListInstanceConfigsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/ListInstances/main.go b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/ListInstances/main.go index d0a6e1b23054..acc674bf525b 100644 --- a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/ListInstances/main.go +++ b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/ListInstances/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &instancepb.ListInstancesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/SetIamPolicy/main.go b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/SetIamPolicy/main.go index f8ff8d042c4d..2d1de4d83b92 100644 --- a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/SetIamPolicy/main.go +++ b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/SetIamPolicy/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/TestIamPermissions/main.go b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/TestIamPermissions/main.go index 783578594c8e..c37b7f8dfcd7 100644 --- a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/TestIamPermissions/main.go +++ b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/TestIamPermissions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/UpdateInstance/main.go b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/UpdateInstance/main.go index 7590201311e5..09cacb55e60f 100644 --- a/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/UpdateInstance/main.go +++ b/internal/generated/snippets/spanner/admin/instance/apiv1/InstanceAdminClient/UpdateInstance/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &instancepb.UpdateInstanceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/apiv1/Client/BatchCreateSessions/main.go b/internal/generated/snippets/spanner/apiv1/Client/BatchCreateSessions/main.go index a74d9891a8bb..7366f66e5840 100644 --- a/internal/generated/snippets/spanner/apiv1/Client/BatchCreateSessions/main.go +++ b/internal/generated/snippets/spanner/apiv1/Client/BatchCreateSessions/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.BatchCreateSessionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/apiv1/Client/BeginTransaction/main.go b/internal/generated/snippets/spanner/apiv1/Client/BeginTransaction/main.go index ea1cc2453301..4324bcc4ac57 100644 --- a/internal/generated/snippets/spanner/apiv1/Client/BeginTransaction/main.go +++ b/internal/generated/snippets/spanner/apiv1/Client/BeginTransaction/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.BeginTransactionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/apiv1/Client/Commit/main.go b/internal/generated/snippets/spanner/apiv1/Client/Commit/main.go index 955d9d7e925c..657de8e4306f 100644 --- a/internal/generated/snippets/spanner/apiv1/Client/Commit/main.go +++ b/internal/generated/snippets/spanner/apiv1/Client/Commit/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.CommitRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/apiv1/Client/CreateSession/main.go b/internal/generated/snippets/spanner/apiv1/Client/CreateSession/main.go index 45239791d68b..f5257be98076 100644 --- a/internal/generated/snippets/spanner/apiv1/Client/CreateSession/main.go +++ b/internal/generated/snippets/spanner/apiv1/Client/CreateSession/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.CreateSessionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/apiv1/Client/DeleteSession/main.go b/internal/generated/snippets/spanner/apiv1/Client/DeleteSession/main.go index 7f976a374acb..b879eb4b8785 100644 --- a/internal/generated/snippets/spanner/apiv1/Client/DeleteSession/main.go +++ b/internal/generated/snippets/spanner/apiv1/Client/DeleteSession/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.DeleteSessionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/apiv1/Client/ExecuteBatchDml/main.go b/internal/generated/snippets/spanner/apiv1/Client/ExecuteBatchDml/main.go index d37adc7dce5b..c9863ee42c1c 100644 --- a/internal/generated/snippets/spanner/apiv1/Client/ExecuteBatchDml/main.go +++ b/internal/generated/snippets/spanner/apiv1/Client/ExecuteBatchDml/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.ExecuteBatchDmlRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/apiv1/Client/ExecuteSql/main.go b/internal/generated/snippets/spanner/apiv1/Client/ExecuteSql/main.go index b1b5933669df..d202f873c98a 100644 --- a/internal/generated/snippets/spanner/apiv1/Client/ExecuteSql/main.go +++ b/internal/generated/snippets/spanner/apiv1/Client/ExecuteSql/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.ExecuteSqlRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/apiv1/Client/GetSession/main.go b/internal/generated/snippets/spanner/apiv1/Client/GetSession/main.go index 7c7b78208c5a..291d58b0c64b 100644 --- a/internal/generated/snippets/spanner/apiv1/Client/GetSession/main.go +++ b/internal/generated/snippets/spanner/apiv1/Client/GetSession/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.GetSessionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/apiv1/Client/ListSessions/main.go b/internal/generated/snippets/spanner/apiv1/Client/ListSessions/main.go index 5b12a1c4bbf1..6ecaa6e75156 100644 --- a/internal/generated/snippets/spanner/apiv1/Client/ListSessions/main.go +++ b/internal/generated/snippets/spanner/apiv1/Client/ListSessions/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.ListSessionsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/apiv1/Client/PartitionQuery/main.go b/internal/generated/snippets/spanner/apiv1/Client/PartitionQuery/main.go index 8420fc8f8902..509ed035edd0 100644 --- a/internal/generated/snippets/spanner/apiv1/Client/PartitionQuery/main.go +++ b/internal/generated/snippets/spanner/apiv1/Client/PartitionQuery/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.PartitionQueryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/apiv1/Client/PartitionRead/main.go b/internal/generated/snippets/spanner/apiv1/Client/PartitionRead/main.go index 2313a06e68c9..2294d4bad3ff 100644 --- a/internal/generated/snippets/spanner/apiv1/Client/PartitionRead/main.go +++ b/internal/generated/snippets/spanner/apiv1/Client/PartitionRead/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.PartitionReadRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/apiv1/Client/Read/main.go b/internal/generated/snippets/spanner/apiv1/Client/Read/main.go index eed3406bf715..2777a7db1ea8 100644 --- a/internal/generated/snippets/spanner/apiv1/Client/Read/main.go +++ b/internal/generated/snippets/spanner/apiv1/Client/Read/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.ReadRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/spanner/apiv1/Client/Rollback/main.go b/internal/generated/snippets/spanner/apiv1/Client/Rollback/main.go index 056e02ae501b..90395ed05064 100644 --- a/internal/generated/snippets/spanner/apiv1/Client/Rollback/main.go +++ b/internal/generated/snippets/spanner/apiv1/Client/Rollback/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.RollbackRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/speech/apiv1/Client/LongRunningRecognize/main.go b/internal/generated/snippets/speech/apiv1/Client/LongRunningRecognize/main.go index 069a1bbcfc70..7a1615edaff8 100644 --- a/internal/generated/snippets/speech/apiv1/Client/LongRunningRecognize/main.go +++ b/internal/generated/snippets/speech/apiv1/Client/LongRunningRecognize/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1" - ctx := context.Background() c, err := speech.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.LongRunningRecognizeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/speech/apiv1/Client/Recognize/main.go b/internal/generated/snippets/speech/apiv1/Client/Recognize/main.go index 3c5cf2ace660..302434b2e738 100644 --- a/internal/generated/snippets/speech/apiv1/Client/Recognize/main.go +++ b/internal/generated/snippets/speech/apiv1/Client/Recognize/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1" - ctx := context.Background() c, err := speech.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.RecognizeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/speech/apiv1/Client/StreamingRecognize/main.go b/internal/generated/snippets/speech/apiv1/Client/StreamingRecognize/main.go index ef84df41d7a8..0b26fabc7d94 100644 --- a/internal/generated/snippets/speech/apiv1/Client/StreamingRecognize/main.go +++ b/internal/generated/snippets/speech/apiv1/Client/StreamingRecognize/main.go @@ -25,13 +25,12 @@ import ( ) func main() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1" - ctx := context.Background() c, err := speech.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.StreamingRecognize(ctx) if err != nil { // TODO: Handle error. diff --git a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/CreateCustomClass/main.go b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/CreateCustomClass/main.go index 4f7f48ba1b43..945aa372f535 100644 --- a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/CreateCustomClass/main.go +++ b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/CreateCustomClass/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewAdaptationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.CreateCustomClassRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/CreatePhraseSet/main.go b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/CreatePhraseSet/main.go index 1867d814ad15..4af4c2247a5c 100644 --- a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/CreatePhraseSet/main.go +++ b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/CreatePhraseSet/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewAdaptationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.CreatePhraseSetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/DeleteCustomClass/main.go b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/DeleteCustomClass/main.go index 52930e6141ac..e9f4d9fd5854 100644 --- a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/DeleteCustomClass/main.go +++ b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/DeleteCustomClass/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.DeleteCustomClassRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/DeletePhraseSet/main.go b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/DeletePhraseSet/main.go index 8f92a7783bb7..981c21e80ffa 100644 --- a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/DeletePhraseSet/main.go +++ b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/DeletePhraseSet/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.DeletePhraseSetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/GetCustomClass/main.go b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/GetCustomClass/main.go index 04a9945f4f69..98f380fd50df 100644 --- a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/GetCustomClass/main.go +++ b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/GetCustomClass/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewAdaptationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.GetCustomClassRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/GetPhraseSet/main.go b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/GetPhraseSet/main.go index b6ccafd84ab9..0117e8ccc978 100644 --- a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/GetPhraseSet/main.go +++ b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/GetPhraseSet/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewAdaptationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.GetPhraseSetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/ListCustomClasses/main.go b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/ListCustomClasses/main.go index ba05d5a56508..6bd66dd10863 100644 --- a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/ListCustomClasses/main.go +++ b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/ListCustomClasses/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := speech.NewAdaptationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.ListCustomClassesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/ListPhraseSet/main.go b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/ListPhraseSet/main.go index 90c49a341246..69ee11ae55f4 100644 --- a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/ListPhraseSet/main.go +++ b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/ListPhraseSet/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := speech.NewAdaptationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.ListPhraseSetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/UpdateCustomClass/main.go b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/UpdateCustomClass/main.go index 87886370678f..c2bb2e5010de 100644 --- a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/UpdateCustomClass/main.go +++ b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/UpdateCustomClass/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewAdaptationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.UpdateCustomClassRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/UpdatePhraseSet/main.go b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/UpdatePhraseSet/main.go index 4f007807d09d..428bc957a26c 100644 --- a/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/UpdatePhraseSet/main.go +++ b/internal/generated/snippets/speech/apiv1p1beta1/AdaptationClient/UpdatePhraseSet/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewAdaptationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.UpdatePhraseSetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/speech/apiv1p1beta1/Client/LongRunningRecognize/main.go b/internal/generated/snippets/speech/apiv1p1beta1/Client/LongRunningRecognize/main.go index 18faf17dfb62..a64b0e8c57c0 100644 --- a/internal/generated/snippets/speech/apiv1p1beta1/Client/LongRunningRecognize/main.go +++ b/internal/generated/snippets/speech/apiv1p1beta1/Client/LongRunningRecognize/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.LongRunningRecognizeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/speech/apiv1p1beta1/Client/Recognize/main.go b/internal/generated/snippets/speech/apiv1p1beta1/Client/Recognize/main.go index a9dea599515e..004efe7ffb27 100644 --- a/internal/generated/snippets/speech/apiv1p1beta1/Client/Recognize/main.go +++ b/internal/generated/snippets/speech/apiv1p1beta1/Client/Recognize/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.RecognizeRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/speech/apiv1p1beta1/Client/StreamingRecognize/main.go b/internal/generated/snippets/speech/apiv1p1beta1/Client/StreamingRecognize/main.go index e6326aa19043..6a0369dee904 100644 --- a/internal/generated/snippets/speech/apiv1p1beta1/Client/StreamingRecognize/main.go +++ b/internal/generated/snippets/speech/apiv1p1beta1/Client/StreamingRecognize/main.go @@ -25,13 +25,12 @@ import ( ) func main() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.StreamingRecognize(ctx) if err != nil { // TODO: Handle error. diff --git a/internal/generated/snippets/talent/apiv4/CompanyClient/CreateCompany/main.go b/internal/generated/snippets/talent/apiv4/CompanyClient/CreateCompany/main.go index 306fb882e376..1d5915b9f39b 100644 --- a/internal/generated/snippets/talent/apiv4/CompanyClient/CreateCompany/main.go +++ b/internal/generated/snippets/talent/apiv4/CompanyClient/CreateCompany/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewCompanyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateCompanyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/CompanyClient/DeleteCompany/main.go b/internal/generated/snippets/talent/apiv4/CompanyClient/DeleteCompany/main.go index e5a8132bf028..e9576ab644bf 100644 --- a/internal/generated/snippets/talent/apiv4/CompanyClient/DeleteCompany/main.go +++ b/internal/generated/snippets/talent/apiv4/CompanyClient/DeleteCompany/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.DeleteCompanyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/CompanyClient/GetCompany/main.go b/internal/generated/snippets/talent/apiv4/CompanyClient/GetCompany/main.go index 70a0eb976742..c115383b9b8f 100644 --- a/internal/generated/snippets/talent/apiv4/CompanyClient/GetCompany/main.go +++ b/internal/generated/snippets/talent/apiv4/CompanyClient/GetCompany/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewCompanyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.GetCompanyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/CompanyClient/ListCompanies/main.go b/internal/generated/snippets/talent/apiv4/CompanyClient/ListCompanies/main.go index bfb84c042c72..f58bef536749 100644 --- a/internal/generated/snippets/talent/apiv4/CompanyClient/ListCompanies/main.go +++ b/internal/generated/snippets/talent/apiv4/CompanyClient/ListCompanies/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewCompanyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.ListCompaniesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/CompanyClient/UpdateCompany/main.go b/internal/generated/snippets/talent/apiv4/CompanyClient/UpdateCompany/main.go index b59014ff1ef9..ecadb870e89d 100644 --- a/internal/generated/snippets/talent/apiv4/CompanyClient/UpdateCompany/main.go +++ b/internal/generated/snippets/talent/apiv4/CompanyClient/UpdateCompany/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewCompanyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.UpdateCompanyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/CompletionClient/CompleteQuery/main.go b/internal/generated/snippets/talent/apiv4/CompletionClient/CompleteQuery/main.go index bc943b315708..c09ce1d050ba 100644 --- a/internal/generated/snippets/talent/apiv4/CompletionClient/CompleteQuery/main.go +++ b/internal/generated/snippets/talent/apiv4/CompletionClient/CompleteQuery/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewCompletionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CompleteQueryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/EventClient/CreateClientEvent/main.go b/internal/generated/snippets/talent/apiv4/EventClient/CreateClientEvent/main.go index d9aec3f7b9fa..fa08a3777508 100644 --- a/internal/generated/snippets/talent/apiv4/EventClient/CreateClientEvent/main.go +++ b/internal/generated/snippets/talent/apiv4/EventClient/CreateClientEvent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateClientEventRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/JobClient/BatchCreateJobs/main.go b/internal/generated/snippets/talent/apiv4/JobClient/BatchCreateJobs/main.go index 732fd4a2adb0..f8de51503c46 100644 --- a/internal/generated/snippets/talent/apiv4/JobClient/BatchCreateJobs/main.go +++ b/internal/generated/snippets/talent/apiv4/JobClient/BatchCreateJobs/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.BatchCreateJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/JobClient/BatchDeleteJobs/main.go b/internal/generated/snippets/talent/apiv4/JobClient/BatchDeleteJobs/main.go index d3ed21b0beee..34af1e2fe073 100644 --- a/internal/generated/snippets/talent/apiv4/JobClient/BatchDeleteJobs/main.go +++ b/internal/generated/snippets/talent/apiv4/JobClient/BatchDeleteJobs/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.BatchDeleteJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/JobClient/BatchUpdateJobs/main.go b/internal/generated/snippets/talent/apiv4/JobClient/BatchUpdateJobs/main.go index fd5c24c40d61..c6273fcafbce 100644 --- a/internal/generated/snippets/talent/apiv4/JobClient/BatchUpdateJobs/main.go +++ b/internal/generated/snippets/talent/apiv4/JobClient/BatchUpdateJobs/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.BatchUpdateJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/JobClient/CreateJob/main.go b/internal/generated/snippets/talent/apiv4/JobClient/CreateJob/main.go index 8ea55caacd4c..44ddab6eb011 100644 --- a/internal/generated/snippets/talent/apiv4/JobClient/CreateJob/main.go +++ b/internal/generated/snippets/talent/apiv4/JobClient/CreateJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/JobClient/DeleteJob/main.go b/internal/generated/snippets/talent/apiv4/JobClient/DeleteJob/main.go index 2b45a9f5f055..e541c8ef0f8d 100644 --- a/internal/generated/snippets/talent/apiv4/JobClient/DeleteJob/main.go +++ b/internal/generated/snippets/talent/apiv4/JobClient/DeleteJob/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.DeleteJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/JobClient/GetJob/main.go b/internal/generated/snippets/talent/apiv4/JobClient/GetJob/main.go index c53da4900698..503d51818719 100644 --- a/internal/generated/snippets/talent/apiv4/JobClient/GetJob/main.go +++ b/internal/generated/snippets/talent/apiv4/JobClient/GetJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.GetJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/JobClient/ListJobs/main.go b/internal/generated/snippets/talent/apiv4/JobClient/ListJobs/main.go index 94989e1e9f76..92d79bfc1ab6 100644 --- a/internal/generated/snippets/talent/apiv4/JobClient/ListJobs/main.go +++ b/internal/generated/snippets/talent/apiv4/JobClient/ListJobs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.ListJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/JobClient/SearchJobs/main.go b/internal/generated/snippets/talent/apiv4/JobClient/SearchJobs/main.go index cb6857b9d1b3..be8fc47b067c 100644 --- a/internal/generated/snippets/talent/apiv4/JobClient/SearchJobs/main.go +++ b/internal/generated/snippets/talent/apiv4/JobClient/SearchJobs/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.SearchJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/JobClient/SearchJobsForAlert/main.go b/internal/generated/snippets/talent/apiv4/JobClient/SearchJobsForAlert/main.go index 216194bdde1e..c4ac46a4721d 100644 --- a/internal/generated/snippets/talent/apiv4/JobClient/SearchJobsForAlert/main.go +++ b/internal/generated/snippets/talent/apiv4/JobClient/SearchJobsForAlert/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.SearchJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/JobClient/UpdateJob/main.go b/internal/generated/snippets/talent/apiv4/JobClient/UpdateJob/main.go index 8e464ee56b55..b20b8aaa67a3 100644 --- a/internal/generated/snippets/talent/apiv4/JobClient/UpdateJob/main.go +++ b/internal/generated/snippets/talent/apiv4/JobClient/UpdateJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.UpdateJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/TenantClient/CreateTenant/main.go b/internal/generated/snippets/talent/apiv4/TenantClient/CreateTenant/main.go index 6c564920ac16..2f991498646f 100644 --- a/internal/generated/snippets/talent/apiv4/TenantClient/CreateTenant/main.go +++ b/internal/generated/snippets/talent/apiv4/TenantClient/CreateTenant/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewTenantClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateTenantRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/TenantClient/DeleteTenant/main.go b/internal/generated/snippets/talent/apiv4/TenantClient/DeleteTenant/main.go index aaf9bcf7e846..8907577a0110 100644 --- a/internal/generated/snippets/talent/apiv4/TenantClient/DeleteTenant/main.go +++ b/internal/generated/snippets/talent/apiv4/TenantClient/DeleteTenant/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.DeleteTenantRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/TenantClient/GetTenant/main.go b/internal/generated/snippets/talent/apiv4/TenantClient/GetTenant/main.go index 596c4e446cca..73441a9b3501 100644 --- a/internal/generated/snippets/talent/apiv4/TenantClient/GetTenant/main.go +++ b/internal/generated/snippets/talent/apiv4/TenantClient/GetTenant/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewTenantClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.GetTenantRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/TenantClient/ListTenants/main.go b/internal/generated/snippets/talent/apiv4/TenantClient/ListTenants/main.go index 42547127dd81..af27d987c2d5 100644 --- a/internal/generated/snippets/talent/apiv4/TenantClient/ListTenants/main.go +++ b/internal/generated/snippets/talent/apiv4/TenantClient/ListTenants/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewTenantClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.ListTenantsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4/TenantClient/UpdateTenant/main.go b/internal/generated/snippets/talent/apiv4/TenantClient/UpdateTenant/main.go index 5254f578c209..692485b3509c 100644 --- a/internal/generated/snippets/talent/apiv4/TenantClient/UpdateTenant/main.go +++ b/internal/generated/snippets/talent/apiv4/TenantClient/UpdateTenant/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewTenantClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.UpdateTenantRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/CreateApplication/main.go b/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/CreateApplication/main.go index 3f12b25d8d15..e89a32d83288 100644 --- a/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/CreateApplication/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/CreateApplication/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewApplicationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateApplicationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/DeleteApplication/main.go b/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/DeleteApplication/main.go index 2bc6e34e0494..17690df294c4 100644 --- a/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/DeleteApplication/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/DeleteApplication/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.DeleteApplicationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/GetApplication/main.go b/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/GetApplication/main.go index d008aca5d50c..df80a5ca53bb 100644 --- a/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/GetApplication/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/GetApplication/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewApplicationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.GetApplicationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/ListApplications/main.go b/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/ListApplications/main.go index c08d17b5a13a..830439bcd926 100644 --- a/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/ListApplications/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/ListApplications/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewApplicationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.ListApplicationsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/UpdateApplication/main.go b/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/UpdateApplication/main.go index 5d7a302ea802..4a9a775c5445 100644 --- a/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/UpdateApplication/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/ApplicationClient/UpdateApplication/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewApplicationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.UpdateApplicationRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/CompanyClient/CreateCompany/main.go b/internal/generated/snippets/talent/apiv4beta1/CompanyClient/CreateCompany/main.go index cf9ab67f3075..a59aafd237ff 100644 --- a/internal/generated/snippets/talent/apiv4beta1/CompanyClient/CreateCompany/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/CompanyClient/CreateCompany/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewCompanyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateCompanyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/CompanyClient/DeleteCompany/main.go b/internal/generated/snippets/talent/apiv4beta1/CompanyClient/DeleteCompany/main.go index f42bf2520c36..d3533dd086fb 100644 --- a/internal/generated/snippets/talent/apiv4beta1/CompanyClient/DeleteCompany/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/CompanyClient/DeleteCompany/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.DeleteCompanyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/CompanyClient/GetCompany/main.go b/internal/generated/snippets/talent/apiv4beta1/CompanyClient/GetCompany/main.go index 0388ab93843c..ab341ecde9bd 100644 --- a/internal/generated/snippets/talent/apiv4beta1/CompanyClient/GetCompany/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/CompanyClient/GetCompany/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewCompanyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.GetCompanyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/CompanyClient/ListCompanies/main.go b/internal/generated/snippets/talent/apiv4beta1/CompanyClient/ListCompanies/main.go index 39649656c735..89ebdbabf38d 100644 --- a/internal/generated/snippets/talent/apiv4beta1/CompanyClient/ListCompanies/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/CompanyClient/ListCompanies/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewCompanyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.ListCompaniesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/CompanyClient/UpdateCompany/main.go b/internal/generated/snippets/talent/apiv4beta1/CompanyClient/UpdateCompany/main.go index fc4b747fa00e..dc9294807d85 100644 --- a/internal/generated/snippets/talent/apiv4beta1/CompanyClient/UpdateCompany/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/CompanyClient/UpdateCompany/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewCompanyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.UpdateCompanyRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/CompletionClient/CompleteQuery/main.go b/internal/generated/snippets/talent/apiv4beta1/CompletionClient/CompleteQuery/main.go index 66827c6dc49c..5d190253293f 100644 --- a/internal/generated/snippets/talent/apiv4beta1/CompletionClient/CompleteQuery/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/CompletionClient/CompleteQuery/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewCompletionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CompleteQueryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/EventClient/CreateClientEvent/main.go b/internal/generated/snippets/talent/apiv4beta1/EventClient/CreateClientEvent/main.go index 9bd965718d76..73a7f735bc76 100644 --- a/internal/generated/snippets/talent/apiv4beta1/EventClient/CreateClientEvent/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/EventClient/CreateClientEvent/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateClientEventRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/JobClient/BatchCreateJobs/main.go b/internal/generated/snippets/talent/apiv4beta1/JobClient/BatchCreateJobs/main.go index a13d2fb2048f..504dc20a04cd 100644 --- a/internal/generated/snippets/talent/apiv4beta1/JobClient/BatchCreateJobs/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/JobClient/BatchCreateJobs/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.BatchCreateJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/JobClient/BatchDeleteJobs/main.go b/internal/generated/snippets/talent/apiv4beta1/JobClient/BatchDeleteJobs/main.go index f8b8aceb5b2f..5218e751fd28 100644 --- a/internal/generated/snippets/talent/apiv4beta1/JobClient/BatchDeleteJobs/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/JobClient/BatchDeleteJobs/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.BatchDeleteJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/JobClient/BatchUpdateJobs/main.go b/internal/generated/snippets/talent/apiv4beta1/JobClient/BatchUpdateJobs/main.go index 538ed734471f..9ea1875ec2de 100644 --- a/internal/generated/snippets/talent/apiv4beta1/JobClient/BatchUpdateJobs/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/JobClient/BatchUpdateJobs/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.BatchUpdateJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/JobClient/CreateJob/main.go b/internal/generated/snippets/talent/apiv4beta1/JobClient/CreateJob/main.go index 7807694abe2d..9df8dba7e22e 100644 --- a/internal/generated/snippets/talent/apiv4beta1/JobClient/CreateJob/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/JobClient/CreateJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/JobClient/DeleteJob/main.go b/internal/generated/snippets/talent/apiv4beta1/JobClient/DeleteJob/main.go index 3ec38b38f1e9..6e91b74a2c5e 100644 --- a/internal/generated/snippets/talent/apiv4beta1/JobClient/DeleteJob/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/JobClient/DeleteJob/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.DeleteJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/JobClient/GetJob/main.go b/internal/generated/snippets/talent/apiv4beta1/JobClient/GetJob/main.go index 5d6d3abe3759..ea38f4f97b0c 100644 --- a/internal/generated/snippets/talent/apiv4beta1/JobClient/GetJob/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/JobClient/GetJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.GetJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/JobClient/ListJobs/main.go b/internal/generated/snippets/talent/apiv4beta1/JobClient/ListJobs/main.go index 1b30391e6f0d..55168731fce9 100644 --- a/internal/generated/snippets/talent/apiv4beta1/JobClient/ListJobs/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/JobClient/ListJobs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.ListJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/JobClient/SearchJobs/main.go b/internal/generated/snippets/talent/apiv4beta1/JobClient/SearchJobs/main.go index b57c49ea95af..704bee3bb1b5 100644 --- a/internal/generated/snippets/talent/apiv4beta1/JobClient/SearchJobs/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/JobClient/SearchJobs/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.SearchJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/JobClient/SearchJobsForAlert/main.go b/internal/generated/snippets/talent/apiv4beta1/JobClient/SearchJobsForAlert/main.go index 73e2e2408a3d..8b2005899b1e 100644 --- a/internal/generated/snippets/talent/apiv4beta1/JobClient/SearchJobsForAlert/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/JobClient/SearchJobsForAlert/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.SearchJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/JobClient/UpdateJob/main.go b/internal/generated/snippets/talent/apiv4beta1/JobClient/UpdateJob/main.go index b81c7e7073ed..b8deff049eb9 100644 --- a/internal/generated/snippets/talent/apiv4beta1/JobClient/UpdateJob/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/JobClient/UpdateJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.UpdateJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/ProfileClient/CreateProfile/main.go b/internal/generated/snippets/talent/apiv4beta1/ProfileClient/CreateProfile/main.go index a6d1a22825c2..aa7d88da3cf8 100644 --- a/internal/generated/snippets/talent/apiv4beta1/ProfileClient/CreateProfile/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/ProfileClient/CreateProfile/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewProfileClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateProfileRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/ProfileClient/DeleteProfile/main.go b/internal/generated/snippets/talent/apiv4beta1/ProfileClient/DeleteProfile/main.go index 13416400c413..afc7f62a14db 100644 --- a/internal/generated/snippets/talent/apiv4beta1/ProfileClient/DeleteProfile/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/ProfileClient/DeleteProfile/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.DeleteProfileRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/ProfileClient/GetProfile/main.go b/internal/generated/snippets/talent/apiv4beta1/ProfileClient/GetProfile/main.go index c247699a395b..66bb45712d3b 100644 --- a/internal/generated/snippets/talent/apiv4beta1/ProfileClient/GetProfile/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/ProfileClient/GetProfile/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewProfileClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.GetProfileRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/ProfileClient/ListProfiles/main.go b/internal/generated/snippets/talent/apiv4beta1/ProfileClient/ListProfiles/main.go index 006bac47b190..ffc19cca614d 100644 --- a/internal/generated/snippets/talent/apiv4beta1/ProfileClient/ListProfiles/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/ProfileClient/ListProfiles/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewProfileClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.ListProfilesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/ProfileClient/SearchProfiles/main.go b/internal/generated/snippets/talent/apiv4beta1/ProfileClient/SearchProfiles/main.go index 4a2f20910feb..a974b52b9705 100644 --- a/internal/generated/snippets/talent/apiv4beta1/ProfileClient/SearchProfiles/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/ProfileClient/SearchProfiles/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewProfileClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.SearchProfilesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/ProfileClient/UpdateProfile/main.go b/internal/generated/snippets/talent/apiv4beta1/ProfileClient/UpdateProfile/main.go index ea7f0cbc74b4..f5f3b6668783 100644 --- a/internal/generated/snippets/talent/apiv4beta1/ProfileClient/UpdateProfile/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/ProfileClient/UpdateProfile/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewProfileClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.UpdateProfileRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/TenantClient/CreateTenant/main.go b/internal/generated/snippets/talent/apiv4beta1/TenantClient/CreateTenant/main.go index fc6f87036ed3..8ed822fb1dbe 100644 --- a/internal/generated/snippets/talent/apiv4beta1/TenantClient/CreateTenant/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/TenantClient/CreateTenant/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewTenantClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateTenantRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/TenantClient/DeleteTenant/main.go b/internal/generated/snippets/talent/apiv4beta1/TenantClient/DeleteTenant/main.go index 02a0271ee0b2..291884066c2f 100644 --- a/internal/generated/snippets/talent/apiv4beta1/TenantClient/DeleteTenant/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/TenantClient/DeleteTenant/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.DeleteTenantRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/TenantClient/GetTenant/main.go b/internal/generated/snippets/talent/apiv4beta1/TenantClient/GetTenant/main.go index 6f721d56c2ef..1495703f97af 100644 --- a/internal/generated/snippets/talent/apiv4beta1/TenantClient/GetTenant/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/TenantClient/GetTenant/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewTenantClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.GetTenantRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/TenantClient/ListTenants/main.go b/internal/generated/snippets/talent/apiv4beta1/TenantClient/ListTenants/main.go index 027b061cb606..1044a1509bb2 100644 --- a/internal/generated/snippets/talent/apiv4beta1/TenantClient/ListTenants/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/TenantClient/ListTenants/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewTenantClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.ListTenantsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/talent/apiv4beta1/TenantClient/UpdateTenant/main.go b/internal/generated/snippets/talent/apiv4beta1/TenantClient/UpdateTenant/main.go index 7be0f7d173b4..126cae71b7a3 100644 --- a/internal/generated/snippets/talent/apiv4beta1/TenantClient/UpdateTenant/main.go +++ b/internal/generated/snippets/talent/apiv4beta1/TenantClient/UpdateTenant/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewTenantClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.UpdateTenantRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/texttospeech/apiv1/Client/ListVoices/main.go b/internal/generated/snippets/texttospeech/apiv1/Client/ListVoices/main.go index 1eb362b4a2b0..52c298e9fa9e 100644 --- a/internal/generated/snippets/texttospeech/apiv1/Client/ListVoices/main.go +++ b/internal/generated/snippets/texttospeech/apiv1/Client/ListVoices/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import texttospeechpb "google.golang.org/genproto/googleapis/cloud/texttospeech/v1" - ctx := context.Background() c, err := texttospeech.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &texttospeechpb.ListVoicesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/texttospeech/apiv1/Client/SynthesizeSpeech/main.go b/internal/generated/snippets/texttospeech/apiv1/Client/SynthesizeSpeech/main.go index 18ef1cdeb744..c35284dcf867 100644 --- a/internal/generated/snippets/texttospeech/apiv1/Client/SynthesizeSpeech/main.go +++ b/internal/generated/snippets/texttospeech/apiv1/Client/SynthesizeSpeech/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import texttospeechpb "google.golang.org/genproto/googleapis/cloud/texttospeech/v1" - ctx := context.Background() c, err := texttospeech.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &texttospeechpb.SynthesizeSpeechRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/trace/apiv1/Client/GetTrace/main.go b/internal/generated/snippets/trace/apiv1/Client/GetTrace/main.go index ad492373e4b9..6cd545249208 100644 --- a/internal/generated/snippets/trace/apiv1/Client/GetTrace/main.go +++ b/internal/generated/snippets/trace/apiv1/Client/GetTrace/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cloudtracepb "google.golang.org/genproto/googleapis/devtools/cloudtrace/v1" - ctx := context.Background() c, err := trace.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudtracepb.GetTraceRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/trace/apiv1/Client/ListTraces/main.go b/internal/generated/snippets/trace/apiv1/Client/ListTraces/main.go index 9813eb9707ad..51f5d25ffdee 100644 --- a/internal/generated/snippets/trace/apiv1/Client/ListTraces/main.go +++ b/internal/generated/snippets/trace/apiv1/Client/ListTraces/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import cloudtracepb "google.golang.org/genproto/googleapis/devtools/cloudtrace/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := trace.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudtracepb.ListTracesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/trace/apiv1/Client/PatchTraces/main.go b/internal/generated/snippets/trace/apiv1/Client/PatchTraces/main.go index c0a7a8cc3716..aa444f668ab9 100644 --- a/internal/generated/snippets/trace/apiv1/Client/PatchTraces/main.go +++ b/internal/generated/snippets/trace/apiv1/Client/PatchTraces/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudtracepb.PatchTracesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/trace/apiv2/Client/BatchWriteSpans/main.go b/internal/generated/snippets/trace/apiv2/Client/BatchWriteSpans/main.go index cfbdecc95812..c4c542eff4ea 100644 --- a/internal/generated/snippets/trace/apiv2/Client/BatchWriteSpans/main.go +++ b/internal/generated/snippets/trace/apiv2/Client/BatchWriteSpans/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudtracepb.BatchWriteSpansRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/trace/apiv2/Client/CreateSpan/main.go b/internal/generated/snippets/trace/apiv2/Client/CreateSpan/main.go index 59c3becc3177..fcf2b8416a1d 100644 --- a/internal/generated/snippets/trace/apiv2/Client/CreateSpan/main.go +++ b/internal/generated/snippets/trace/apiv2/Client/CreateSpan/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import cloudtracepb "google.golang.org/genproto/googleapis/devtools/cloudtrace/v2" - ctx := context.Background() c, err := trace.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudtracepb.Span{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/translate/apiv3/TranslationClient/BatchTranslateText/main.go b/internal/generated/snippets/translate/apiv3/TranslationClient/BatchTranslateText/main.go index 9f93a4cf7ede..8533547b4cab 100644 --- a/internal/generated/snippets/translate/apiv3/TranslationClient/BatchTranslateText/main.go +++ b/internal/generated/snippets/translate/apiv3/TranslationClient/BatchTranslateText/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" - ctx := context.Background() c, err := translate.NewTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &translatepb.BatchTranslateTextRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/translate/apiv3/TranslationClient/CreateGlossary/main.go b/internal/generated/snippets/translate/apiv3/TranslationClient/CreateGlossary/main.go index fa561e6480c7..95e31e78d721 100644 --- a/internal/generated/snippets/translate/apiv3/TranslationClient/CreateGlossary/main.go +++ b/internal/generated/snippets/translate/apiv3/TranslationClient/CreateGlossary/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" - ctx := context.Background() c, err := translate.NewTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &translatepb.CreateGlossaryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/translate/apiv3/TranslationClient/DeleteGlossary/main.go b/internal/generated/snippets/translate/apiv3/TranslationClient/DeleteGlossary/main.go index 9c8f9d180ade..329792efa436 100644 --- a/internal/generated/snippets/translate/apiv3/TranslationClient/DeleteGlossary/main.go +++ b/internal/generated/snippets/translate/apiv3/TranslationClient/DeleteGlossary/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" - ctx := context.Background() c, err := translate.NewTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &translatepb.DeleteGlossaryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/translate/apiv3/TranslationClient/DetectLanguage/main.go b/internal/generated/snippets/translate/apiv3/TranslationClient/DetectLanguage/main.go index a697288ff9c1..f90220f10974 100644 --- a/internal/generated/snippets/translate/apiv3/TranslationClient/DetectLanguage/main.go +++ b/internal/generated/snippets/translate/apiv3/TranslationClient/DetectLanguage/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" - ctx := context.Background() c, err := translate.NewTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &translatepb.DetectLanguageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/translate/apiv3/TranslationClient/GetGlossary/main.go b/internal/generated/snippets/translate/apiv3/TranslationClient/GetGlossary/main.go index ca272b953819..bffb9b2803a9 100644 --- a/internal/generated/snippets/translate/apiv3/TranslationClient/GetGlossary/main.go +++ b/internal/generated/snippets/translate/apiv3/TranslationClient/GetGlossary/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" - ctx := context.Background() c, err := translate.NewTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &translatepb.GetGlossaryRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/translate/apiv3/TranslationClient/GetSupportedLanguages/main.go b/internal/generated/snippets/translate/apiv3/TranslationClient/GetSupportedLanguages/main.go index 3ec7586ecff9..02a661f497f6 100644 --- a/internal/generated/snippets/translate/apiv3/TranslationClient/GetSupportedLanguages/main.go +++ b/internal/generated/snippets/translate/apiv3/TranslationClient/GetSupportedLanguages/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" - ctx := context.Background() c, err := translate.NewTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &translatepb.GetSupportedLanguagesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/translate/apiv3/TranslationClient/ListGlossaries/main.go b/internal/generated/snippets/translate/apiv3/TranslationClient/ListGlossaries/main.go index b8aa9f5188e7..5ada71d8865f 100644 --- a/internal/generated/snippets/translate/apiv3/TranslationClient/ListGlossaries/main.go +++ b/internal/generated/snippets/translate/apiv3/TranslationClient/ListGlossaries/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := translate.NewTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &translatepb.ListGlossariesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/translate/apiv3/TranslationClient/TranslateText/main.go b/internal/generated/snippets/translate/apiv3/TranslationClient/TranslateText/main.go index ec421b1e1e61..3282b6aa2fb9 100644 --- a/internal/generated/snippets/translate/apiv3/TranslationClient/TranslateText/main.go +++ b/internal/generated/snippets/translate/apiv3/TranslationClient/TranslateText/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" - ctx := context.Background() c, err := translate.NewTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &translatepb.TranslateTextRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/video/transcoder/apiv1beta1/Client/CreateJob/main.go b/internal/generated/snippets/video/transcoder/apiv1beta1/Client/CreateJob/main.go index af6f0136172e..1f4bcc50419b 100644 --- a/internal/generated/snippets/video/transcoder/apiv1beta1/Client/CreateJob/main.go +++ b/internal/generated/snippets/video/transcoder/apiv1beta1/Client/CreateJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import transcoderpb "google.golang.org/genproto/googleapis/cloud/video/transcoder/v1beta1" - ctx := context.Background() c, err := transcoder.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &transcoderpb.CreateJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/video/transcoder/apiv1beta1/Client/CreateJobTemplate/main.go b/internal/generated/snippets/video/transcoder/apiv1beta1/Client/CreateJobTemplate/main.go index 6d5352b8691c..04f6b744e65c 100644 --- a/internal/generated/snippets/video/transcoder/apiv1beta1/Client/CreateJobTemplate/main.go +++ b/internal/generated/snippets/video/transcoder/apiv1beta1/Client/CreateJobTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import transcoderpb "google.golang.org/genproto/googleapis/cloud/video/transcoder/v1beta1" - ctx := context.Background() c, err := transcoder.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &transcoderpb.CreateJobTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/video/transcoder/apiv1beta1/Client/DeleteJob/main.go b/internal/generated/snippets/video/transcoder/apiv1beta1/Client/DeleteJob/main.go index 64890b8e8cec..4285af6f28c7 100644 --- a/internal/generated/snippets/video/transcoder/apiv1beta1/Client/DeleteJob/main.go +++ b/internal/generated/snippets/video/transcoder/apiv1beta1/Client/DeleteJob/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &transcoderpb.DeleteJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/video/transcoder/apiv1beta1/Client/DeleteJobTemplate/main.go b/internal/generated/snippets/video/transcoder/apiv1beta1/Client/DeleteJobTemplate/main.go index 40a3c7353d4a..5f666d53b7c9 100644 --- a/internal/generated/snippets/video/transcoder/apiv1beta1/Client/DeleteJobTemplate/main.go +++ b/internal/generated/snippets/video/transcoder/apiv1beta1/Client/DeleteJobTemplate/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &transcoderpb.DeleteJobTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/video/transcoder/apiv1beta1/Client/GetJob/main.go b/internal/generated/snippets/video/transcoder/apiv1beta1/Client/GetJob/main.go index 9291db4422f5..67956e091db8 100644 --- a/internal/generated/snippets/video/transcoder/apiv1beta1/Client/GetJob/main.go +++ b/internal/generated/snippets/video/transcoder/apiv1beta1/Client/GetJob/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import transcoderpb "google.golang.org/genproto/googleapis/cloud/video/transcoder/v1beta1" - ctx := context.Background() c, err := transcoder.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &transcoderpb.GetJobRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/video/transcoder/apiv1beta1/Client/GetJobTemplate/main.go b/internal/generated/snippets/video/transcoder/apiv1beta1/Client/GetJobTemplate/main.go index 0eafb358f50e..c666df389b28 100644 --- a/internal/generated/snippets/video/transcoder/apiv1beta1/Client/GetJobTemplate/main.go +++ b/internal/generated/snippets/video/transcoder/apiv1beta1/Client/GetJobTemplate/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import transcoderpb "google.golang.org/genproto/googleapis/cloud/video/transcoder/v1beta1" - ctx := context.Background() c, err := transcoder.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &transcoderpb.GetJobTemplateRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/video/transcoder/apiv1beta1/Client/ListJobTemplates/main.go b/internal/generated/snippets/video/transcoder/apiv1beta1/Client/ListJobTemplates/main.go index bfce95c4a8b7..711990e26aa5 100644 --- a/internal/generated/snippets/video/transcoder/apiv1beta1/Client/ListJobTemplates/main.go +++ b/internal/generated/snippets/video/transcoder/apiv1beta1/Client/ListJobTemplates/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import transcoderpb "google.golang.org/genproto/googleapis/cloud/video/transcoder/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := transcoder.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &transcoderpb.ListJobTemplatesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/video/transcoder/apiv1beta1/Client/ListJobs/main.go b/internal/generated/snippets/video/transcoder/apiv1beta1/Client/ListJobs/main.go index 9ca6c66031ed..f9935438ebc1 100644 --- a/internal/generated/snippets/video/transcoder/apiv1beta1/Client/ListJobs/main.go +++ b/internal/generated/snippets/video/transcoder/apiv1beta1/Client/ListJobs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import transcoderpb "google.golang.org/genproto/googleapis/cloud/video/transcoder/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := transcoder.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &transcoderpb.ListJobsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/videointelligence/apiv1/Client/AnnotateVideo/main.go b/internal/generated/snippets/videointelligence/apiv1/Client/AnnotateVideo/main.go index 32f89f9c9889..2df892806824 100644 --- a/internal/generated/snippets/videointelligence/apiv1/Client/AnnotateVideo/main.go +++ b/internal/generated/snippets/videointelligence/apiv1/Client/AnnotateVideo/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import videointelligencepb "google.golang.org/genproto/googleapis/cloud/videointelligence/v1" - ctx := context.Background() c, err := videointelligence.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &videointelligencepb.AnnotateVideoRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/videointelligence/apiv1beta2/Client/AnnotateVideo/main.go b/internal/generated/snippets/videointelligence/apiv1beta2/Client/AnnotateVideo/main.go index 222c33e1f999..72ef85c63955 100644 --- a/internal/generated/snippets/videointelligence/apiv1beta2/Client/AnnotateVideo/main.go +++ b/internal/generated/snippets/videointelligence/apiv1beta2/Client/AnnotateVideo/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import videointelligencepb "google.golang.org/genproto/googleapis/cloud/videointelligence/v1beta2" - ctx := context.Background() c, err := videointelligence.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &videointelligencepb.AnnotateVideoRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ImageAnnotatorClient/AsyncBatchAnnotateFiles/main.go b/internal/generated/snippets/vision/apiv1/ImageAnnotatorClient/AsyncBatchAnnotateFiles/main.go index 54b5b26b6af3..8ebb980f9b42 100644 --- a/internal/generated/snippets/vision/apiv1/ImageAnnotatorClient/AsyncBatchAnnotateFiles/main.go +++ b/internal/generated/snippets/vision/apiv1/ImageAnnotatorClient/AsyncBatchAnnotateFiles/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewImageAnnotatorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.AsyncBatchAnnotateFilesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ImageAnnotatorClient/AsyncBatchAnnotateImages/main.go b/internal/generated/snippets/vision/apiv1/ImageAnnotatorClient/AsyncBatchAnnotateImages/main.go index 61c9a0d602b2..a476d558448a 100644 --- a/internal/generated/snippets/vision/apiv1/ImageAnnotatorClient/AsyncBatchAnnotateImages/main.go +++ b/internal/generated/snippets/vision/apiv1/ImageAnnotatorClient/AsyncBatchAnnotateImages/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewImageAnnotatorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.AsyncBatchAnnotateImagesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ImageAnnotatorClient/BatchAnnotateFiles/main.go b/internal/generated/snippets/vision/apiv1/ImageAnnotatorClient/BatchAnnotateFiles/main.go index 484d07937e69..cf3763a2d91d 100644 --- a/internal/generated/snippets/vision/apiv1/ImageAnnotatorClient/BatchAnnotateFiles/main.go +++ b/internal/generated/snippets/vision/apiv1/ImageAnnotatorClient/BatchAnnotateFiles/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewImageAnnotatorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.BatchAnnotateFilesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ImageAnnotatorClient/BatchAnnotateImages/main.go b/internal/generated/snippets/vision/apiv1/ImageAnnotatorClient/BatchAnnotateImages/main.go index 0d531647d7bd..b36e055f5dbc 100644 --- a/internal/generated/snippets/vision/apiv1/ImageAnnotatorClient/BatchAnnotateImages/main.go +++ b/internal/generated/snippets/vision/apiv1/ImageAnnotatorClient/BatchAnnotateImages/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewImageAnnotatorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.BatchAnnotateImagesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/AddProductToProductSet/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/AddProductToProductSet/main.go index 9eed5da2ba56..1b3162e10516 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/AddProductToProductSet/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/AddProductToProductSet/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.AddProductToProductSetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/CreateProduct/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/CreateProduct/main.go index 79997ed2beb5..ec7ff2917cff 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/CreateProduct/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/CreateProduct/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.CreateProductRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/CreateProductSet/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/CreateProductSet/main.go index b76623308ff2..1b3ae345a649 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/CreateProductSet/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/CreateProductSet/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.CreateProductSetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/CreateReferenceImage/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/CreateReferenceImage/main.go index b057f8af06fc..8f0426d259d8 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/CreateReferenceImage/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/CreateReferenceImage/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.CreateReferenceImageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/DeleteProduct/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/DeleteProduct/main.go index 1c27fdb66d7e..fc054d5276d8 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/DeleteProduct/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/DeleteProduct/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.DeleteProductRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/DeleteProductSet/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/DeleteProductSet/main.go index a37b9e939286..b612fcb0e67f 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/DeleteProductSet/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/DeleteProductSet/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.DeleteProductSetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/DeleteReferenceImage/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/DeleteReferenceImage/main.go index 736bc8283dbd..3f9486f5700e 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/DeleteReferenceImage/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/DeleteReferenceImage/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.DeleteReferenceImageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/GetProduct/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/GetProduct/main.go index 00209617ae49..c926dc768fcc 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/GetProduct/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/GetProduct/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.GetProductRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/GetProductSet/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/GetProductSet/main.go index 58bcea2a0bae..3a1f2a2a1988 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/GetProductSet/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/GetProductSet/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.GetProductSetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/GetReferenceImage/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/GetReferenceImage/main.go index 9566db2eca11..3a0538ef6a10 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/GetReferenceImage/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/GetReferenceImage/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.GetReferenceImageRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/ImportProductSets/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/ImportProductSets/main.go index 994d93302891..e8f443bfe864 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/ImportProductSets/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/ImportProductSets/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.ImportProductSetsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/ListProductSets/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/ListProductSets/main.go index 9d8d7abdf3c9..6d2ee1d3ad32 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/ListProductSets/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/ListProductSets/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.ListProductSetsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/ListProducts/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/ListProducts/main.go index edb62bd20210..d5d413f8efaa 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/ListProducts/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/ListProducts/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.ListProductsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/ListProductsInProductSet/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/ListProductsInProductSet/main.go index 52dfdb93089f..86c9dfcfb016 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/ListProductsInProductSet/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/ListProductsInProductSet/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.ListProductsInProductSetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/ListReferenceImages/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/ListReferenceImages/main.go index dbf7ff07a883..aba3d616345a 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/ListReferenceImages/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/ListReferenceImages/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.ListReferenceImagesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/PurgeProducts/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/PurgeProducts/main.go index 0779c1dfa166..c366862429f6 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/PurgeProducts/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/PurgeProducts/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.PurgeProductsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/RemoveProductFromProductSet/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/RemoveProductFromProductSet/main.go index 5a46e149bb63..201e865efd5d 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/RemoveProductFromProductSet/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/RemoveProductFromProductSet/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.RemoveProductFromProductSetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/UpdateProduct/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/UpdateProduct/main.go index d6b30735127f..ced4bd669b73 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/UpdateProduct/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/UpdateProduct/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.UpdateProductRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1/ProductSearchClient/UpdateProductSet/main.go b/internal/generated/snippets/vision/apiv1/ProductSearchClient/UpdateProductSet/main.go index 3d0452164583..00e9b2dcd7e9 100644 --- a/internal/generated/snippets/vision/apiv1/ProductSearchClient/UpdateProductSet/main.go +++ b/internal/generated/snippets/vision/apiv1/ProductSearchClient/UpdateProductSet/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.UpdateProductSetRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/vision/apiv1p1beta1/ImageAnnotatorClient/BatchAnnotateImages/main.go b/internal/generated/snippets/vision/apiv1p1beta1/ImageAnnotatorClient/BatchAnnotateImages/main.go index 0a0e1c014aac..33207e920244 100644 --- a/internal/generated/snippets/vision/apiv1p1beta1/ImageAnnotatorClient/BatchAnnotateImages/main.go +++ b/internal/generated/snippets/vision/apiv1p1beta1/ImageAnnotatorClient/BatchAnnotateImages/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1p1beta1" - ctx := context.Background() c, err := vision.NewImageAnnotatorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.BatchAnnotateImagesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/webrisk/apiv1/Client/ComputeThreatListDiff/main.go b/internal/generated/snippets/webrisk/apiv1/Client/ComputeThreatListDiff/main.go index 095cab7b1655..1397eb78e9f6 100644 --- a/internal/generated/snippets/webrisk/apiv1/Client/ComputeThreatListDiff/main.go +++ b/internal/generated/snippets/webrisk/apiv1/Client/ComputeThreatListDiff/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import webriskpb "google.golang.org/genproto/googleapis/cloud/webrisk/v1" - ctx := context.Background() c, err := webrisk.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &webriskpb.ComputeThreatListDiffRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/webrisk/apiv1/Client/CreateSubmission/main.go b/internal/generated/snippets/webrisk/apiv1/Client/CreateSubmission/main.go index 2cd9a12e8d88..579993758958 100644 --- a/internal/generated/snippets/webrisk/apiv1/Client/CreateSubmission/main.go +++ b/internal/generated/snippets/webrisk/apiv1/Client/CreateSubmission/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import webriskpb "google.golang.org/genproto/googleapis/cloud/webrisk/v1" - ctx := context.Background() c, err := webrisk.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &webriskpb.CreateSubmissionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/webrisk/apiv1/Client/SearchHashes/main.go b/internal/generated/snippets/webrisk/apiv1/Client/SearchHashes/main.go index 75e35a8d6339..b84137e252ad 100644 --- a/internal/generated/snippets/webrisk/apiv1/Client/SearchHashes/main.go +++ b/internal/generated/snippets/webrisk/apiv1/Client/SearchHashes/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import webriskpb "google.golang.org/genproto/googleapis/cloud/webrisk/v1" - ctx := context.Background() c, err := webrisk.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &webriskpb.SearchHashesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/webrisk/apiv1/Client/SearchUris/main.go b/internal/generated/snippets/webrisk/apiv1/Client/SearchUris/main.go index ee80b660a8e2..e808b1390206 100644 --- a/internal/generated/snippets/webrisk/apiv1/Client/SearchUris/main.go +++ b/internal/generated/snippets/webrisk/apiv1/Client/SearchUris/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import webriskpb "google.golang.org/genproto/googleapis/cloud/webrisk/v1" - ctx := context.Background() c, err := webrisk.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &webriskpb.SearchUrisRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/webrisk/apiv1beta1/WebRiskServiceV1Beta1Client/ComputeThreatListDiff/main.go b/internal/generated/snippets/webrisk/apiv1beta1/WebRiskServiceV1Beta1Client/ComputeThreatListDiff/main.go index e989f7748bb3..4901be708deb 100644 --- a/internal/generated/snippets/webrisk/apiv1beta1/WebRiskServiceV1Beta1Client/ComputeThreatListDiff/main.go +++ b/internal/generated/snippets/webrisk/apiv1beta1/WebRiskServiceV1Beta1Client/ComputeThreatListDiff/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import webriskpb "google.golang.org/genproto/googleapis/cloud/webrisk/v1beta1" - ctx := context.Background() c, err := webrisk.NewWebRiskServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &webriskpb.ComputeThreatListDiffRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/webrisk/apiv1beta1/WebRiskServiceV1Beta1Client/SearchHashes/main.go b/internal/generated/snippets/webrisk/apiv1beta1/WebRiskServiceV1Beta1Client/SearchHashes/main.go index 8b406e26acde..7b02dd20644c 100644 --- a/internal/generated/snippets/webrisk/apiv1beta1/WebRiskServiceV1Beta1Client/SearchHashes/main.go +++ b/internal/generated/snippets/webrisk/apiv1beta1/WebRiskServiceV1Beta1Client/SearchHashes/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import webriskpb "google.golang.org/genproto/googleapis/cloud/webrisk/v1beta1" - ctx := context.Background() c, err := webrisk.NewWebRiskServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &webriskpb.SearchHashesRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/webrisk/apiv1beta1/WebRiskServiceV1Beta1Client/SearchUris/main.go b/internal/generated/snippets/webrisk/apiv1beta1/WebRiskServiceV1Beta1Client/SearchUris/main.go index 6b3e870e2bcf..602f933254b0 100644 --- a/internal/generated/snippets/webrisk/apiv1beta1/WebRiskServiceV1Beta1Client/SearchUris/main.go +++ b/internal/generated/snippets/webrisk/apiv1beta1/WebRiskServiceV1Beta1Client/SearchUris/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import webriskpb "google.golang.org/genproto/googleapis/cloud/webrisk/v1beta1" - ctx := context.Background() c, err := webrisk.NewWebRiskServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &webriskpb.SearchUrisRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/websecurityscanner/apiv1/Client/CreateScanConfig/main.go b/internal/generated/snippets/websecurityscanner/apiv1/Client/CreateScanConfig/main.go index 22afc18bdd29..ee42e58a616a 100644 --- a/internal/generated/snippets/websecurityscanner/apiv1/Client/CreateScanConfig/main.go +++ b/internal/generated/snippets/websecurityscanner/apiv1/Client/CreateScanConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.CreateScanConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/websecurityscanner/apiv1/Client/DeleteScanConfig/main.go b/internal/generated/snippets/websecurityscanner/apiv1/Client/DeleteScanConfig/main.go index 7647ab37022b..ceba888d837b 100644 --- a/internal/generated/snippets/websecurityscanner/apiv1/Client/DeleteScanConfig/main.go +++ b/internal/generated/snippets/websecurityscanner/apiv1/Client/DeleteScanConfig/main.go @@ -29,6 +29,7 @@ func main() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.DeleteScanConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/websecurityscanner/apiv1/Client/GetFinding/main.go b/internal/generated/snippets/websecurityscanner/apiv1/Client/GetFinding/main.go index a0216cc6c911..689b410f927a 100644 --- a/internal/generated/snippets/websecurityscanner/apiv1/Client/GetFinding/main.go +++ b/internal/generated/snippets/websecurityscanner/apiv1/Client/GetFinding/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.GetFindingRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/websecurityscanner/apiv1/Client/GetScanConfig/main.go b/internal/generated/snippets/websecurityscanner/apiv1/Client/GetScanConfig/main.go index 8a6b47b54e11..8e6d4a0b62f3 100644 --- a/internal/generated/snippets/websecurityscanner/apiv1/Client/GetScanConfig/main.go +++ b/internal/generated/snippets/websecurityscanner/apiv1/Client/GetScanConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.GetScanConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/websecurityscanner/apiv1/Client/GetScanRun/main.go b/internal/generated/snippets/websecurityscanner/apiv1/Client/GetScanRun/main.go index 111decbb850f..361e14ce24c8 100644 --- a/internal/generated/snippets/websecurityscanner/apiv1/Client/GetScanRun/main.go +++ b/internal/generated/snippets/websecurityscanner/apiv1/Client/GetScanRun/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.GetScanRunRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/websecurityscanner/apiv1/Client/ListCrawledUrls/main.go b/internal/generated/snippets/websecurityscanner/apiv1/Client/ListCrawledUrls/main.go index 71096d5224c6..4a8102b8efb1 100644 --- a/internal/generated/snippets/websecurityscanner/apiv1/Client/ListCrawledUrls/main.go +++ b/internal/generated/snippets/websecurityscanner/apiv1/Client/ListCrawledUrls/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.ListCrawledUrlsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/websecurityscanner/apiv1/Client/ListFindingTypeStats/main.go b/internal/generated/snippets/websecurityscanner/apiv1/Client/ListFindingTypeStats/main.go index 57a340c0fbd1..8591e63845ee 100644 --- a/internal/generated/snippets/websecurityscanner/apiv1/Client/ListFindingTypeStats/main.go +++ b/internal/generated/snippets/websecurityscanner/apiv1/Client/ListFindingTypeStats/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.ListFindingTypeStatsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/websecurityscanner/apiv1/Client/ListFindings/main.go b/internal/generated/snippets/websecurityscanner/apiv1/Client/ListFindings/main.go index e2eac65cf695..5c97862257c5 100644 --- a/internal/generated/snippets/websecurityscanner/apiv1/Client/ListFindings/main.go +++ b/internal/generated/snippets/websecurityscanner/apiv1/Client/ListFindings/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.ListFindingsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/websecurityscanner/apiv1/Client/ListScanConfigs/main.go b/internal/generated/snippets/websecurityscanner/apiv1/Client/ListScanConfigs/main.go index 9790fd1bc3ca..aae76055012c 100644 --- a/internal/generated/snippets/websecurityscanner/apiv1/Client/ListScanConfigs/main.go +++ b/internal/generated/snippets/websecurityscanner/apiv1/Client/ListScanConfigs/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.ListScanConfigsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/websecurityscanner/apiv1/Client/ListScanRuns/main.go b/internal/generated/snippets/websecurityscanner/apiv1/Client/ListScanRuns/main.go index a2722ba87d0a..7b32342ec665 100644 --- a/internal/generated/snippets/websecurityscanner/apiv1/Client/ListScanRuns/main.go +++ b/internal/generated/snippets/websecurityscanner/apiv1/Client/ListScanRuns/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.ListScanRunsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/websecurityscanner/apiv1/Client/StartScanRun/main.go b/internal/generated/snippets/websecurityscanner/apiv1/Client/StartScanRun/main.go index df1098a1aff8..5e82d6692e1b 100644 --- a/internal/generated/snippets/websecurityscanner/apiv1/Client/StartScanRun/main.go +++ b/internal/generated/snippets/websecurityscanner/apiv1/Client/StartScanRun/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.StartScanRunRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/websecurityscanner/apiv1/Client/StopScanRun/main.go b/internal/generated/snippets/websecurityscanner/apiv1/Client/StopScanRun/main.go index b79061572756..722b90ce1c79 100644 --- a/internal/generated/snippets/websecurityscanner/apiv1/Client/StopScanRun/main.go +++ b/internal/generated/snippets/websecurityscanner/apiv1/Client/StopScanRun/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.StopScanRunRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/websecurityscanner/apiv1/Client/UpdateScanConfig/main.go b/internal/generated/snippets/websecurityscanner/apiv1/Client/UpdateScanConfig/main.go index 9574fbfde941..616b5c982156 100644 --- a/internal/generated/snippets/websecurityscanner/apiv1/Client/UpdateScanConfig/main.go +++ b/internal/generated/snippets/websecurityscanner/apiv1/Client/UpdateScanConfig/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.UpdateScanConfigRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/workflows/apiv1beta/Client/CreateWorkflow/main.go b/internal/generated/snippets/workflows/apiv1beta/Client/CreateWorkflow/main.go index 6811f025bd69..d7314faf0e2f 100644 --- a/internal/generated/snippets/workflows/apiv1beta/Client/CreateWorkflow/main.go +++ b/internal/generated/snippets/workflows/apiv1beta/Client/CreateWorkflow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import workflowspb "google.golang.org/genproto/googleapis/cloud/workflows/v1beta" - ctx := context.Background() c, err := workflows.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &workflowspb.CreateWorkflowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/workflows/apiv1beta/Client/DeleteWorkflow/main.go b/internal/generated/snippets/workflows/apiv1beta/Client/DeleteWorkflow/main.go index 50d1f798f3ca..3797e4545d77 100644 --- a/internal/generated/snippets/workflows/apiv1beta/Client/DeleteWorkflow/main.go +++ b/internal/generated/snippets/workflows/apiv1beta/Client/DeleteWorkflow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import workflowspb "google.golang.org/genproto/googleapis/cloud/workflows/v1beta" - ctx := context.Background() c, err := workflows.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &workflowspb.DeleteWorkflowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/workflows/apiv1beta/Client/GetWorkflow/main.go b/internal/generated/snippets/workflows/apiv1beta/Client/GetWorkflow/main.go index 45b221765a98..83ebb6b503bb 100644 --- a/internal/generated/snippets/workflows/apiv1beta/Client/GetWorkflow/main.go +++ b/internal/generated/snippets/workflows/apiv1beta/Client/GetWorkflow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import workflowspb "google.golang.org/genproto/googleapis/cloud/workflows/v1beta" - ctx := context.Background() c, err := workflows.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &workflowspb.GetWorkflowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/workflows/apiv1beta/Client/ListWorkflows/main.go b/internal/generated/snippets/workflows/apiv1beta/Client/ListWorkflows/main.go index 05dd579c572c..0d973c051b9a 100644 --- a/internal/generated/snippets/workflows/apiv1beta/Client/ListWorkflows/main.go +++ b/internal/generated/snippets/workflows/apiv1beta/Client/ListWorkflows/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import workflowspb "google.golang.org/genproto/googleapis/cloud/workflows/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := workflows.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &workflowspb.ListWorkflowsRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/workflows/apiv1beta/Client/UpdateWorkflow/main.go b/internal/generated/snippets/workflows/apiv1beta/Client/UpdateWorkflow/main.go index 91d0628d765d..dc6be1d42cca 100644 --- a/internal/generated/snippets/workflows/apiv1beta/Client/UpdateWorkflow/main.go +++ b/internal/generated/snippets/workflows/apiv1beta/Client/UpdateWorkflow/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import workflowspb "google.golang.org/genproto/googleapis/cloud/workflows/v1beta" - ctx := context.Background() c, err := workflows.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &workflowspb.UpdateWorkflowRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/workflows/executions/apiv1beta/Client/CancelExecution/main.go b/internal/generated/snippets/workflows/executions/apiv1beta/Client/CancelExecution/main.go index 4143993a6b31..c982b0f08a3f 100644 --- a/internal/generated/snippets/workflows/executions/apiv1beta/Client/CancelExecution/main.go +++ b/internal/generated/snippets/workflows/executions/apiv1beta/Client/CancelExecution/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import executionspb "google.golang.org/genproto/googleapis/cloud/workflows/executions/v1beta" - ctx := context.Background() c, err := executions.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &executionspb.CancelExecutionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/workflows/executions/apiv1beta/Client/CreateExecution/main.go b/internal/generated/snippets/workflows/executions/apiv1beta/Client/CreateExecution/main.go index 473fec7bd242..a5582353006b 100644 --- a/internal/generated/snippets/workflows/executions/apiv1beta/Client/CreateExecution/main.go +++ b/internal/generated/snippets/workflows/executions/apiv1beta/Client/CreateExecution/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import executionspb "google.golang.org/genproto/googleapis/cloud/workflows/executions/v1beta" - ctx := context.Background() c, err := executions.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &executionspb.CreateExecutionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/workflows/executions/apiv1beta/Client/GetExecution/main.go b/internal/generated/snippets/workflows/executions/apiv1beta/Client/GetExecution/main.go index f1d14e95a9cb..a5307de211b4 100644 --- a/internal/generated/snippets/workflows/executions/apiv1beta/Client/GetExecution/main.go +++ b/internal/generated/snippets/workflows/executions/apiv1beta/Client/GetExecution/main.go @@ -24,13 +24,12 @@ import ( ) func main() { - // import executionspb "google.golang.org/genproto/googleapis/cloud/workflows/executions/v1beta" - ctx := context.Background() c, err := executions.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &executionspb.GetExecutionRequest{ // TODO: Fill request struct fields. diff --git a/internal/generated/snippets/workflows/executions/apiv1beta/Client/ListExecutions/main.go b/internal/generated/snippets/workflows/executions/apiv1beta/Client/ListExecutions/main.go index dda4cda6983c..15e3ee126c6e 100644 --- a/internal/generated/snippets/workflows/executions/apiv1beta/Client/ListExecutions/main.go +++ b/internal/generated/snippets/workflows/executions/apiv1beta/Client/ListExecutions/main.go @@ -25,14 +25,12 @@ import ( ) func main() { - // import executionspb "google.golang.org/genproto/googleapis/cloud/workflows/executions/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := executions.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &executionspb.ListExecutionsRequest{ // TODO: Fill request struct fields. diff --git a/iot/apiv1/device_manager_client.go b/iot/apiv1/device_manager_client.go index 5193e2acf798..540a9db1700f 100644 --- a/iot/apiv1/device_manager_client.go +++ b/iot/apiv1/device_manager_client.go @@ -61,7 +61,7 @@ type DeviceManagerCallOptions struct { UnbindDeviceFromGateway []gax.CallOption } -func defaultDeviceManagerClientOptions() []option.ClientOption { +func defaultDeviceManagerGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudiot.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudiot.mtls.googleapis.com:443"), @@ -209,32 +209,210 @@ func defaultDeviceManagerCallOptions() *DeviceManagerCallOptions { } } +// internalDeviceManagerClient is an interface that defines the methods availaible from Cloud IoT API. +type internalDeviceManagerClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateDeviceRegistry(context.Context, *iotpb.CreateDeviceRegistryRequest, ...gax.CallOption) (*iotpb.DeviceRegistry, error) + GetDeviceRegistry(context.Context, *iotpb.GetDeviceRegistryRequest, ...gax.CallOption) (*iotpb.DeviceRegistry, error) + UpdateDeviceRegistry(context.Context, *iotpb.UpdateDeviceRegistryRequest, ...gax.CallOption) (*iotpb.DeviceRegistry, error) + DeleteDeviceRegistry(context.Context, *iotpb.DeleteDeviceRegistryRequest, ...gax.CallOption) error + ListDeviceRegistries(context.Context, *iotpb.ListDeviceRegistriesRequest, ...gax.CallOption) *DeviceRegistryIterator + CreateDevice(context.Context, *iotpb.CreateDeviceRequest, ...gax.CallOption) (*iotpb.Device, error) + GetDevice(context.Context, *iotpb.GetDeviceRequest, ...gax.CallOption) (*iotpb.Device, error) + UpdateDevice(context.Context, *iotpb.UpdateDeviceRequest, ...gax.CallOption) (*iotpb.Device, error) + DeleteDevice(context.Context, *iotpb.DeleteDeviceRequest, ...gax.CallOption) error + ListDevices(context.Context, *iotpb.ListDevicesRequest, ...gax.CallOption) *DeviceIterator + ModifyCloudToDeviceConfig(context.Context, *iotpb.ModifyCloudToDeviceConfigRequest, ...gax.CallOption) (*iotpb.DeviceConfig, error) + ListDeviceConfigVersions(context.Context, *iotpb.ListDeviceConfigVersionsRequest, ...gax.CallOption) (*iotpb.ListDeviceConfigVersionsResponse, error) + ListDeviceStates(context.Context, *iotpb.ListDeviceStatesRequest, ...gax.CallOption) (*iotpb.ListDeviceStatesResponse, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) + SendCommandToDevice(context.Context, *iotpb.SendCommandToDeviceRequest, ...gax.CallOption) (*iotpb.SendCommandToDeviceResponse, error) + BindDeviceToGateway(context.Context, *iotpb.BindDeviceToGatewayRequest, ...gax.CallOption) (*iotpb.BindDeviceToGatewayResponse, error) + UnbindDeviceFromGateway(context.Context, *iotpb.UnbindDeviceFromGatewayRequest, ...gax.CallOption) (*iotpb.UnbindDeviceFromGatewayResponse, error) +} + // DeviceManagerClient is a client for interacting with Cloud IoT API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Internet of Things (IoT) service. Securely connect and manage IoT devices. type DeviceManagerClient struct { + // The internal transport-dependent client. + internalClient internalDeviceManagerClient + + // The call options for this service. + CallOptions *DeviceManagerCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *DeviceManagerClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *DeviceManagerClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *DeviceManagerClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateDeviceRegistry creates a device registry that contains devices. +func (c *DeviceManagerClient) CreateDeviceRegistry(ctx context.Context, req *iotpb.CreateDeviceRegistryRequest, opts ...gax.CallOption) (*iotpb.DeviceRegistry, error) { + return c.internalClient.CreateDeviceRegistry(ctx, req, opts...) +} + +// GetDeviceRegistry gets a device registry configuration. +func (c *DeviceManagerClient) GetDeviceRegistry(ctx context.Context, req *iotpb.GetDeviceRegistryRequest, opts ...gax.CallOption) (*iotpb.DeviceRegistry, error) { + return c.internalClient.GetDeviceRegistry(ctx, req, opts...) +} + +// UpdateDeviceRegistry updates a device registry configuration. +func (c *DeviceManagerClient) UpdateDeviceRegistry(ctx context.Context, req *iotpb.UpdateDeviceRegistryRequest, opts ...gax.CallOption) (*iotpb.DeviceRegistry, error) { + return c.internalClient.UpdateDeviceRegistry(ctx, req, opts...) +} + +// DeleteDeviceRegistry deletes a device registry configuration. +func (c *DeviceManagerClient) DeleteDeviceRegistry(ctx context.Context, req *iotpb.DeleteDeviceRegistryRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteDeviceRegistry(ctx, req, opts...) +} + +// ListDeviceRegistries lists device registries. +func (c *DeviceManagerClient) ListDeviceRegistries(ctx context.Context, req *iotpb.ListDeviceRegistriesRequest, opts ...gax.CallOption) *DeviceRegistryIterator { + return c.internalClient.ListDeviceRegistries(ctx, req, opts...) +} + +// CreateDevice creates a device in a device registry. +func (c *DeviceManagerClient) CreateDevice(ctx context.Context, req *iotpb.CreateDeviceRequest, opts ...gax.CallOption) (*iotpb.Device, error) { + return c.internalClient.CreateDevice(ctx, req, opts...) +} + +// GetDevice gets details about a device. +func (c *DeviceManagerClient) GetDevice(ctx context.Context, req *iotpb.GetDeviceRequest, opts ...gax.CallOption) (*iotpb.Device, error) { + return c.internalClient.GetDevice(ctx, req, opts...) +} + +// UpdateDevice updates a device. +func (c *DeviceManagerClient) UpdateDevice(ctx context.Context, req *iotpb.UpdateDeviceRequest, opts ...gax.CallOption) (*iotpb.Device, error) { + return c.internalClient.UpdateDevice(ctx, req, opts...) +} + +// DeleteDevice deletes a device. +func (c *DeviceManagerClient) DeleteDevice(ctx context.Context, req *iotpb.DeleteDeviceRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteDevice(ctx, req, opts...) +} + +// ListDevices list devices in a device registry. +func (c *DeviceManagerClient) ListDevices(ctx context.Context, req *iotpb.ListDevicesRequest, opts ...gax.CallOption) *DeviceIterator { + return c.internalClient.ListDevices(ctx, req, opts...) +} + +// ModifyCloudToDeviceConfig modifies the configuration for the device, which is eventually sent from +// the Cloud IoT Core servers. Returns the modified configuration version and +// its metadata. +func (c *DeviceManagerClient) ModifyCloudToDeviceConfig(ctx context.Context, req *iotpb.ModifyCloudToDeviceConfigRequest, opts ...gax.CallOption) (*iotpb.DeviceConfig, error) { + return c.internalClient.ModifyCloudToDeviceConfig(ctx, req, opts...) +} + +// ListDeviceConfigVersions lists the last few versions of the device configuration in descending +// order (i.e.: newest first). +func (c *DeviceManagerClient) ListDeviceConfigVersions(ctx context.Context, req *iotpb.ListDeviceConfigVersionsRequest, opts ...gax.CallOption) (*iotpb.ListDeviceConfigVersionsResponse, error) { + return c.internalClient.ListDeviceConfigVersions(ctx, req, opts...) +} + +// ListDeviceStates lists the last few versions of the device state in descending order (i.e.: +// newest first). +func (c *DeviceManagerClient) ListDeviceStates(ctx context.Context, req *iotpb.ListDeviceStatesRequest, opts ...gax.CallOption) (*iotpb.ListDeviceStatesResponse, error) { + return c.internalClient.ListDeviceStates(ctx, req, opts...) +} + +// SetIamPolicy sets the access control policy on the specified resource. Replaces any +// existing policy. +func (c *DeviceManagerClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy for a resource. +// Returns an empty policy if the resource exists and does not have a policy +// set. +func (c *DeviceManagerClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns permissions that a caller has on the specified resource. +// If the resource does not exist, this will return an empty set of +// permissions, not a NOT_FOUND error. +func (c *DeviceManagerClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// SendCommandToDevice sends a command to the specified device. In order for a device to be able +// to receive commands, it must: +// +// be connected to Cloud IoT Core using the MQTT protocol, and +// +// be subscribed to the group of MQTT topics specified by +// /devices/{device-id}/commands/#. This subscription will receive commands +// at the top-level topic /devices/{device-id}/commands as well as commands +// for subfolders, like /devices/{device-id}/commands/subfolder. +// Note that subscribing to specific subfolders is not supported. +// If the command could not be delivered to the device, this method will +// return an error; in particular, if the device is not subscribed, this +// method will return FAILED_PRECONDITION. Otherwise, this method will +// return OK. If the subscription is QoS 1, at least once delivery will be +// guaranteed; for QoS 0, no acknowledgment will be expected from the device. +func (c *DeviceManagerClient) SendCommandToDevice(ctx context.Context, req *iotpb.SendCommandToDeviceRequest, opts ...gax.CallOption) (*iotpb.SendCommandToDeviceResponse, error) { + return c.internalClient.SendCommandToDevice(ctx, req, opts...) +} + +// BindDeviceToGateway associates the device with the gateway. +func (c *DeviceManagerClient) BindDeviceToGateway(ctx context.Context, req *iotpb.BindDeviceToGatewayRequest, opts ...gax.CallOption) (*iotpb.BindDeviceToGatewayResponse, error) { + return c.internalClient.BindDeviceToGateway(ctx, req, opts...) +} + +// UnbindDeviceFromGateway deletes the association between the device and the gateway. +func (c *DeviceManagerClient) UnbindDeviceFromGateway(ctx context.Context, req *iotpb.UnbindDeviceFromGatewayRequest, opts ...gax.CallOption) (*iotpb.UnbindDeviceFromGatewayResponse, error) { + return c.internalClient.UnbindDeviceFromGateway(ctx, req, opts...) +} + +// deviceManagerGRPCClient is a client for interacting with Cloud IoT API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type deviceManagerGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing DeviceManagerClient + CallOptions **DeviceManagerCallOptions + // The gRPC API client. deviceManagerClient iotpb.DeviceManagerClient - // The call options for this service. - CallOptions *DeviceManagerCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewDeviceManagerClient creates a new device manager client. +// NewDeviceManagerClient creates a new device manager client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Internet of Things (IoT) service. Securely connect and manage IoT devices. func NewDeviceManagerClient(ctx context.Context, opts ...option.ClientOption) (*DeviceManagerClient, error) { - clientOpts := defaultDeviceManagerClientOptions() - + clientOpts := defaultDeviceManagerGRPCClientOptions() if newDeviceManagerClientHook != nil { hookOpts, err := newDeviceManagerClientHook(ctx, clientHookParams{}) if err != nil { @@ -252,42 +430,44 @@ func NewDeviceManagerClient(ctx context.Context, opts ...option.ClientOption) (* if err != nil { return nil, err } - c := &DeviceManagerClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultDeviceManagerCallOptions(), + client := DeviceManagerClient{CallOptions: defaultDeviceManagerCallOptions()} + c := &deviceManagerGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, deviceManagerClient: iotpb.NewDeviceManagerClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *DeviceManagerClient) Connection() *grpc.ClientConn { +func (c *deviceManagerGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *DeviceManagerClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *DeviceManagerClient) setGoogleClientInfo(keyval ...string) { +func (c *deviceManagerGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateDeviceRegistry creates a device registry that contains devices. -func (c *DeviceManagerClient) CreateDeviceRegistry(ctx context.Context, req *iotpb.CreateDeviceRegistryRequest, opts ...gax.CallOption) (*iotpb.DeviceRegistry, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *deviceManagerGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *deviceManagerGRPCClient) CreateDeviceRegistry(ctx context.Context, req *iotpb.CreateDeviceRegistryRequest, opts ...gax.CallOption) (*iotpb.DeviceRegistry, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -295,7 +475,7 @@ func (c *DeviceManagerClient) CreateDeviceRegistry(ctx context.Context, req *iot } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateDeviceRegistry[0:len(c.CallOptions.CreateDeviceRegistry):len(c.CallOptions.CreateDeviceRegistry)], opts...) + opts = append((*c.CallOptions).CreateDeviceRegistry[0:len((*c.CallOptions).CreateDeviceRegistry):len((*c.CallOptions).CreateDeviceRegistry)], opts...) var resp *iotpb.DeviceRegistry err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -308,8 +488,7 @@ func (c *DeviceManagerClient) CreateDeviceRegistry(ctx context.Context, req *iot return resp, nil } -// GetDeviceRegistry gets a device registry configuration. -func (c *DeviceManagerClient) GetDeviceRegistry(ctx context.Context, req *iotpb.GetDeviceRegistryRequest, opts ...gax.CallOption) (*iotpb.DeviceRegistry, error) { +func (c *deviceManagerGRPCClient) GetDeviceRegistry(ctx context.Context, req *iotpb.GetDeviceRegistryRequest, opts ...gax.CallOption) (*iotpb.DeviceRegistry, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -317,7 +496,7 @@ func (c *DeviceManagerClient) GetDeviceRegistry(ctx context.Context, req *iotpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetDeviceRegistry[0:len(c.CallOptions.GetDeviceRegistry):len(c.CallOptions.GetDeviceRegistry)], opts...) + opts = append((*c.CallOptions).GetDeviceRegistry[0:len((*c.CallOptions).GetDeviceRegistry):len((*c.CallOptions).GetDeviceRegistry)], opts...) var resp *iotpb.DeviceRegistry err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -330,8 +509,7 @@ func (c *DeviceManagerClient) GetDeviceRegistry(ctx context.Context, req *iotpb. return resp, nil } -// UpdateDeviceRegistry updates a device registry configuration. -func (c *DeviceManagerClient) UpdateDeviceRegistry(ctx context.Context, req *iotpb.UpdateDeviceRegistryRequest, opts ...gax.CallOption) (*iotpb.DeviceRegistry, error) { +func (c *deviceManagerGRPCClient) UpdateDeviceRegistry(ctx context.Context, req *iotpb.UpdateDeviceRegistryRequest, opts ...gax.CallOption) (*iotpb.DeviceRegistry, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -339,7 +517,7 @@ func (c *DeviceManagerClient) UpdateDeviceRegistry(ctx context.Context, req *iot } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "device_registry.name", url.QueryEscape(req.GetDeviceRegistry().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateDeviceRegistry[0:len(c.CallOptions.UpdateDeviceRegistry):len(c.CallOptions.UpdateDeviceRegistry)], opts...) + opts = append((*c.CallOptions).UpdateDeviceRegistry[0:len((*c.CallOptions).UpdateDeviceRegistry):len((*c.CallOptions).UpdateDeviceRegistry)], opts...) var resp *iotpb.DeviceRegistry err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -352,8 +530,7 @@ func (c *DeviceManagerClient) UpdateDeviceRegistry(ctx context.Context, req *iot return resp, nil } -// DeleteDeviceRegistry deletes a device registry configuration. -func (c *DeviceManagerClient) DeleteDeviceRegistry(ctx context.Context, req *iotpb.DeleteDeviceRegistryRequest, opts ...gax.CallOption) error { +func (c *deviceManagerGRPCClient) DeleteDeviceRegistry(ctx context.Context, req *iotpb.DeleteDeviceRegistryRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -361,7 +538,7 @@ func (c *DeviceManagerClient) DeleteDeviceRegistry(ctx context.Context, req *iot } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteDeviceRegistry[0:len(c.CallOptions.DeleteDeviceRegistry):len(c.CallOptions.DeleteDeviceRegistry)], opts...) + opts = append((*c.CallOptions).DeleteDeviceRegistry[0:len((*c.CallOptions).DeleteDeviceRegistry):len((*c.CallOptions).DeleteDeviceRegistry)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.deviceManagerClient.DeleteDeviceRegistry(ctx, req, settings.GRPC...) @@ -370,11 +547,10 @@ func (c *DeviceManagerClient) DeleteDeviceRegistry(ctx context.Context, req *iot return err } -// ListDeviceRegistries lists device registries. -func (c *DeviceManagerClient) ListDeviceRegistries(ctx context.Context, req *iotpb.ListDeviceRegistriesRequest, opts ...gax.CallOption) *DeviceRegistryIterator { +func (c *deviceManagerGRPCClient) ListDeviceRegistries(ctx context.Context, req *iotpb.ListDeviceRegistriesRequest, opts ...gax.CallOption) *DeviceRegistryIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDeviceRegistries[0:len(c.CallOptions.ListDeviceRegistries):len(c.CallOptions.ListDeviceRegistries)], opts...) + opts = append((*c.CallOptions).ListDeviceRegistries[0:len((*c.CallOptions).ListDeviceRegistries):len((*c.CallOptions).ListDeviceRegistries)], opts...) it := &DeviceRegistryIterator{} req = proto.Clone(req).(*iotpb.ListDeviceRegistriesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*iotpb.DeviceRegistry, string, error) { @@ -411,8 +587,7 @@ func (c *DeviceManagerClient) ListDeviceRegistries(ctx context.Context, req *iot return it } -// CreateDevice creates a device in a device registry. -func (c *DeviceManagerClient) CreateDevice(ctx context.Context, req *iotpb.CreateDeviceRequest, opts ...gax.CallOption) (*iotpb.Device, error) { +func (c *deviceManagerGRPCClient) CreateDevice(ctx context.Context, req *iotpb.CreateDeviceRequest, opts ...gax.CallOption) (*iotpb.Device, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -420,7 +595,7 @@ func (c *DeviceManagerClient) CreateDevice(ctx context.Context, req *iotpb.Creat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateDevice[0:len(c.CallOptions.CreateDevice):len(c.CallOptions.CreateDevice)], opts...) + opts = append((*c.CallOptions).CreateDevice[0:len((*c.CallOptions).CreateDevice):len((*c.CallOptions).CreateDevice)], opts...) var resp *iotpb.Device err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -433,8 +608,7 @@ func (c *DeviceManagerClient) CreateDevice(ctx context.Context, req *iotpb.Creat return resp, nil } -// GetDevice gets details about a device. -func (c *DeviceManagerClient) GetDevice(ctx context.Context, req *iotpb.GetDeviceRequest, opts ...gax.CallOption) (*iotpb.Device, error) { +func (c *deviceManagerGRPCClient) GetDevice(ctx context.Context, req *iotpb.GetDeviceRequest, opts ...gax.CallOption) (*iotpb.Device, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -442,7 +616,7 @@ func (c *DeviceManagerClient) GetDevice(ctx context.Context, req *iotpb.GetDevic } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetDevice[0:len(c.CallOptions.GetDevice):len(c.CallOptions.GetDevice)], opts...) + opts = append((*c.CallOptions).GetDevice[0:len((*c.CallOptions).GetDevice):len((*c.CallOptions).GetDevice)], opts...) var resp *iotpb.Device err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -455,8 +629,7 @@ func (c *DeviceManagerClient) GetDevice(ctx context.Context, req *iotpb.GetDevic return resp, nil } -// UpdateDevice updates a device. -func (c *DeviceManagerClient) UpdateDevice(ctx context.Context, req *iotpb.UpdateDeviceRequest, opts ...gax.CallOption) (*iotpb.Device, error) { +func (c *deviceManagerGRPCClient) UpdateDevice(ctx context.Context, req *iotpb.UpdateDeviceRequest, opts ...gax.CallOption) (*iotpb.Device, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -464,7 +637,7 @@ func (c *DeviceManagerClient) UpdateDevice(ctx context.Context, req *iotpb.Updat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "device.name", url.QueryEscape(req.GetDevice().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateDevice[0:len(c.CallOptions.UpdateDevice):len(c.CallOptions.UpdateDevice)], opts...) + opts = append((*c.CallOptions).UpdateDevice[0:len((*c.CallOptions).UpdateDevice):len((*c.CallOptions).UpdateDevice)], opts...) var resp *iotpb.Device err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -477,8 +650,7 @@ func (c *DeviceManagerClient) UpdateDevice(ctx context.Context, req *iotpb.Updat return resp, nil } -// DeleteDevice deletes a device. -func (c *DeviceManagerClient) DeleteDevice(ctx context.Context, req *iotpb.DeleteDeviceRequest, opts ...gax.CallOption) error { +func (c *deviceManagerGRPCClient) DeleteDevice(ctx context.Context, req *iotpb.DeleteDeviceRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -486,7 +658,7 @@ func (c *DeviceManagerClient) DeleteDevice(ctx context.Context, req *iotpb.Delet } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteDevice[0:len(c.CallOptions.DeleteDevice):len(c.CallOptions.DeleteDevice)], opts...) + opts = append((*c.CallOptions).DeleteDevice[0:len((*c.CallOptions).DeleteDevice):len((*c.CallOptions).DeleteDevice)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.deviceManagerClient.DeleteDevice(ctx, req, settings.GRPC...) @@ -495,11 +667,10 @@ func (c *DeviceManagerClient) DeleteDevice(ctx context.Context, req *iotpb.Delet return err } -// ListDevices list devices in a device registry. -func (c *DeviceManagerClient) ListDevices(ctx context.Context, req *iotpb.ListDevicesRequest, opts ...gax.CallOption) *DeviceIterator { +func (c *deviceManagerGRPCClient) ListDevices(ctx context.Context, req *iotpb.ListDevicesRequest, opts ...gax.CallOption) *DeviceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDevices[0:len(c.CallOptions.ListDevices):len(c.CallOptions.ListDevices)], opts...) + opts = append((*c.CallOptions).ListDevices[0:len((*c.CallOptions).ListDevices):len((*c.CallOptions).ListDevices)], opts...) it := &DeviceIterator{} req = proto.Clone(req).(*iotpb.ListDevicesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*iotpb.Device, string, error) { @@ -536,10 +707,7 @@ func (c *DeviceManagerClient) ListDevices(ctx context.Context, req *iotpb.ListDe return it } -// ModifyCloudToDeviceConfig modifies the configuration for the device, which is eventually sent from -// the Cloud IoT Core servers. Returns the modified configuration version and -// its metadata. -func (c *DeviceManagerClient) ModifyCloudToDeviceConfig(ctx context.Context, req *iotpb.ModifyCloudToDeviceConfigRequest, opts ...gax.CallOption) (*iotpb.DeviceConfig, error) { +func (c *deviceManagerGRPCClient) ModifyCloudToDeviceConfig(ctx context.Context, req *iotpb.ModifyCloudToDeviceConfigRequest, opts ...gax.CallOption) (*iotpb.DeviceConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -547,7 +715,7 @@ func (c *DeviceManagerClient) ModifyCloudToDeviceConfig(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ModifyCloudToDeviceConfig[0:len(c.CallOptions.ModifyCloudToDeviceConfig):len(c.CallOptions.ModifyCloudToDeviceConfig)], opts...) + opts = append((*c.CallOptions).ModifyCloudToDeviceConfig[0:len((*c.CallOptions).ModifyCloudToDeviceConfig):len((*c.CallOptions).ModifyCloudToDeviceConfig)], opts...) var resp *iotpb.DeviceConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -560,9 +728,7 @@ func (c *DeviceManagerClient) ModifyCloudToDeviceConfig(ctx context.Context, req return resp, nil } -// ListDeviceConfigVersions lists the last few versions of the device configuration in descending -// order (i.e.: newest first). -func (c *DeviceManagerClient) ListDeviceConfigVersions(ctx context.Context, req *iotpb.ListDeviceConfigVersionsRequest, opts ...gax.CallOption) (*iotpb.ListDeviceConfigVersionsResponse, error) { +func (c *deviceManagerGRPCClient) ListDeviceConfigVersions(ctx context.Context, req *iotpb.ListDeviceConfigVersionsRequest, opts ...gax.CallOption) (*iotpb.ListDeviceConfigVersionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -570,7 +736,7 @@ func (c *DeviceManagerClient) ListDeviceConfigVersions(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDeviceConfigVersions[0:len(c.CallOptions.ListDeviceConfigVersions):len(c.CallOptions.ListDeviceConfigVersions)], opts...) + opts = append((*c.CallOptions).ListDeviceConfigVersions[0:len((*c.CallOptions).ListDeviceConfigVersions):len((*c.CallOptions).ListDeviceConfigVersions)], opts...) var resp *iotpb.ListDeviceConfigVersionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -583,9 +749,7 @@ func (c *DeviceManagerClient) ListDeviceConfigVersions(ctx context.Context, req return resp, nil } -// ListDeviceStates lists the last few versions of the device state in descending order (i.e.: -// newest first). -func (c *DeviceManagerClient) ListDeviceStates(ctx context.Context, req *iotpb.ListDeviceStatesRequest, opts ...gax.CallOption) (*iotpb.ListDeviceStatesResponse, error) { +func (c *deviceManagerGRPCClient) ListDeviceStates(ctx context.Context, req *iotpb.ListDeviceStatesRequest, opts ...gax.CallOption) (*iotpb.ListDeviceStatesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -593,7 +757,7 @@ func (c *DeviceManagerClient) ListDeviceStates(ctx context.Context, req *iotpb.L } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDeviceStates[0:len(c.CallOptions.ListDeviceStates):len(c.CallOptions.ListDeviceStates)], opts...) + opts = append((*c.CallOptions).ListDeviceStates[0:len((*c.CallOptions).ListDeviceStates):len((*c.CallOptions).ListDeviceStates)], opts...) var resp *iotpb.ListDeviceStatesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -606,9 +770,7 @@ func (c *DeviceManagerClient) ListDeviceStates(ctx context.Context, req *iotpb.L return resp, nil } -// SetIamPolicy sets the access control policy on the specified resource. Replaces any -// existing policy. -func (c *DeviceManagerClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *deviceManagerGRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -616,7 +778,7 @@ func (c *DeviceManagerClient) SetIamPolicy(ctx context.Context, req *iampb.SetIa } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -629,10 +791,7 @@ func (c *DeviceManagerClient) SetIamPolicy(ctx context.Context, req *iampb.SetIa return resp, nil } -// GetIamPolicy gets the access control policy for a resource. -// Returns an empty policy if the resource exists and does not have a policy -// set. -func (c *DeviceManagerClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *deviceManagerGRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -640,7 +799,7 @@ func (c *DeviceManagerClient) GetIamPolicy(ctx context.Context, req *iampb.GetIa } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -653,10 +812,7 @@ func (c *DeviceManagerClient) GetIamPolicy(ctx context.Context, req *iampb.GetIa return resp, nil } -// TestIamPermissions returns permissions that a caller has on the specified resource. -// If the resource does not exist, this will return an empty set of -// permissions, not a NOT_FOUND error. -func (c *DeviceManagerClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *deviceManagerGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -664,7 +820,7 @@ func (c *DeviceManagerClient) TestIamPermissions(ctx context.Context, req *iampb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -677,22 +833,7 @@ func (c *DeviceManagerClient) TestIamPermissions(ctx context.Context, req *iampb return resp, nil } -// SendCommandToDevice sends a command to the specified device. In order for a device to be able -// to receive commands, it must: -// -// be connected to Cloud IoT Core using the MQTT protocol, and -// -// be subscribed to the group of MQTT topics specified by -// /devices/{device-id}/commands/#. This subscription will receive commands -// at the top-level topic /devices/{device-id}/commands as well as commands -// for subfolders, like /devices/{device-id}/commands/subfolder. -// Note that subscribing to specific subfolders is not supported. -// If the command could not be delivered to the device, this method will -// return an error; in particular, if the device is not subscribed, this -// method will return FAILED_PRECONDITION. Otherwise, this method will -// return OK. If the subscription is QoS 1, at least once delivery will be -// guaranteed; for QoS 0, no acknowledgment will be expected from the device. -func (c *DeviceManagerClient) SendCommandToDevice(ctx context.Context, req *iotpb.SendCommandToDeviceRequest, opts ...gax.CallOption) (*iotpb.SendCommandToDeviceResponse, error) { +func (c *deviceManagerGRPCClient) SendCommandToDevice(ctx context.Context, req *iotpb.SendCommandToDeviceRequest, opts ...gax.CallOption) (*iotpb.SendCommandToDeviceResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -700,7 +841,7 @@ func (c *DeviceManagerClient) SendCommandToDevice(ctx context.Context, req *iotp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SendCommandToDevice[0:len(c.CallOptions.SendCommandToDevice):len(c.CallOptions.SendCommandToDevice)], opts...) + opts = append((*c.CallOptions).SendCommandToDevice[0:len((*c.CallOptions).SendCommandToDevice):len((*c.CallOptions).SendCommandToDevice)], opts...) var resp *iotpb.SendCommandToDeviceResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -713,8 +854,7 @@ func (c *DeviceManagerClient) SendCommandToDevice(ctx context.Context, req *iotp return resp, nil } -// BindDeviceToGateway associates the device with the gateway. -func (c *DeviceManagerClient) BindDeviceToGateway(ctx context.Context, req *iotpb.BindDeviceToGatewayRequest, opts ...gax.CallOption) (*iotpb.BindDeviceToGatewayResponse, error) { +func (c *deviceManagerGRPCClient) BindDeviceToGateway(ctx context.Context, req *iotpb.BindDeviceToGatewayRequest, opts ...gax.CallOption) (*iotpb.BindDeviceToGatewayResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -722,7 +862,7 @@ func (c *DeviceManagerClient) BindDeviceToGateway(ctx context.Context, req *iotp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BindDeviceToGateway[0:len(c.CallOptions.BindDeviceToGateway):len(c.CallOptions.BindDeviceToGateway)], opts...) + opts = append((*c.CallOptions).BindDeviceToGateway[0:len((*c.CallOptions).BindDeviceToGateway):len((*c.CallOptions).BindDeviceToGateway)], opts...) var resp *iotpb.BindDeviceToGatewayResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -735,8 +875,7 @@ func (c *DeviceManagerClient) BindDeviceToGateway(ctx context.Context, req *iotp return resp, nil } -// UnbindDeviceFromGateway deletes the association between the device and the gateway. -func (c *DeviceManagerClient) UnbindDeviceFromGateway(ctx context.Context, req *iotpb.UnbindDeviceFromGatewayRequest, opts ...gax.CallOption) (*iotpb.UnbindDeviceFromGatewayResponse, error) { +func (c *deviceManagerGRPCClient) UnbindDeviceFromGateway(ctx context.Context, req *iotpb.UnbindDeviceFromGatewayRequest, opts ...gax.CallOption) (*iotpb.UnbindDeviceFromGatewayResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -744,7 +883,7 @@ func (c *DeviceManagerClient) UnbindDeviceFromGateway(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UnbindDeviceFromGateway[0:len(c.CallOptions.UnbindDeviceFromGateway):len(c.CallOptions.UnbindDeviceFromGateway)], opts...) + opts = append((*c.CallOptions).UnbindDeviceFromGateway[0:len((*c.CallOptions).UnbindDeviceFromGateway):len((*c.CallOptions).UnbindDeviceFromGateway)], opts...) var resp *iotpb.UnbindDeviceFromGatewayResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/iot/apiv1/device_manager_client_example_test.go b/iot/apiv1/device_manager_client_example_test.go index a5ef99bd95aa..68cd303f3d87 100644 --- a/iot/apiv1/device_manager_client_example_test.go +++ b/iot/apiv1/device_manager_client_example_test.go @@ -31,18 +31,19 @@ func ExampleNewDeviceManagerClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleDeviceManagerClient_CreateDeviceRegistry() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.CreateDeviceRegistryRequest{ // TODO: Fill request struct fields. @@ -56,13 +57,12 @@ func ExampleDeviceManagerClient_CreateDeviceRegistry() { } func ExampleDeviceManagerClient_GetDeviceRegistry() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.GetDeviceRegistryRequest{ // TODO: Fill request struct fields. @@ -76,13 +76,12 @@ func ExampleDeviceManagerClient_GetDeviceRegistry() { } func ExampleDeviceManagerClient_UpdateDeviceRegistry() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.UpdateDeviceRegistryRequest{ // TODO: Fill request struct fields. @@ -101,6 +100,7 @@ func ExampleDeviceManagerClient_DeleteDeviceRegistry() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.DeleteDeviceRegistryRequest{ // TODO: Fill request struct fields. @@ -112,14 +112,12 @@ func ExampleDeviceManagerClient_DeleteDeviceRegistry() { } func ExampleDeviceManagerClient_ListDeviceRegistries() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.ListDeviceRegistriesRequest{ // TODO: Fill request struct fields. @@ -139,13 +137,12 @@ func ExampleDeviceManagerClient_ListDeviceRegistries() { } func ExampleDeviceManagerClient_CreateDevice() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.CreateDeviceRequest{ // TODO: Fill request struct fields. @@ -159,13 +156,12 @@ func ExampleDeviceManagerClient_CreateDevice() { } func ExampleDeviceManagerClient_GetDevice() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.GetDeviceRequest{ // TODO: Fill request struct fields. @@ -179,13 +175,12 @@ func ExampleDeviceManagerClient_GetDevice() { } func ExampleDeviceManagerClient_UpdateDevice() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.UpdateDeviceRequest{ // TODO: Fill request struct fields. @@ -204,6 +199,7 @@ func ExampleDeviceManagerClient_DeleteDevice() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.DeleteDeviceRequest{ // TODO: Fill request struct fields. @@ -215,14 +211,12 @@ func ExampleDeviceManagerClient_DeleteDevice() { } func ExampleDeviceManagerClient_ListDevices() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.ListDevicesRequest{ // TODO: Fill request struct fields. @@ -242,13 +236,12 @@ func ExampleDeviceManagerClient_ListDevices() { } func ExampleDeviceManagerClient_ModifyCloudToDeviceConfig() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.ModifyCloudToDeviceConfigRequest{ // TODO: Fill request struct fields. @@ -262,13 +255,12 @@ func ExampleDeviceManagerClient_ModifyCloudToDeviceConfig() { } func ExampleDeviceManagerClient_ListDeviceConfigVersions() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.ListDeviceConfigVersionsRequest{ // TODO: Fill request struct fields. @@ -282,13 +274,12 @@ func ExampleDeviceManagerClient_ListDeviceConfigVersions() { } func ExampleDeviceManagerClient_ListDeviceStates() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.ListDeviceStatesRequest{ // TODO: Fill request struct fields. @@ -302,13 +293,12 @@ func ExampleDeviceManagerClient_ListDeviceStates() { } func ExampleDeviceManagerClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -322,13 +312,12 @@ func ExampleDeviceManagerClient_SetIamPolicy() { } func ExampleDeviceManagerClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -342,13 +331,12 @@ func ExampleDeviceManagerClient_GetIamPolicy() { } func ExampleDeviceManagerClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. @@ -362,13 +350,12 @@ func ExampleDeviceManagerClient_TestIamPermissions() { } func ExampleDeviceManagerClient_SendCommandToDevice() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.SendCommandToDeviceRequest{ // TODO: Fill request struct fields. @@ -382,13 +369,12 @@ func ExampleDeviceManagerClient_SendCommandToDevice() { } func ExampleDeviceManagerClient_BindDeviceToGateway() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.BindDeviceToGatewayRequest{ // TODO: Fill request struct fields. @@ -402,13 +388,12 @@ func ExampleDeviceManagerClient_BindDeviceToGateway() { } func ExampleDeviceManagerClient_UnbindDeviceFromGateway() { - // import iotpb "google.golang.org/genproto/googleapis/cloud/iot/v1" - ctx := context.Background() c, err := iot.NewDeviceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iotpb.UnbindDeviceFromGatewayRequest{ // TODO: Fill request struct fields. diff --git a/iot/apiv1/doc.go b/iot/apiv1/doc.go index 0d38352d3f1e..bf17aab97976 100644 --- a/iot/apiv1/doc.go +++ b/iot/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package iot // import "cloud.google.com/go/iot/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/kms/apiv1/doc.go b/kms/apiv1/doc.go index d94bf6ee7d18..37f8e312cce4 100644 --- a/kms/apiv1/doc.go +++ b/kms/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package kms // import "cloud.google.com/go/kms/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/kms/apiv1/key_management_client.go b/kms/apiv1/key_management_client.go index 46ceaefc6fac..ebd5c933e1d8 100644 --- a/kms/apiv1/key_management_client.go +++ b/kms/apiv1/key_management_client.go @@ -64,7 +64,7 @@ type KeyManagementCallOptions struct { RestoreCryptoKeyVersion []gax.CallOption } -func defaultKeyManagementClientOptions() []option.ClientOption { +func defaultKeyManagementGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudkms.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudkms.mtls.googleapis.com:443"), @@ -335,27 +335,271 @@ func defaultKeyManagementCallOptions() *KeyManagementCallOptions { } } +// internalKeyManagementClient is an interface that defines the methods availaible from Cloud Key Management Service (KMS) API. +type internalKeyManagementClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListKeyRings(context.Context, *kmspb.ListKeyRingsRequest, ...gax.CallOption) *KeyRingIterator + ListCryptoKeys(context.Context, *kmspb.ListCryptoKeysRequest, ...gax.CallOption) *CryptoKeyIterator + ListCryptoKeyVersions(context.Context, *kmspb.ListCryptoKeyVersionsRequest, ...gax.CallOption) *CryptoKeyVersionIterator + ListImportJobs(context.Context, *kmspb.ListImportJobsRequest, ...gax.CallOption) *ImportJobIterator + GetKeyRing(context.Context, *kmspb.GetKeyRingRequest, ...gax.CallOption) (*kmspb.KeyRing, error) + GetCryptoKey(context.Context, *kmspb.GetCryptoKeyRequest, ...gax.CallOption) (*kmspb.CryptoKey, error) + GetCryptoKeyVersion(context.Context, *kmspb.GetCryptoKeyVersionRequest, ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) + GetPublicKey(context.Context, *kmspb.GetPublicKeyRequest, ...gax.CallOption) (*kmspb.PublicKey, error) + GetImportJob(context.Context, *kmspb.GetImportJobRequest, ...gax.CallOption) (*kmspb.ImportJob, error) + CreateKeyRing(context.Context, *kmspb.CreateKeyRingRequest, ...gax.CallOption) (*kmspb.KeyRing, error) + CreateCryptoKey(context.Context, *kmspb.CreateCryptoKeyRequest, ...gax.CallOption) (*kmspb.CryptoKey, error) + CreateCryptoKeyVersion(context.Context, *kmspb.CreateCryptoKeyVersionRequest, ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) + ImportCryptoKeyVersion(context.Context, *kmspb.ImportCryptoKeyVersionRequest, ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) + CreateImportJob(context.Context, *kmspb.CreateImportJobRequest, ...gax.CallOption) (*kmspb.ImportJob, error) + UpdateCryptoKey(context.Context, *kmspb.UpdateCryptoKeyRequest, ...gax.CallOption) (*kmspb.CryptoKey, error) + UpdateCryptoKeyVersion(context.Context, *kmspb.UpdateCryptoKeyVersionRequest, ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) + Encrypt(context.Context, *kmspb.EncryptRequest, ...gax.CallOption) (*kmspb.EncryptResponse, error) + Decrypt(context.Context, *kmspb.DecryptRequest, ...gax.CallOption) (*kmspb.DecryptResponse, error) + AsymmetricSign(context.Context, *kmspb.AsymmetricSignRequest, ...gax.CallOption) (*kmspb.AsymmetricSignResponse, error) + AsymmetricDecrypt(context.Context, *kmspb.AsymmetricDecryptRequest, ...gax.CallOption) (*kmspb.AsymmetricDecryptResponse, error) + UpdateCryptoKeyPrimaryVersion(context.Context, *kmspb.UpdateCryptoKeyPrimaryVersionRequest, ...gax.CallOption) (*kmspb.CryptoKey, error) + DestroyCryptoKeyVersion(context.Context, *kmspb.DestroyCryptoKeyVersionRequest, ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) + RestoreCryptoKeyVersion(context.Context, *kmspb.RestoreCryptoKeyVersionRequest, ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) +} + // KeyManagementClient is a client for interacting with Cloud Key Management Service (KMS) API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Google Cloud Key Management Service +// +// Manages cryptographic keys and operations using those keys. Implements a REST +// model with the following objects: +// +// KeyRing +// +// CryptoKey +// +// CryptoKeyVersion +// +// ImportJob +// +// If you are using manual gRPC libraries, see +// Using gRPC with Cloud KMS (at https://cloud.google.com/kms/docs/grpc). type KeyManagementClient struct { + // The internal transport-dependent client. + internalClient internalKeyManagementClient + + // The call options for this service. + CallOptions *KeyManagementCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *KeyManagementClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *KeyManagementClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *KeyManagementClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListKeyRings lists KeyRings. +func (c *KeyManagementClient) ListKeyRings(ctx context.Context, req *kmspb.ListKeyRingsRequest, opts ...gax.CallOption) *KeyRingIterator { + return c.internalClient.ListKeyRings(ctx, req, opts...) +} + +// ListCryptoKeys lists CryptoKeys. +func (c *KeyManagementClient) ListCryptoKeys(ctx context.Context, req *kmspb.ListCryptoKeysRequest, opts ...gax.CallOption) *CryptoKeyIterator { + return c.internalClient.ListCryptoKeys(ctx, req, opts...) +} + +// ListCryptoKeyVersions lists CryptoKeyVersions. +func (c *KeyManagementClient) ListCryptoKeyVersions(ctx context.Context, req *kmspb.ListCryptoKeyVersionsRequest, opts ...gax.CallOption) *CryptoKeyVersionIterator { + return c.internalClient.ListCryptoKeyVersions(ctx, req, opts...) +} + +// ListImportJobs lists ImportJobs. +func (c *KeyManagementClient) ListImportJobs(ctx context.Context, req *kmspb.ListImportJobsRequest, opts ...gax.CallOption) *ImportJobIterator { + return c.internalClient.ListImportJobs(ctx, req, opts...) +} + +// GetKeyRing returns metadata for a given KeyRing. +func (c *KeyManagementClient) GetKeyRing(ctx context.Context, req *kmspb.GetKeyRingRequest, opts ...gax.CallOption) (*kmspb.KeyRing, error) { + return c.internalClient.GetKeyRing(ctx, req, opts...) +} + +// GetCryptoKey returns metadata for a given CryptoKey, as well as its +// primary CryptoKeyVersion. +func (c *KeyManagementClient) GetCryptoKey(ctx context.Context, req *kmspb.GetCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error) { + return c.internalClient.GetCryptoKey(ctx, req, opts...) +} + +// GetCryptoKeyVersion returns metadata for a given CryptoKeyVersion. +func (c *KeyManagementClient) GetCryptoKeyVersion(ctx context.Context, req *kmspb.GetCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { + return c.internalClient.GetCryptoKeyVersion(ctx, req, opts...) +} + +// GetPublicKey returns the public key for the given CryptoKeyVersion. The +// CryptoKey.purpose must be +// ASYMMETRIC_SIGN or +// ASYMMETRIC_DECRYPT. +func (c *KeyManagementClient) GetPublicKey(ctx context.Context, req *kmspb.GetPublicKeyRequest, opts ...gax.CallOption) (*kmspb.PublicKey, error) { + return c.internalClient.GetPublicKey(ctx, req, opts...) +} + +// GetImportJob returns metadata for a given ImportJob. +func (c *KeyManagementClient) GetImportJob(ctx context.Context, req *kmspb.GetImportJobRequest, opts ...gax.CallOption) (*kmspb.ImportJob, error) { + return c.internalClient.GetImportJob(ctx, req, opts...) +} + +// CreateKeyRing create a new KeyRing in a given Project and Location. +func (c *KeyManagementClient) CreateKeyRing(ctx context.Context, req *kmspb.CreateKeyRingRequest, opts ...gax.CallOption) (*kmspb.KeyRing, error) { + return c.internalClient.CreateKeyRing(ctx, req, opts...) +} + +// CreateCryptoKey create a new CryptoKey within a KeyRing. +// +// CryptoKey.purpose and +// CryptoKey.version_template.algorithm +// are required. +func (c *KeyManagementClient) CreateCryptoKey(ctx context.Context, req *kmspb.CreateCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error) { + return c.internalClient.CreateCryptoKey(ctx, req, opts...) +} + +// CreateCryptoKeyVersion create a new CryptoKeyVersion in a CryptoKey. +// +// The server will assign the next sequential id. If unset, +// state will be set to +// ENABLED. +func (c *KeyManagementClient) CreateCryptoKeyVersion(ctx context.Context, req *kmspb.CreateCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { + return c.internalClient.CreateCryptoKeyVersion(ctx, req, opts...) +} + +// ImportCryptoKeyVersion imports a new CryptoKeyVersion into an existing CryptoKey using the +// wrapped key material provided in the request. +// +// The version ID will be assigned the next sequential id within the +// CryptoKey. +func (c *KeyManagementClient) ImportCryptoKeyVersion(ctx context.Context, req *kmspb.ImportCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { + return c.internalClient.ImportCryptoKeyVersion(ctx, req, opts...) +} + +// CreateImportJob create a new ImportJob within a KeyRing. +// +// ImportJob.import_method is required. +func (c *KeyManagementClient) CreateImportJob(ctx context.Context, req *kmspb.CreateImportJobRequest, opts ...gax.CallOption) (*kmspb.ImportJob, error) { + return c.internalClient.CreateImportJob(ctx, req, opts...) +} + +// UpdateCryptoKey update a CryptoKey. +func (c *KeyManagementClient) UpdateCryptoKey(ctx context.Context, req *kmspb.UpdateCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error) { + return c.internalClient.UpdateCryptoKey(ctx, req, opts...) +} + +// UpdateCryptoKeyVersion update a CryptoKeyVersion's metadata. +// +// state may be changed between +// ENABLED and +// DISABLED using this +// method. See DestroyCryptoKeyVersion and RestoreCryptoKeyVersion to +// move between other states. +func (c *KeyManagementClient) UpdateCryptoKeyVersion(ctx context.Context, req *kmspb.UpdateCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { + return c.internalClient.UpdateCryptoKeyVersion(ctx, req, opts...) +} + +// Encrypt encrypts data, so that it can only be recovered by a call to Decrypt. +// The CryptoKey.purpose must be +// ENCRYPT_DECRYPT. +func (c *KeyManagementClient) Encrypt(ctx context.Context, req *kmspb.EncryptRequest, opts ...gax.CallOption) (*kmspb.EncryptResponse, error) { + return c.internalClient.Encrypt(ctx, req, opts...) +} + +// Decrypt decrypts data that was protected by Encrypt. The CryptoKey.purpose +// must be ENCRYPT_DECRYPT. +func (c *KeyManagementClient) Decrypt(ctx context.Context, req *kmspb.DecryptRequest, opts ...gax.CallOption) (*kmspb.DecryptResponse, error) { + return c.internalClient.Decrypt(ctx, req, opts...) +} + +// AsymmetricSign signs data using a CryptoKeyVersion with CryptoKey.purpose +// ASYMMETRIC_SIGN, producing a signature that can be verified with the public +// key retrieved from GetPublicKey. +func (c *KeyManagementClient) AsymmetricSign(ctx context.Context, req *kmspb.AsymmetricSignRequest, opts ...gax.CallOption) (*kmspb.AsymmetricSignResponse, error) { + return c.internalClient.AsymmetricSign(ctx, req, opts...) +} + +// AsymmetricDecrypt decrypts data that was encrypted with a public key retrieved from +// GetPublicKey corresponding to a CryptoKeyVersion with +// CryptoKey.purpose ASYMMETRIC_DECRYPT. +func (c *KeyManagementClient) AsymmetricDecrypt(ctx context.Context, req *kmspb.AsymmetricDecryptRequest, opts ...gax.CallOption) (*kmspb.AsymmetricDecryptResponse, error) { + return c.internalClient.AsymmetricDecrypt(ctx, req, opts...) +} + +// UpdateCryptoKeyPrimaryVersion update the version of a CryptoKey that will be used in Encrypt. +// +// Returns an error if called on an asymmetric key. +func (c *KeyManagementClient) UpdateCryptoKeyPrimaryVersion(ctx context.Context, req *kmspb.UpdateCryptoKeyPrimaryVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error) { + return c.internalClient.UpdateCryptoKeyPrimaryVersion(ctx, req, opts...) +} + +// DestroyCryptoKeyVersion schedule a CryptoKeyVersion for destruction. +// +// Upon calling this method, CryptoKeyVersion.state will be set to +// DESTROY_SCHEDULED +// and destroy_time will be set to a time 24 +// hours in the future, at which point the state +// will be changed to +// DESTROYED, and the key +// material will be irrevocably destroyed. +// +// Before the destroy_time is reached, +// RestoreCryptoKeyVersion may be called to reverse the process. +func (c *KeyManagementClient) DestroyCryptoKeyVersion(ctx context.Context, req *kmspb.DestroyCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { + return c.internalClient.DestroyCryptoKeyVersion(ctx, req, opts...) +} + +// RestoreCryptoKeyVersion restore a CryptoKeyVersion in the +// DESTROY_SCHEDULED +// state. +// +// Upon restoration of the CryptoKeyVersion, state +// will be set to DISABLED, +// and destroy_time will be cleared. +func (c *KeyManagementClient) RestoreCryptoKeyVersion(ctx context.Context, req *kmspb.RestoreCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { + return c.internalClient.RestoreCryptoKeyVersion(ctx, req, opts...) +} + +// keyManagementGRPCClient is a client for interacting with Cloud Key Management Service (KMS) API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type keyManagementGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing KeyManagementClient + CallOptions **KeyManagementCallOptions + // The gRPC API client. keyManagementClient kmspb.KeyManagementServiceClient - // The call options for this service. - CallOptions *KeyManagementCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewKeyManagementClient creates a new key management service client. +// NewKeyManagementClient creates a new key management service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Google Cloud Key Management Service // @@ -373,8 +617,7 @@ type KeyManagementClient struct { // If you are using manual gRPC libraries, see // Using gRPC with Cloud KMS (at https://cloud.google.com/kms/docs/grpc). func NewKeyManagementClient(ctx context.Context, opts ...option.ClientOption) (*KeyManagementClient, error) { - clientOpts := defaultKeyManagementClientOptions() - + clientOpts := defaultKeyManagementGRPCClientOptions() if newKeyManagementClientHook != nil { hookOpts, err := newKeyManagementClientHook(ctx, clientHookParams{}) if err != nil { @@ -392,45 +635,47 @@ func NewKeyManagementClient(ctx context.Context, opts ...option.ClientOption) (* if err != nil { return nil, err } - c := &KeyManagementClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultKeyManagementCallOptions(), + client := KeyManagementClient{CallOptions: defaultKeyManagementCallOptions()} + c := &keyManagementGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, keyManagementClient: kmspb.NewKeyManagementServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *KeyManagementClient) Connection() *grpc.ClientConn { +func (c *keyManagementGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *KeyManagementClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *KeyManagementClient) setGoogleClientInfo(keyval ...string) { +func (c *keyManagementGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListKeyRings lists KeyRings. -func (c *KeyManagementClient) ListKeyRings(ctx context.Context, req *kmspb.ListKeyRingsRequest, opts ...gax.CallOption) *KeyRingIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *keyManagementGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *keyManagementGRPCClient) ListKeyRings(ctx context.Context, req *kmspb.ListKeyRingsRequest, opts ...gax.CallOption) *KeyRingIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListKeyRings[0:len(c.CallOptions.ListKeyRings):len(c.CallOptions.ListKeyRings)], opts...) + opts = append((*c.CallOptions).ListKeyRings[0:len((*c.CallOptions).ListKeyRings):len((*c.CallOptions).ListKeyRings)], opts...) it := &KeyRingIterator{} req = proto.Clone(req).(*kmspb.ListKeyRingsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*kmspb.KeyRing, string, error) { @@ -467,11 +712,10 @@ func (c *KeyManagementClient) ListKeyRings(ctx context.Context, req *kmspb.ListK return it } -// ListCryptoKeys lists CryptoKeys. -func (c *KeyManagementClient) ListCryptoKeys(ctx context.Context, req *kmspb.ListCryptoKeysRequest, opts ...gax.CallOption) *CryptoKeyIterator { +func (c *keyManagementGRPCClient) ListCryptoKeys(ctx context.Context, req *kmspb.ListCryptoKeysRequest, opts ...gax.CallOption) *CryptoKeyIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCryptoKeys[0:len(c.CallOptions.ListCryptoKeys):len(c.CallOptions.ListCryptoKeys)], opts...) + opts = append((*c.CallOptions).ListCryptoKeys[0:len((*c.CallOptions).ListCryptoKeys):len((*c.CallOptions).ListCryptoKeys)], opts...) it := &CryptoKeyIterator{} req = proto.Clone(req).(*kmspb.ListCryptoKeysRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*kmspb.CryptoKey, string, error) { @@ -508,11 +752,10 @@ func (c *KeyManagementClient) ListCryptoKeys(ctx context.Context, req *kmspb.Lis return it } -// ListCryptoKeyVersions lists CryptoKeyVersions. -func (c *KeyManagementClient) ListCryptoKeyVersions(ctx context.Context, req *kmspb.ListCryptoKeyVersionsRequest, opts ...gax.CallOption) *CryptoKeyVersionIterator { +func (c *keyManagementGRPCClient) ListCryptoKeyVersions(ctx context.Context, req *kmspb.ListCryptoKeyVersionsRequest, opts ...gax.CallOption) *CryptoKeyVersionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCryptoKeyVersions[0:len(c.CallOptions.ListCryptoKeyVersions):len(c.CallOptions.ListCryptoKeyVersions)], opts...) + opts = append((*c.CallOptions).ListCryptoKeyVersions[0:len((*c.CallOptions).ListCryptoKeyVersions):len((*c.CallOptions).ListCryptoKeyVersions)], opts...) it := &CryptoKeyVersionIterator{} req = proto.Clone(req).(*kmspb.ListCryptoKeyVersionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*kmspb.CryptoKeyVersion, string, error) { @@ -549,11 +792,10 @@ func (c *KeyManagementClient) ListCryptoKeyVersions(ctx context.Context, req *km return it } -// ListImportJobs lists ImportJobs. -func (c *KeyManagementClient) ListImportJobs(ctx context.Context, req *kmspb.ListImportJobsRequest, opts ...gax.CallOption) *ImportJobIterator { +func (c *keyManagementGRPCClient) ListImportJobs(ctx context.Context, req *kmspb.ListImportJobsRequest, opts ...gax.CallOption) *ImportJobIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListImportJobs[0:len(c.CallOptions.ListImportJobs):len(c.CallOptions.ListImportJobs)], opts...) + opts = append((*c.CallOptions).ListImportJobs[0:len((*c.CallOptions).ListImportJobs):len((*c.CallOptions).ListImportJobs)], opts...) it := &ImportJobIterator{} req = proto.Clone(req).(*kmspb.ListImportJobsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*kmspb.ImportJob, string, error) { @@ -590,8 +832,7 @@ func (c *KeyManagementClient) ListImportJobs(ctx context.Context, req *kmspb.Lis return it } -// GetKeyRing returns metadata for a given KeyRing. -func (c *KeyManagementClient) GetKeyRing(ctx context.Context, req *kmspb.GetKeyRingRequest, opts ...gax.CallOption) (*kmspb.KeyRing, error) { +func (c *keyManagementGRPCClient) GetKeyRing(ctx context.Context, req *kmspb.GetKeyRingRequest, opts ...gax.CallOption) (*kmspb.KeyRing, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -599,7 +840,7 @@ func (c *KeyManagementClient) GetKeyRing(ctx context.Context, req *kmspb.GetKeyR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetKeyRing[0:len(c.CallOptions.GetKeyRing):len(c.CallOptions.GetKeyRing)], opts...) + opts = append((*c.CallOptions).GetKeyRing[0:len((*c.CallOptions).GetKeyRing):len((*c.CallOptions).GetKeyRing)], opts...) var resp *kmspb.KeyRing err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -612,9 +853,7 @@ func (c *KeyManagementClient) GetKeyRing(ctx context.Context, req *kmspb.GetKeyR return resp, nil } -// GetCryptoKey returns metadata for a given CryptoKey, as well as its -// primary CryptoKeyVersion. -func (c *KeyManagementClient) GetCryptoKey(ctx context.Context, req *kmspb.GetCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error) { +func (c *keyManagementGRPCClient) GetCryptoKey(ctx context.Context, req *kmspb.GetCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -622,7 +861,7 @@ func (c *KeyManagementClient) GetCryptoKey(ctx context.Context, req *kmspb.GetCr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCryptoKey[0:len(c.CallOptions.GetCryptoKey):len(c.CallOptions.GetCryptoKey)], opts...) + opts = append((*c.CallOptions).GetCryptoKey[0:len((*c.CallOptions).GetCryptoKey):len((*c.CallOptions).GetCryptoKey)], opts...) var resp *kmspb.CryptoKey err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -635,8 +874,7 @@ func (c *KeyManagementClient) GetCryptoKey(ctx context.Context, req *kmspb.GetCr return resp, nil } -// GetCryptoKeyVersion returns metadata for a given CryptoKeyVersion. -func (c *KeyManagementClient) GetCryptoKeyVersion(ctx context.Context, req *kmspb.GetCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { +func (c *keyManagementGRPCClient) GetCryptoKeyVersion(ctx context.Context, req *kmspb.GetCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -644,7 +882,7 @@ func (c *KeyManagementClient) GetCryptoKeyVersion(ctx context.Context, req *kmsp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCryptoKeyVersion[0:len(c.CallOptions.GetCryptoKeyVersion):len(c.CallOptions.GetCryptoKeyVersion)], opts...) + opts = append((*c.CallOptions).GetCryptoKeyVersion[0:len((*c.CallOptions).GetCryptoKeyVersion):len((*c.CallOptions).GetCryptoKeyVersion)], opts...) var resp *kmspb.CryptoKeyVersion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -657,11 +895,7 @@ func (c *KeyManagementClient) GetCryptoKeyVersion(ctx context.Context, req *kmsp return resp, nil } -// GetPublicKey returns the public key for the given CryptoKeyVersion. The -// CryptoKey.purpose must be -// ASYMMETRIC_SIGN or -// ASYMMETRIC_DECRYPT. -func (c *KeyManagementClient) GetPublicKey(ctx context.Context, req *kmspb.GetPublicKeyRequest, opts ...gax.CallOption) (*kmspb.PublicKey, error) { +func (c *keyManagementGRPCClient) GetPublicKey(ctx context.Context, req *kmspb.GetPublicKeyRequest, opts ...gax.CallOption) (*kmspb.PublicKey, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -669,7 +903,7 @@ func (c *KeyManagementClient) GetPublicKey(ctx context.Context, req *kmspb.GetPu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetPublicKey[0:len(c.CallOptions.GetPublicKey):len(c.CallOptions.GetPublicKey)], opts...) + opts = append((*c.CallOptions).GetPublicKey[0:len((*c.CallOptions).GetPublicKey):len((*c.CallOptions).GetPublicKey)], opts...) var resp *kmspb.PublicKey err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -682,8 +916,7 @@ func (c *KeyManagementClient) GetPublicKey(ctx context.Context, req *kmspb.GetPu return resp, nil } -// GetImportJob returns metadata for a given ImportJob. -func (c *KeyManagementClient) GetImportJob(ctx context.Context, req *kmspb.GetImportJobRequest, opts ...gax.CallOption) (*kmspb.ImportJob, error) { +func (c *keyManagementGRPCClient) GetImportJob(ctx context.Context, req *kmspb.GetImportJobRequest, opts ...gax.CallOption) (*kmspb.ImportJob, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -691,7 +924,7 @@ func (c *KeyManagementClient) GetImportJob(ctx context.Context, req *kmspb.GetIm } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetImportJob[0:len(c.CallOptions.GetImportJob):len(c.CallOptions.GetImportJob)], opts...) + opts = append((*c.CallOptions).GetImportJob[0:len((*c.CallOptions).GetImportJob):len((*c.CallOptions).GetImportJob)], opts...) var resp *kmspb.ImportJob err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -704,8 +937,7 @@ func (c *KeyManagementClient) GetImportJob(ctx context.Context, req *kmspb.GetIm return resp, nil } -// CreateKeyRing create a new KeyRing in a given Project and Location. -func (c *KeyManagementClient) CreateKeyRing(ctx context.Context, req *kmspb.CreateKeyRingRequest, opts ...gax.CallOption) (*kmspb.KeyRing, error) { +func (c *keyManagementGRPCClient) CreateKeyRing(ctx context.Context, req *kmspb.CreateKeyRingRequest, opts ...gax.CallOption) (*kmspb.KeyRing, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -713,7 +945,7 @@ func (c *KeyManagementClient) CreateKeyRing(ctx context.Context, req *kmspb.Crea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateKeyRing[0:len(c.CallOptions.CreateKeyRing):len(c.CallOptions.CreateKeyRing)], opts...) + opts = append((*c.CallOptions).CreateKeyRing[0:len((*c.CallOptions).CreateKeyRing):len((*c.CallOptions).CreateKeyRing)], opts...) var resp *kmspb.KeyRing err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -726,12 +958,7 @@ func (c *KeyManagementClient) CreateKeyRing(ctx context.Context, req *kmspb.Crea return resp, nil } -// CreateCryptoKey create a new CryptoKey within a KeyRing. -// -// CryptoKey.purpose and -// CryptoKey.version_template.algorithm -// are required. -func (c *KeyManagementClient) CreateCryptoKey(ctx context.Context, req *kmspb.CreateCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error) { +func (c *keyManagementGRPCClient) CreateCryptoKey(ctx context.Context, req *kmspb.CreateCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -739,7 +966,7 @@ func (c *KeyManagementClient) CreateCryptoKey(ctx context.Context, req *kmspb.Cr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCryptoKey[0:len(c.CallOptions.CreateCryptoKey):len(c.CallOptions.CreateCryptoKey)], opts...) + opts = append((*c.CallOptions).CreateCryptoKey[0:len((*c.CallOptions).CreateCryptoKey):len((*c.CallOptions).CreateCryptoKey)], opts...) var resp *kmspb.CryptoKey err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -752,12 +979,7 @@ func (c *KeyManagementClient) CreateCryptoKey(ctx context.Context, req *kmspb.Cr return resp, nil } -// CreateCryptoKeyVersion create a new CryptoKeyVersion in a CryptoKey. -// -// The server will assign the next sequential id. If unset, -// state will be set to -// ENABLED. -func (c *KeyManagementClient) CreateCryptoKeyVersion(ctx context.Context, req *kmspb.CreateCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { +func (c *keyManagementGRPCClient) CreateCryptoKeyVersion(ctx context.Context, req *kmspb.CreateCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -765,7 +987,7 @@ func (c *KeyManagementClient) CreateCryptoKeyVersion(ctx context.Context, req *k } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCryptoKeyVersion[0:len(c.CallOptions.CreateCryptoKeyVersion):len(c.CallOptions.CreateCryptoKeyVersion)], opts...) + opts = append((*c.CallOptions).CreateCryptoKeyVersion[0:len((*c.CallOptions).CreateCryptoKeyVersion):len((*c.CallOptions).CreateCryptoKeyVersion)], opts...) var resp *kmspb.CryptoKeyVersion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -778,12 +1000,7 @@ func (c *KeyManagementClient) CreateCryptoKeyVersion(ctx context.Context, req *k return resp, nil } -// ImportCryptoKeyVersion imports a new CryptoKeyVersion into an existing CryptoKey using the -// wrapped key material provided in the request. -// -// The version ID will be assigned the next sequential id within the -// CryptoKey. -func (c *KeyManagementClient) ImportCryptoKeyVersion(ctx context.Context, req *kmspb.ImportCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { +func (c *keyManagementGRPCClient) ImportCryptoKeyVersion(ctx context.Context, req *kmspb.ImportCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -791,7 +1008,7 @@ func (c *KeyManagementClient) ImportCryptoKeyVersion(ctx context.Context, req *k } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportCryptoKeyVersion[0:len(c.CallOptions.ImportCryptoKeyVersion):len(c.CallOptions.ImportCryptoKeyVersion)], opts...) + opts = append((*c.CallOptions).ImportCryptoKeyVersion[0:len((*c.CallOptions).ImportCryptoKeyVersion):len((*c.CallOptions).ImportCryptoKeyVersion)], opts...) var resp *kmspb.CryptoKeyVersion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -804,10 +1021,7 @@ func (c *KeyManagementClient) ImportCryptoKeyVersion(ctx context.Context, req *k return resp, nil } -// CreateImportJob create a new ImportJob within a KeyRing. -// -// ImportJob.import_method is required. -func (c *KeyManagementClient) CreateImportJob(ctx context.Context, req *kmspb.CreateImportJobRequest, opts ...gax.CallOption) (*kmspb.ImportJob, error) { +func (c *keyManagementGRPCClient) CreateImportJob(ctx context.Context, req *kmspb.CreateImportJobRequest, opts ...gax.CallOption) (*kmspb.ImportJob, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -815,7 +1029,7 @@ func (c *KeyManagementClient) CreateImportJob(ctx context.Context, req *kmspb.Cr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateImportJob[0:len(c.CallOptions.CreateImportJob):len(c.CallOptions.CreateImportJob)], opts...) + opts = append((*c.CallOptions).CreateImportJob[0:len((*c.CallOptions).CreateImportJob):len((*c.CallOptions).CreateImportJob)], opts...) var resp *kmspb.ImportJob err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -828,8 +1042,7 @@ func (c *KeyManagementClient) CreateImportJob(ctx context.Context, req *kmspb.Cr return resp, nil } -// UpdateCryptoKey update a CryptoKey. -func (c *KeyManagementClient) UpdateCryptoKey(ctx context.Context, req *kmspb.UpdateCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error) { +func (c *keyManagementGRPCClient) UpdateCryptoKey(ctx context.Context, req *kmspb.UpdateCryptoKeyRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -837,7 +1050,7 @@ func (c *KeyManagementClient) UpdateCryptoKey(ctx context.Context, req *kmspb.Up } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "crypto_key.name", url.QueryEscape(req.GetCryptoKey().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCryptoKey[0:len(c.CallOptions.UpdateCryptoKey):len(c.CallOptions.UpdateCryptoKey)], opts...) + opts = append((*c.CallOptions).UpdateCryptoKey[0:len((*c.CallOptions).UpdateCryptoKey):len((*c.CallOptions).UpdateCryptoKey)], opts...) var resp *kmspb.CryptoKey err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -850,14 +1063,7 @@ func (c *KeyManagementClient) UpdateCryptoKey(ctx context.Context, req *kmspb.Up return resp, nil } -// UpdateCryptoKeyVersion update a CryptoKeyVersion's metadata. -// -// state may be changed between -// ENABLED and -// DISABLED using this -// method. See DestroyCryptoKeyVersion and RestoreCryptoKeyVersion to -// move between other states. -func (c *KeyManagementClient) UpdateCryptoKeyVersion(ctx context.Context, req *kmspb.UpdateCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { +func (c *keyManagementGRPCClient) UpdateCryptoKeyVersion(ctx context.Context, req *kmspb.UpdateCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -865,7 +1071,7 @@ func (c *KeyManagementClient) UpdateCryptoKeyVersion(ctx context.Context, req *k } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "crypto_key_version.name", url.QueryEscape(req.GetCryptoKeyVersion().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCryptoKeyVersion[0:len(c.CallOptions.UpdateCryptoKeyVersion):len(c.CallOptions.UpdateCryptoKeyVersion)], opts...) + opts = append((*c.CallOptions).UpdateCryptoKeyVersion[0:len((*c.CallOptions).UpdateCryptoKeyVersion):len((*c.CallOptions).UpdateCryptoKeyVersion)], opts...) var resp *kmspb.CryptoKeyVersion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -878,10 +1084,7 @@ func (c *KeyManagementClient) UpdateCryptoKeyVersion(ctx context.Context, req *k return resp, nil } -// Encrypt encrypts data, so that it can only be recovered by a call to Decrypt. -// The CryptoKey.purpose must be -// ENCRYPT_DECRYPT. -func (c *KeyManagementClient) Encrypt(ctx context.Context, req *kmspb.EncryptRequest, opts ...gax.CallOption) (*kmspb.EncryptResponse, error) { +func (c *keyManagementGRPCClient) Encrypt(ctx context.Context, req *kmspb.EncryptRequest, opts ...gax.CallOption) (*kmspb.EncryptResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -889,7 +1092,7 @@ func (c *KeyManagementClient) Encrypt(ctx context.Context, req *kmspb.EncryptReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.Encrypt[0:len(c.CallOptions.Encrypt):len(c.CallOptions.Encrypt)], opts...) + opts = append((*c.CallOptions).Encrypt[0:len((*c.CallOptions).Encrypt):len((*c.CallOptions).Encrypt)], opts...) var resp *kmspb.EncryptResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -902,9 +1105,7 @@ func (c *KeyManagementClient) Encrypt(ctx context.Context, req *kmspb.EncryptReq return resp, nil } -// Decrypt decrypts data that was protected by Encrypt. The CryptoKey.purpose -// must be ENCRYPT_DECRYPT. -func (c *KeyManagementClient) Decrypt(ctx context.Context, req *kmspb.DecryptRequest, opts ...gax.CallOption) (*kmspb.DecryptResponse, error) { +func (c *keyManagementGRPCClient) Decrypt(ctx context.Context, req *kmspb.DecryptRequest, opts ...gax.CallOption) (*kmspb.DecryptResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -912,7 +1113,7 @@ func (c *KeyManagementClient) Decrypt(ctx context.Context, req *kmspb.DecryptReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.Decrypt[0:len(c.CallOptions.Decrypt):len(c.CallOptions.Decrypt)], opts...) + opts = append((*c.CallOptions).Decrypt[0:len((*c.CallOptions).Decrypt):len((*c.CallOptions).Decrypt)], opts...) var resp *kmspb.DecryptResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -925,10 +1126,7 @@ func (c *KeyManagementClient) Decrypt(ctx context.Context, req *kmspb.DecryptReq return resp, nil } -// AsymmetricSign signs data using a CryptoKeyVersion with CryptoKey.purpose -// ASYMMETRIC_SIGN, producing a signature that can be verified with the public -// key retrieved from GetPublicKey. -func (c *KeyManagementClient) AsymmetricSign(ctx context.Context, req *kmspb.AsymmetricSignRequest, opts ...gax.CallOption) (*kmspb.AsymmetricSignResponse, error) { +func (c *keyManagementGRPCClient) AsymmetricSign(ctx context.Context, req *kmspb.AsymmetricSignRequest, opts ...gax.CallOption) (*kmspb.AsymmetricSignResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -936,7 +1134,7 @@ func (c *KeyManagementClient) AsymmetricSign(ctx context.Context, req *kmspb.Asy } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AsymmetricSign[0:len(c.CallOptions.AsymmetricSign):len(c.CallOptions.AsymmetricSign)], opts...) + opts = append((*c.CallOptions).AsymmetricSign[0:len((*c.CallOptions).AsymmetricSign):len((*c.CallOptions).AsymmetricSign)], opts...) var resp *kmspb.AsymmetricSignResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -949,10 +1147,7 @@ func (c *KeyManagementClient) AsymmetricSign(ctx context.Context, req *kmspb.Asy return resp, nil } -// AsymmetricDecrypt decrypts data that was encrypted with a public key retrieved from -// GetPublicKey corresponding to a CryptoKeyVersion with -// CryptoKey.purpose ASYMMETRIC_DECRYPT. -func (c *KeyManagementClient) AsymmetricDecrypt(ctx context.Context, req *kmspb.AsymmetricDecryptRequest, opts ...gax.CallOption) (*kmspb.AsymmetricDecryptResponse, error) { +func (c *keyManagementGRPCClient) AsymmetricDecrypt(ctx context.Context, req *kmspb.AsymmetricDecryptRequest, opts ...gax.CallOption) (*kmspb.AsymmetricDecryptResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -960,7 +1155,7 @@ func (c *KeyManagementClient) AsymmetricDecrypt(ctx context.Context, req *kmspb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AsymmetricDecrypt[0:len(c.CallOptions.AsymmetricDecrypt):len(c.CallOptions.AsymmetricDecrypt)], opts...) + opts = append((*c.CallOptions).AsymmetricDecrypt[0:len((*c.CallOptions).AsymmetricDecrypt):len((*c.CallOptions).AsymmetricDecrypt)], opts...) var resp *kmspb.AsymmetricDecryptResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -973,10 +1168,7 @@ func (c *KeyManagementClient) AsymmetricDecrypt(ctx context.Context, req *kmspb. return resp, nil } -// UpdateCryptoKeyPrimaryVersion update the version of a CryptoKey that will be used in Encrypt. -// -// Returns an error if called on an asymmetric key. -func (c *KeyManagementClient) UpdateCryptoKeyPrimaryVersion(ctx context.Context, req *kmspb.UpdateCryptoKeyPrimaryVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error) { +func (c *keyManagementGRPCClient) UpdateCryptoKeyPrimaryVersion(ctx context.Context, req *kmspb.UpdateCryptoKeyPrimaryVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKey, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -984,7 +1176,7 @@ func (c *KeyManagementClient) UpdateCryptoKeyPrimaryVersion(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCryptoKeyPrimaryVersion[0:len(c.CallOptions.UpdateCryptoKeyPrimaryVersion):len(c.CallOptions.UpdateCryptoKeyPrimaryVersion)], opts...) + opts = append((*c.CallOptions).UpdateCryptoKeyPrimaryVersion[0:len((*c.CallOptions).UpdateCryptoKeyPrimaryVersion):len((*c.CallOptions).UpdateCryptoKeyPrimaryVersion)], opts...) var resp *kmspb.CryptoKey err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -997,19 +1189,7 @@ func (c *KeyManagementClient) UpdateCryptoKeyPrimaryVersion(ctx context.Context, return resp, nil } -// DestroyCryptoKeyVersion schedule a CryptoKeyVersion for destruction. -// -// Upon calling this method, CryptoKeyVersion.state will be set to -// DESTROY_SCHEDULED -// and destroy_time will be set to a time 24 -// hours in the future, at which point the state -// will be changed to -// DESTROYED, and the key -// material will be irrevocably destroyed. -// -// Before the destroy_time is reached, -// RestoreCryptoKeyVersion may be called to reverse the process. -func (c *KeyManagementClient) DestroyCryptoKeyVersion(ctx context.Context, req *kmspb.DestroyCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { +func (c *keyManagementGRPCClient) DestroyCryptoKeyVersion(ctx context.Context, req *kmspb.DestroyCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1017,7 +1197,7 @@ func (c *KeyManagementClient) DestroyCryptoKeyVersion(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DestroyCryptoKeyVersion[0:len(c.CallOptions.DestroyCryptoKeyVersion):len(c.CallOptions.DestroyCryptoKeyVersion)], opts...) + opts = append((*c.CallOptions).DestroyCryptoKeyVersion[0:len((*c.CallOptions).DestroyCryptoKeyVersion):len((*c.CallOptions).DestroyCryptoKeyVersion)], opts...) var resp *kmspb.CryptoKeyVersion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1030,14 +1210,7 @@ func (c *KeyManagementClient) DestroyCryptoKeyVersion(ctx context.Context, req * return resp, nil } -// RestoreCryptoKeyVersion restore a CryptoKeyVersion in the -// DESTROY_SCHEDULED -// state. -// -// Upon restoration of the CryptoKeyVersion, state -// will be set to DISABLED, -// and destroy_time will be cleared. -func (c *KeyManagementClient) RestoreCryptoKeyVersion(ctx context.Context, req *kmspb.RestoreCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { +func (c *keyManagementGRPCClient) RestoreCryptoKeyVersion(ctx context.Context, req *kmspb.RestoreCryptoKeyVersionRequest, opts ...gax.CallOption) (*kmspb.CryptoKeyVersion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1045,7 +1218,7 @@ func (c *KeyManagementClient) RestoreCryptoKeyVersion(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RestoreCryptoKeyVersion[0:len(c.CallOptions.RestoreCryptoKeyVersion):len(c.CallOptions.RestoreCryptoKeyVersion)], opts...) + opts = append((*c.CallOptions).RestoreCryptoKeyVersion[0:len((*c.CallOptions).RestoreCryptoKeyVersion):len((*c.CallOptions).RestoreCryptoKeyVersion)], opts...) var resp *kmspb.CryptoKeyVersion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/kms/apiv1/key_management_client_example_test.go b/kms/apiv1/key_management_client_example_test.go index 772b6fa2a478..1de678f4c802 100644 --- a/kms/apiv1/key_management_client_example_test.go +++ b/kms/apiv1/key_management_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewKeyManagementClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleKeyManagementClient_ListKeyRings() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.ListKeyRingsRequest{ // TODO: Fill request struct fields. @@ -62,14 +62,12 @@ func ExampleKeyManagementClient_ListKeyRings() { } func ExampleKeyManagementClient_ListCryptoKeys() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.ListCryptoKeysRequest{ // TODO: Fill request struct fields. @@ -89,14 +87,12 @@ func ExampleKeyManagementClient_ListCryptoKeys() { } func ExampleKeyManagementClient_ListCryptoKeyVersions() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.ListCryptoKeyVersionsRequest{ // TODO: Fill request struct fields. @@ -116,14 +112,12 @@ func ExampleKeyManagementClient_ListCryptoKeyVersions() { } func ExampleKeyManagementClient_ListImportJobs() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.ListImportJobsRequest{ // TODO: Fill request struct fields. @@ -143,13 +137,12 @@ func ExampleKeyManagementClient_ListImportJobs() { } func ExampleKeyManagementClient_GetKeyRing() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.GetKeyRingRequest{ // TODO: Fill request struct fields. @@ -163,13 +156,12 @@ func ExampleKeyManagementClient_GetKeyRing() { } func ExampleKeyManagementClient_GetCryptoKey() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.GetCryptoKeyRequest{ // TODO: Fill request struct fields. @@ -183,13 +175,12 @@ func ExampleKeyManagementClient_GetCryptoKey() { } func ExampleKeyManagementClient_GetCryptoKeyVersion() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.GetCryptoKeyVersionRequest{ // TODO: Fill request struct fields. @@ -203,13 +194,12 @@ func ExampleKeyManagementClient_GetCryptoKeyVersion() { } func ExampleKeyManagementClient_GetPublicKey() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.GetPublicKeyRequest{ // TODO: Fill request struct fields. @@ -223,13 +213,12 @@ func ExampleKeyManagementClient_GetPublicKey() { } func ExampleKeyManagementClient_GetImportJob() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.GetImportJobRequest{ // TODO: Fill request struct fields. @@ -243,13 +232,12 @@ func ExampleKeyManagementClient_GetImportJob() { } func ExampleKeyManagementClient_CreateKeyRing() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.CreateKeyRingRequest{ // TODO: Fill request struct fields. @@ -263,13 +251,12 @@ func ExampleKeyManagementClient_CreateKeyRing() { } func ExampleKeyManagementClient_CreateCryptoKey() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.CreateCryptoKeyRequest{ // TODO: Fill request struct fields. @@ -283,13 +270,12 @@ func ExampleKeyManagementClient_CreateCryptoKey() { } func ExampleKeyManagementClient_CreateCryptoKeyVersion() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.CreateCryptoKeyVersionRequest{ // TODO: Fill request struct fields. @@ -303,13 +289,12 @@ func ExampleKeyManagementClient_CreateCryptoKeyVersion() { } func ExampleKeyManagementClient_ImportCryptoKeyVersion() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.ImportCryptoKeyVersionRequest{ // TODO: Fill request struct fields. @@ -323,13 +308,12 @@ func ExampleKeyManagementClient_ImportCryptoKeyVersion() { } func ExampleKeyManagementClient_CreateImportJob() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.CreateImportJobRequest{ // TODO: Fill request struct fields. @@ -343,13 +327,12 @@ func ExampleKeyManagementClient_CreateImportJob() { } func ExampleKeyManagementClient_UpdateCryptoKey() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.UpdateCryptoKeyRequest{ // TODO: Fill request struct fields. @@ -363,13 +346,12 @@ func ExampleKeyManagementClient_UpdateCryptoKey() { } func ExampleKeyManagementClient_UpdateCryptoKeyVersion() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.UpdateCryptoKeyVersionRequest{ // TODO: Fill request struct fields. @@ -383,13 +365,12 @@ func ExampleKeyManagementClient_UpdateCryptoKeyVersion() { } func ExampleKeyManagementClient_Encrypt() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.EncryptRequest{ // TODO: Fill request struct fields. @@ -403,13 +384,12 @@ func ExampleKeyManagementClient_Encrypt() { } func ExampleKeyManagementClient_Decrypt() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.DecryptRequest{ // TODO: Fill request struct fields. @@ -423,13 +403,12 @@ func ExampleKeyManagementClient_Decrypt() { } func ExampleKeyManagementClient_AsymmetricSign() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.AsymmetricSignRequest{ // TODO: Fill request struct fields. @@ -443,13 +422,12 @@ func ExampleKeyManagementClient_AsymmetricSign() { } func ExampleKeyManagementClient_AsymmetricDecrypt() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.AsymmetricDecryptRequest{ // TODO: Fill request struct fields. @@ -463,13 +441,12 @@ func ExampleKeyManagementClient_AsymmetricDecrypt() { } func ExampleKeyManagementClient_UpdateCryptoKeyPrimaryVersion() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.UpdateCryptoKeyPrimaryVersionRequest{ // TODO: Fill request struct fields. @@ -483,13 +460,12 @@ func ExampleKeyManagementClient_UpdateCryptoKeyPrimaryVersion() { } func ExampleKeyManagementClient_DestroyCryptoKeyVersion() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.DestroyCryptoKeyVersionRequest{ // TODO: Fill request struct fields. @@ -503,13 +479,12 @@ func ExampleKeyManagementClient_DestroyCryptoKeyVersion() { } func ExampleKeyManagementClient_RestoreCryptoKeyVersion() { - // import kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" - ctx := context.Background() c, err := kms.NewKeyManagementClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &kmspb.RestoreCryptoKeyVersionRequest{ // TODO: Fill request struct fields. diff --git a/language/apiv1/doc.go b/language/apiv1/doc.go index 31aa34bbade6..325356e6d77d 100644 --- a/language/apiv1/doc.go +++ b/language/apiv1/doc.go @@ -30,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package language // import "cloud.google.com/go/language/apiv1" import ( @@ -50,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/language/apiv1/language_client.go b/language/apiv1/language_client.go index 98e1ddfdc64a..05a74eb19ed7 100644 --- a/language/apiv1/language_client.go +++ b/language/apiv1/language_client.go @@ -43,7 +43,7 @@ type CallOptions struct { AnnotateText []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("language.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("language.mtls.googleapis.com:443"), @@ -132,33 +132,117 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Natural Language API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + AnalyzeSentiment(context.Context, *languagepb.AnalyzeSentimentRequest, ...gax.CallOption) (*languagepb.AnalyzeSentimentResponse, error) + AnalyzeEntities(context.Context, *languagepb.AnalyzeEntitiesRequest, ...gax.CallOption) (*languagepb.AnalyzeEntitiesResponse, error) + AnalyzeEntitySentiment(context.Context, *languagepb.AnalyzeEntitySentimentRequest, ...gax.CallOption) (*languagepb.AnalyzeEntitySentimentResponse, error) + AnalyzeSyntax(context.Context, *languagepb.AnalyzeSyntaxRequest, ...gax.CallOption) (*languagepb.AnalyzeSyntaxResponse, error) + ClassifyText(context.Context, *languagepb.ClassifyTextRequest, ...gax.CallOption) (*languagepb.ClassifyTextResponse, error) + AnnotateText(context.Context, *languagepb.AnnotateTextRequest, ...gax.CallOption) (*languagepb.AnnotateTextResponse, error) +} + // Client is a client for interacting with Cloud Natural Language API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Provides text analysis operations such as sentiment analysis and entity +// recognition. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// AnalyzeSentiment analyzes the sentiment of the provided text. +func (c *Client) AnalyzeSentiment(ctx context.Context, req *languagepb.AnalyzeSentimentRequest, opts ...gax.CallOption) (*languagepb.AnalyzeSentimentResponse, error) { + return c.internalClient.AnalyzeSentiment(ctx, req, opts...) +} + +// AnalyzeEntities finds named entities (currently proper names and common nouns) in the text +// along with entity types, salience, mentions for each entity, and +// other properties. +func (c *Client) AnalyzeEntities(ctx context.Context, req *languagepb.AnalyzeEntitiesRequest, opts ...gax.CallOption) (*languagepb.AnalyzeEntitiesResponse, error) { + return c.internalClient.AnalyzeEntities(ctx, req, opts...) +} + +// AnalyzeEntitySentiment finds entities, similar to AnalyzeEntities in the text and analyzes +// sentiment associated with each entity and its mentions. +func (c *Client) AnalyzeEntitySentiment(ctx context.Context, req *languagepb.AnalyzeEntitySentimentRequest, opts ...gax.CallOption) (*languagepb.AnalyzeEntitySentimentResponse, error) { + return c.internalClient.AnalyzeEntitySentiment(ctx, req, opts...) +} + +// AnalyzeSyntax analyzes the syntax of the text and provides sentence boundaries and +// tokenization along with part of speech tags, dependency trees, and other +// properties. +func (c *Client) AnalyzeSyntax(ctx context.Context, req *languagepb.AnalyzeSyntaxRequest, opts ...gax.CallOption) (*languagepb.AnalyzeSyntaxResponse, error) { + return c.internalClient.AnalyzeSyntax(ctx, req, opts...) +} + +// ClassifyText classifies a document into categories. +func (c *Client) ClassifyText(ctx context.Context, req *languagepb.ClassifyTextRequest, opts ...gax.CallOption) (*languagepb.ClassifyTextResponse, error) { + return c.internalClient.ClassifyText(ctx, req, opts...) +} + +// AnnotateText a convenience method that provides all the features that analyzeSentiment, +// analyzeEntities, and analyzeSyntax provide in one call. +func (c *Client) AnnotateText(ctx context.Context, req *languagepb.AnnotateTextRequest, opts ...gax.CallOption) (*languagepb.AnnotateTextResponse, error) { + return c.internalClient.AnnotateText(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud Natural Language API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client languagepb.LanguageServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new language service client. +// NewClient creates a new language service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Provides text analysis operations such as sentiment analysis and entity // recognition. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -176,49 +260,51 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: languagepb.NewLanguageServiceClient(connPool), + client: languagepb.NewLanguageServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// AnalyzeSentiment analyzes the sentiment of the provided text. -func (c *Client) AnalyzeSentiment(ctx context.Context, req *languagepb.AnalyzeSentimentRequest, opts ...gax.CallOption) (*languagepb.AnalyzeSentimentResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) AnalyzeSentiment(ctx context.Context, req *languagepb.AnalyzeSentimentRequest, opts ...gax.CallOption) (*languagepb.AnalyzeSentimentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.AnalyzeSentiment[0:len(c.CallOptions.AnalyzeSentiment):len(c.CallOptions.AnalyzeSentiment)], opts...) + opts = append((*c.CallOptions).AnalyzeSentiment[0:len((*c.CallOptions).AnalyzeSentiment):len((*c.CallOptions).AnalyzeSentiment)], opts...) var resp *languagepb.AnalyzeSentimentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -231,17 +317,14 @@ func (c *Client) AnalyzeSentiment(ctx context.Context, req *languagepb.AnalyzeSe return resp, nil } -// AnalyzeEntities finds named entities (currently proper names and common nouns) in the text -// along with entity types, salience, mentions for each entity, and -// other properties. -func (c *Client) AnalyzeEntities(ctx context.Context, req *languagepb.AnalyzeEntitiesRequest, opts ...gax.CallOption) (*languagepb.AnalyzeEntitiesResponse, error) { +func (c *gRPCClient) AnalyzeEntities(ctx context.Context, req *languagepb.AnalyzeEntitiesRequest, opts ...gax.CallOption) (*languagepb.AnalyzeEntitiesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.AnalyzeEntities[0:len(c.CallOptions.AnalyzeEntities):len(c.CallOptions.AnalyzeEntities)], opts...) + opts = append((*c.CallOptions).AnalyzeEntities[0:len((*c.CallOptions).AnalyzeEntities):len((*c.CallOptions).AnalyzeEntities)], opts...) var resp *languagepb.AnalyzeEntitiesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -254,16 +337,14 @@ func (c *Client) AnalyzeEntities(ctx context.Context, req *languagepb.AnalyzeEnt return resp, nil } -// AnalyzeEntitySentiment finds entities, similar to AnalyzeEntities in the text and analyzes -// sentiment associated with each entity and its mentions. -func (c *Client) AnalyzeEntitySentiment(ctx context.Context, req *languagepb.AnalyzeEntitySentimentRequest, opts ...gax.CallOption) (*languagepb.AnalyzeEntitySentimentResponse, error) { +func (c *gRPCClient) AnalyzeEntitySentiment(ctx context.Context, req *languagepb.AnalyzeEntitySentimentRequest, opts ...gax.CallOption) (*languagepb.AnalyzeEntitySentimentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.AnalyzeEntitySentiment[0:len(c.CallOptions.AnalyzeEntitySentiment):len(c.CallOptions.AnalyzeEntitySentiment)], opts...) + opts = append((*c.CallOptions).AnalyzeEntitySentiment[0:len((*c.CallOptions).AnalyzeEntitySentiment):len((*c.CallOptions).AnalyzeEntitySentiment)], opts...) var resp *languagepb.AnalyzeEntitySentimentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -276,17 +357,14 @@ func (c *Client) AnalyzeEntitySentiment(ctx context.Context, req *languagepb.Ana return resp, nil } -// AnalyzeSyntax analyzes the syntax of the text and provides sentence boundaries and -// tokenization along with part of speech tags, dependency trees, and other -// properties. -func (c *Client) AnalyzeSyntax(ctx context.Context, req *languagepb.AnalyzeSyntaxRequest, opts ...gax.CallOption) (*languagepb.AnalyzeSyntaxResponse, error) { +func (c *gRPCClient) AnalyzeSyntax(ctx context.Context, req *languagepb.AnalyzeSyntaxRequest, opts ...gax.CallOption) (*languagepb.AnalyzeSyntaxResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.AnalyzeSyntax[0:len(c.CallOptions.AnalyzeSyntax):len(c.CallOptions.AnalyzeSyntax)], opts...) + opts = append((*c.CallOptions).AnalyzeSyntax[0:len((*c.CallOptions).AnalyzeSyntax):len((*c.CallOptions).AnalyzeSyntax)], opts...) var resp *languagepb.AnalyzeSyntaxResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -299,15 +377,14 @@ func (c *Client) AnalyzeSyntax(ctx context.Context, req *languagepb.AnalyzeSynta return resp, nil } -// ClassifyText classifies a document into categories. -func (c *Client) ClassifyText(ctx context.Context, req *languagepb.ClassifyTextRequest, opts ...gax.CallOption) (*languagepb.ClassifyTextResponse, error) { +func (c *gRPCClient) ClassifyText(ctx context.Context, req *languagepb.ClassifyTextRequest, opts ...gax.CallOption) (*languagepb.ClassifyTextResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ClassifyText[0:len(c.CallOptions.ClassifyText):len(c.CallOptions.ClassifyText)], opts...) + opts = append((*c.CallOptions).ClassifyText[0:len((*c.CallOptions).ClassifyText):len((*c.CallOptions).ClassifyText)], opts...) var resp *languagepb.ClassifyTextResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -320,16 +397,14 @@ func (c *Client) ClassifyText(ctx context.Context, req *languagepb.ClassifyTextR return resp, nil } -// AnnotateText a convenience method that provides all the features that analyzeSentiment, -// analyzeEntities, and analyzeSyntax provide in one call. -func (c *Client) AnnotateText(ctx context.Context, req *languagepb.AnnotateTextRequest, opts ...gax.CallOption) (*languagepb.AnnotateTextResponse, error) { +func (c *gRPCClient) AnnotateText(ctx context.Context, req *languagepb.AnnotateTextRequest, opts ...gax.CallOption) (*languagepb.AnnotateTextResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.AnnotateText[0:len(c.CallOptions.AnnotateText):len(c.CallOptions.AnnotateText)], opts...) + opts = append((*c.CallOptions).AnnotateText[0:len((*c.CallOptions).AnnotateText):len((*c.CallOptions).AnnotateText)], opts...) var resp *languagepb.AnnotateTextResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/language/apiv1/language_client_example_test.go b/language/apiv1/language_client_example_test.go index 87070f48e0e8..d08c0356f17c 100644 --- a/language/apiv1/language_client_example_test.go +++ b/language/apiv1/language_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_AnalyzeSentiment() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnalyzeSentimentRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleClient_AnalyzeSentiment() { } func ExampleClient_AnalyzeEntities() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnalyzeEntitiesRequest{ // TODO: Fill request struct fields. @@ -74,13 +74,12 @@ func ExampleClient_AnalyzeEntities() { } func ExampleClient_AnalyzeEntitySentiment() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnalyzeEntitySentimentRequest{ // TODO: Fill request struct fields. @@ -94,13 +93,12 @@ func ExampleClient_AnalyzeEntitySentiment() { } func ExampleClient_AnalyzeSyntax() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnalyzeSyntaxRequest{ // TODO: Fill request struct fields. @@ -114,13 +112,12 @@ func ExampleClient_AnalyzeSyntax() { } func ExampleClient_ClassifyText() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.ClassifyTextRequest{ // TODO: Fill request struct fields. @@ -134,13 +131,12 @@ func ExampleClient_ClassifyText() { } func ExampleClient_AnnotateText() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnnotateTextRequest{ // TODO: Fill request struct fields. diff --git a/language/apiv1beta2/doc.go b/language/apiv1beta2/doc.go index 56d382898310..2622b5a2a419 100644 --- a/language/apiv1beta2/doc.go +++ b/language/apiv1beta2/doc.go @@ -21,6 +21,8 @@ // analysis, entity recognition, entity sentiment analysis, and other text // annotations, to developers. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -30,7 +32,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package language // import "cloud.google.com/go/language/apiv1beta2" import ( @@ -50,7 +52,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/language/apiv1beta2/language_client.go b/language/apiv1beta2/language_client.go index 852991accc27..ef054808fa09 100644 --- a/language/apiv1beta2/language_client.go +++ b/language/apiv1beta2/language_client.go @@ -43,7 +43,7 @@ type CallOptions struct { AnnotateText []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("language.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("language.mtls.googleapis.com:443"), @@ -132,33 +132,117 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Natural Language API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + AnalyzeSentiment(context.Context, *languagepb.AnalyzeSentimentRequest, ...gax.CallOption) (*languagepb.AnalyzeSentimentResponse, error) + AnalyzeEntities(context.Context, *languagepb.AnalyzeEntitiesRequest, ...gax.CallOption) (*languagepb.AnalyzeEntitiesResponse, error) + AnalyzeEntitySentiment(context.Context, *languagepb.AnalyzeEntitySentimentRequest, ...gax.CallOption) (*languagepb.AnalyzeEntitySentimentResponse, error) + AnalyzeSyntax(context.Context, *languagepb.AnalyzeSyntaxRequest, ...gax.CallOption) (*languagepb.AnalyzeSyntaxResponse, error) + ClassifyText(context.Context, *languagepb.ClassifyTextRequest, ...gax.CallOption) (*languagepb.ClassifyTextResponse, error) + AnnotateText(context.Context, *languagepb.AnnotateTextRequest, ...gax.CallOption) (*languagepb.AnnotateTextResponse, error) +} + // Client is a client for interacting with Cloud Natural Language API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Provides text analysis operations such as sentiment analysis and entity +// recognition. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// AnalyzeSentiment analyzes the sentiment of the provided text. +func (c *Client) AnalyzeSentiment(ctx context.Context, req *languagepb.AnalyzeSentimentRequest, opts ...gax.CallOption) (*languagepb.AnalyzeSentimentResponse, error) { + return c.internalClient.AnalyzeSentiment(ctx, req, opts...) +} + +// AnalyzeEntities finds named entities (currently proper names and common nouns) in the text +// along with entity types, salience, mentions for each entity, and +// other properties. +func (c *Client) AnalyzeEntities(ctx context.Context, req *languagepb.AnalyzeEntitiesRequest, opts ...gax.CallOption) (*languagepb.AnalyzeEntitiesResponse, error) { + return c.internalClient.AnalyzeEntities(ctx, req, opts...) +} + +// AnalyzeEntitySentiment finds entities, similar to AnalyzeEntities in the text and analyzes +// sentiment associated with each entity and its mentions. +func (c *Client) AnalyzeEntitySentiment(ctx context.Context, req *languagepb.AnalyzeEntitySentimentRequest, opts ...gax.CallOption) (*languagepb.AnalyzeEntitySentimentResponse, error) { + return c.internalClient.AnalyzeEntitySentiment(ctx, req, opts...) +} + +// AnalyzeSyntax analyzes the syntax of the text and provides sentence boundaries and +// tokenization along with part-of-speech tags, dependency trees, and other +// properties. +func (c *Client) AnalyzeSyntax(ctx context.Context, req *languagepb.AnalyzeSyntaxRequest, opts ...gax.CallOption) (*languagepb.AnalyzeSyntaxResponse, error) { + return c.internalClient.AnalyzeSyntax(ctx, req, opts...) +} + +// ClassifyText classifies a document into categories. +func (c *Client) ClassifyText(ctx context.Context, req *languagepb.ClassifyTextRequest, opts ...gax.CallOption) (*languagepb.ClassifyTextResponse, error) { + return c.internalClient.ClassifyText(ctx, req, opts...) +} + +// AnnotateText a convenience method that provides all syntax, sentiment, entity, and +// classification features in one call. +func (c *Client) AnnotateText(ctx context.Context, req *languagepb.AnnotateTextRequest, opts ...gax.CallOption) (*languagepb.AnnotateTextResponse, error) { + return c.internalClient.AnnotateText(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud Natural Language API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client languagepb.LanguageServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new language service client. +// NewClient creates a new language service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Provides text analysis operations such as sentiment analysis and entity // recognition. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -176,49 +260,51 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: languagepb.NewLanguageServiceClient(connPool), + client: languagepb.NewLanguageServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// AnalyzeSentiment analyzes the sentiment of the provided text. -func (c *Client) AnalyzeSentiment(ctx context.Context, req *languagepb.AnalyzeSentimentRequest, opts ...gax.CallOption) (*languagepb.AnalyzeSentimentResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) AnalyzeSentiment(ctx context.Context, req *languagepb.AnalyzeSentimentRequest, opts ...gax.CallOption) (*languagepb.AnalyzeSentimentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.AnalyzeSentiment[0:len(c.CallOptions.AnalyzeSentiment):len(c.CallOptions.AnalyzeSentiment)], opts...) + opts = append((*c.CallOptions).AnalyzeSentiment[0:len((*c.CallOptions).AnalyzeSentiment):len((*c.CallOptions).AnalyzeSentiment)], opts...) var resp *languagepb.AnalyzeSentimentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -231,17 +317,14 @@ func (c *Client) AnalyzeSentiment(ctx context.Context, req *languagepb.AnalyzeSe return resp, nil } -// AnalyzeEntities finds named entities (currently proper names and common nouns) in the text -// along with entity types, salience, mentions for each entity, and -// other properties. -func (c *Client) AnalyzeEntities(ctx context.Context, req *languagepb.AnalyzeEntitiesRequest, opts ...gax.CallOption) (*languagepb.AnalyzeEntitiesResponse, error) { +func (c *gRPCClient) AnalyzeEntities(ctx context.Context, req *languagepb.AnalyzeEntitiesRequest, opts ...gax.CallOption) (*languagepb.AnalyzeEntitiesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.AnalyzeEntities[0:len(c.CallOptions.AnalyzeEntities):len(c.CallOptions.AnalyzeEntities)], opts...) + opts = append((*c.CallOptions).AnalyzeEntities[0:len((*c.CallOptions).AnalyzeEntities):len((*c.CallOptions).AnalyzeEntities)], opts...) var resp *languagepb.AnalyzeEntitiesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -254,16 +337,14 @@ func (c *Client) AnalyzeEntities(ctx context.Context, req *languagepb.AnalyzeEnt return resp, nil } -// AnalyzeEntitySentiment finds entities, similar to AnalyzeEntities in the text and analyzes -// sentiment associated with each entity and its mentions. -func (c *Client) AnalyzeEntitySentiment(ctx context.Context, req *languagepb.AnalyzeEntitySentimentRequest, opts ...gax.CallOption) (*languagepb.AnalyzeEntitySentimentResponse, error) { +func (c *gRPCClient) AnalyzeEntitySentiment(ctx context.Context, req *languagepb.AnalyzeEntitySentimentRequest, opts ...gax.CallOption) (*languagepb.AnalyzeEntitySentimentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.AnalyzeEntitySentiment[0:len(c.CallOptions.AnalyzeEntitySentiment):len(c.CallOptions.AnalyzeEntitySentiment)], opts...) + opts = append((*c.CallOptions).AnalyzeEntitySentiment[0:len((*c.CallOptions).AnalyzeEntitySentiment):len((*c.CallOptions).AnalyzeEntitySentiment)], opts...) var resp *languagepb.AnalyzeEntitySentimentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -276,17 +357,14 @@ func (c *Client) AnalyzeEntitySentiment(ctx context.Context, req *languagepb.Ana return resp, nil } -// AnalyzeSyntax analyzes the syntax of the text and provides sentence boundaries and -// tokenization along with part-of-speech tags, dependency trees, and other -// properties. -func (c *Client) AnalyzeSyntax(ctx context.Context, req *languagepb.AnalyzeSyntaxRequest, opts ...gax.CallOption) (*languagepb.AnalyzeSyntaxResponse, error) { +func (c *gRPCClient) AnalyzeSyntax(ctx context.Context, req *languagepb.AnalyzeSyntaxRequest, opts ...gax.CallOption) (*languagepb.AnalyzeSyntaxResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.AnalyzeSyntax[0:len(c.CallOptions.AnalyzeSyntax):len(c.CallOptions.AnalyzeSyntax)], opts...) + opts = append((*c.CallOptions).AnalyzeSyntax[0:len((*c.CallOptions).AnalyzeSyntax):len((*c.CallOptions).AnalyzeSyntax)], opts...) var resp *languagepb.AnalyzeSyntaxResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -299,15 +377,14 @@ func (c *Client) AnalyzeSyntax(ctx context.Context, req *languagepb.AnalyzeSynta return resp, nil } -// ClassifyText classifies a document into categories. -func (c *Client) ClassifyText(ctx context.Context, req *languagepb.ClassifyTextRequest, opts ...gax.CallOption) (*languagepb.ClassifyTextResponse, error) { +func (c *gRPCClient) ClassifyText(ctx context.Context, req *languagepb.ClassifyTextRequest, opts ...gax.CallOption) (*languagepb.ClassifyTextResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ClassifyText[0:len(c.CallOptions.ClassifyText):len(c.CallOptions.ClassifyText)], opts...) + opts = append((*c.CallOptions).ClassifyText[0:len((*c.CallOptions).ClassifyText):len((*c.CallOptions).ClassifyText)], opts...) var resp *languagepb.ClassifyTextResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -320,16 +397,14 @@ func (c *Client) ClassifyText(ctx context.Context, req *languagepb.ClassifyTextR return resp, nil } -// AnnotateText a convenience method that provides all syntax, sentiment, entity, and -// classification features in one call. -func (c *Client) AnnotateText(ctx context.Context, req *languagepb.AnnotateTextRequest, opts ...gax.CallOption) (*languagepb.AnnotateTextResponse, error) { +func (c *gRPCClient) AnnotateText(ctx context.Context, req *languagepb.AnnotateTextRequest, opts ...gax.CallOption) (*languagepb.AnnotateTextResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.AnnotateText[0:len(c.CallOptions.AnnotateText):len(c.CallOptions.AnnotateText)], opts...) + opts = append((*c.CallOptions).AnnotateText[0:len((*c.CallOptions).AnnotateText):len((*c.CallOptions).AnnotateText)], opts...) var resp *languagepb.AnnotateTextResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/language/apiv1beta2/language_client_example_test.go b/language/apiv1beta2/language_client_example_test.go index db72b9fdefd4..ed15c0d901b6 100644 --- a/language/apiv1beta2/language_client_example_test.go +++ b/language/apiv1beta2/language_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_AnalyzeSentiment() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1beta2" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnalyzeSentimentRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleClient_AnalyzeSentiment() { } func ExampleClient_AnalyzeEntities() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1beta2" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnalyzeEntitiesRequest{ // TODO: Fill request struct fields. @@ -74,13 +74,12 @@ func ExampleClient_AnalyzeEntities() { } func ExampleClient_AnalyzeEntitySentiment() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1beta2" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnalyzeEntitySentimentRequest{ // TODO: Fill request struct fields. @@ -94,13 +93,12 @@ func ExampleClient_AnalyzeEntitySentiment() { } func ExampleClient_AnalyzeSyntax() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1beta2" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnalyzeSyntaxRequest{ // TODO: Fill request struct fields. @@ -114,13 +112,12 @@ func ExampleClient_AnalyzeSyntax() { } func ExampleClient_ClassifyText() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1beta2" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.ClassifyTextRequest{ // TODO: Fill request struct fields. @@ -134,13 +131,12 @@ func ExampleClient_ClassifyText() { } func ExampleClient_AnnotateText() { - // import languagepb "google.golang.org/genproto/googleapis/cloud/language/v1beta2" - ctx := context.Background() c, err := language.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &languagepb.AnnotateTextRequest{ // TODO: Fill request struct fields. diff --git a/logging/apiv2/config_client.go b/logging/apiv2/config_client.go index e80e55711082..f9ea46ed9421 100644 --- a/logging/apiv2/config_client.go +++ b/logging/apiv2/config_client.go @@ -64,7 +64,7 @@ type ConfigCallOptions struct { UpdateCmekSettings []gax.CallOption } -func defaultConfigClientOptions() []option.ClientOption { +func defaultConfigGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("logging.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("logging.mtls.googleapis.com:443"), @@ -188,32 +188,259 @@ func defaultConfigCallOptions() *ConfigCallOptions { } } +// internalConfigClient is an interface that defines the methods availaible from Cloud Logging API. +type internalConfigClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListBuckets(context.Context, *loggingpb.ListBucketsRequest, ...gax.CallOption) *LogBucketIterator + GetBucket(context.Context, *loggingpb.GetBucketRequest, ...gax.CallOption) (*loggingpb.LogBucket, error) + CreateBucket(context.Context, *loggingpb.CreateBucketRequest, ...gax.CallOption) (*loggingpb.LogBucket, error) + UpdateBucket(context.Context, *loggingpb.UpdateBucketRequest, ...gax.CallOption) (*loggingpb.LogBucket, error) + DeleteBucket(context.Context, *loggingpb.DeleteBucketRequest, ...gax.CallOption) error + UndeleteBucket(context.Context, *loggingpb.UndeleteBucketRequest, ...gax.CallOption) error + ListViews(context.Context, *loggingpb.ListViewsRequest, ...gax.CallOption) *LogViewIterator + GetView(context.Context, *loggingpb.GetViewRequest, ...gax.CallOption) (*loggingpb.LogView, error) + CreateView(context.Context, *loggingpb.CreateViewRequest, ...gax.CallOption) (*loggingpb.LogView, error) + UpdateView(context.Context, *loggingpb.UpdateViewRequest, ...gax.CallOption) (*loggingpb.LogView, error) + DeleteView(context.Context, *loggingpb.DeleteViewRequest, ...gax.CallOption) error + ListSinks(context.Context, *loggingpb.ListSinksRequest, ...gax.CallOption) *LogSinkIterator + GetSink(context.Context, *loggingpb.GetSinkRequest, ...gax.CallOption) (*loggingpb.LogSink, error) + CreateSink(context.Context, *loggingpb.CreateSinkRequest, ...gax.CallOption) (*loggingpb.LogSink, error) + UpdateSink(context.Context, *loggingpb.UpdateSinkRequest, ...gax.CallOption) (*loggingpb.LogSink, error) + DeleteSink(context.Context, *loggingpb.DeleteSinkRequest, ...gax.CallOption) error + ListExclusions(context.Context, *loggingpb.ListExclusionsRequest, ...gax.CallOption) *LogExclusionIterator + GetExclusion(context.Context, *loggingpb.GetExclusionRequest, ...gax.CallOption) (*loggingpb.LogExclusion, error) + CreateExclusion(context.Context, *loggingpb.CreateExclusionRequest, ...gax.CallOption) (*loggingpb.LogExclusion, error) + UpdateExclusion(context.Context, *loggingpb.UpdateExclusionRequest, ...gax.CallOption) (*loggingpb.LogExclusion, error) + DeleteExclusion(context.Context, *loggingpb.DeleteExclusionRequest, ...gax.CallOption) error + GetCmekSettings(context.Context, *loggingpb.GetCmekSettingsRequest, ...gax.CallOption) (*loggingpb.CmekSettings, error) + UpdateCmekSettings(context.Context, *loggingpb.UpdateCmekSettingsRequest, ...gax.CallOption) (*loggingpb.CmekSettings, error) +} + // ConfigClient is a client for interacting with Cloud Logging API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for configuring sinks used to route log entries. type ConfigClient struct { + // The internal transport-dependent client. + internalClient internalConfigClient + + // The call options for this service. + CallOptions *ConfigCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ConfigClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ConfigClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ConfigClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListBuckets lists buckets. +func (c *ConfigClient) ListBuckets(ctx context.Context, req *loggingpb.ListBucketsRequest, opts ...gax.CallOption) *LogBucketIterator { + return c.internalClient.ListBuckets(ctx, req, opts...) +} + +// GetBucket gets a bucket. +func (c *ConfigClient) GetBucket(ctx context.Context, req *loggingpb.GetBucketRequest, opts ...gax.CallOption) (*loggingpb.LogBucket, error) { + return c.internalClient.GetBucket(ctx, req, opts...) +} + +// CreateBucket creates a bucket that can be used to store log entries. Once a bucket has +// been created, the region cannot be changed. +func (c *ConfigClient) CreateBucket(ctx context.Context, req *loggingpb.CreateBucketRequest, opts ...gax.CallOption) (*loggingpb.LogBucket, error) { + return c.internalClient.CreateBucket(ctx, req, opts...) +} + +// UpdateBucket updates a bucket. This method replaces the following fields in the +// existing bucket with values from the new bucket: retention_period +// +// If the retention period is decreased and the bucket is locked, +// FAILED_PRECONDITION will be returned. +// +// If the bucket has a LifecycleState of DELETE_REQUESTED, FAILED_PRECONDITION +// will be returned. +// +// A buckets region may not be modified after it is created. +func (c *ConfigClient) UpdateBucket(ctx context.Context, req *loggingpb.UpdateBucketRequest, opts ...gax.CallOption) (*loggingpb.LogBucket, error) { + return c.internalClient.UpdateBucket(ctx, req, opts...) +} + +// DeleteBucket deletes a bucket. +// Moves the bucket to the DELETE_REQUESTED state. After 7 days, the +// bucket will be purged and all logs in the bucket will be permanently +// deleted. +func (c *ConfigClient) DeleteBucket(ctx context.Context, req *loggingpb.DeleteBucketRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteBucket(ctx, req, opts...) +} + +// UndeleteBucket undeletes a bucket. A bucket that has been deleted may be undeleted within +// the grace period of 7 days. +func (c *ConfigClient) UndeleteBucket(ctx context.Context, req *loggingpb.UndeleteBucketRequest, opts ...gax.CallOption) error { + return c.internalClient.UndeleteBucket(ctx, req, opts...) +} + +// ListViews lists views on a bucket. +func (c *ConfigClient) ListViews(ctx context.Context, req *loggingpb.ListViewsRequest, opts ...gax.CallOption) *LogViewIterator { + return c.internalClient.ListViews(ctx, req, opts...) +} + +// GetView gets a view. +func (c *ConfigClient) GetView(ctx context.Context, req *loggingpb.GetViewRequest, opts ...gax.CallOption) (*loggingpb.LogView, error) { + return c.internalClient.GetView(ctx, req, opts...) +} + +// CreateView creates a view over logs in a bucket. A bucket may contain a maximum of +// 50 views. +func (c *ConfigClient) CreateView(ctx context.Context, req *loggingpb.CreateViewRequest, opts ...gax.CallOption) (*loggingpb.LogView, error) { + return c.internalClient.CreateView(ctx, req, opts...) +} + +// UpdateView updates a view. This method replaces the following fields in the existing +// view with values from the new view: filter. +func (c *ConfigClient) UpdateView(ctx context.Context, req *loggingpb.UpdateViewRequest, opts ...gax.CallOption) (*loggingpb.LogView, error) { + return c.internalClient.UpdateView(ctx, req, opts...) +} + +// DeleteView deletes a view from a bucket. +func (c *ConfigClient) DeleteView(ctx context.Context, req *loggingpb.DeleteViewRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteView(ctx, req, opts...) +} + +// ListSinks lists sinks. +func (c *ConfigClient) ListSinks(ctx context.Context, req *loggingpb.ListSinksRequest, opts ...gax.CallOption) *LogSinkIterator { + return c.internalClient.ListSinks(ctx, req, opts...) +} + +// GetSink gets a sink. +func (c *ConfigClient) GetSink(ctx context.Context, req *loggingpb.GetSinkRequest, opts ...gax.CallOption) (*loggingpb.LogSink, error) { + return c.internalClient.GetSink(ctx, req, opts...) +} + +// CreateSink creates a sink that exports specified log entries to a destination. The +// export of newly-ingested log entries begins immediately, unless the sink’s +// writer_identity is not permitted to write to the destination. A sink can +// export log entries only from the resource owning the sink. +func (c *ConfigClient) CreateSink(ctx context.Context, req *loggingpb.CreateSinkRequest, opts ...gax.CallOption) (*loggingpb.LogSink, error) { + return c.internalClient.CreateSink(ctx, req, opts...) +} + +// UpdateSink updates a sink. This method replaces the following fields in the existing +// sink with values from the new sink: destination, and filter. +// +// The updated sink might also have a new writer_identity; see the +// unique_writer_identity field. +func (c *ConfigClient) UpdateSink(ctx context.Context, req *loggingpb.UpdateSinkRequest, opts ...gax.CallOption) (*loggingpb.LogSink, error) { + return c.internalClient.UpdateSink(ctx, req, opts...) +} + +// DeleteSink deletes a sink. If the sink has a unique writer_identity, then that +// service account is also deleted. +func (c *ConfigClient) DeleteSink(ctx context.Context, req *loggingpb.DeleteSinkRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteSink(ctx, req, opts...) +} + +// ListExclusions lists all the exclusions in a parent resource. +func (c *ConfigClient) ListExclusions(ctx context.Context, req *loggingpb.ListExclusionsRequest, opts ...gax.CallOption) *LogExclusionIterator { + return c.internalClient.ListExclusions(ctx, req, opts...) +} + +// GetExclusion gets the description of an exclusion. +func (c *ConfigClient) GetExclusion(ctx context.Context, req *loggingpb.GetExclusionRequest, opts ...gax.CallOption) (*loggingpb.LogExclusion, error) { + return c.internalClient.GetExclusion(ctx, req, opts...) +} + +// CreateExclusion creates a new exclusion in a specified parent resource. +// Only log entries belonging to that resource can be excluded. +// You can have up to 10 exclusions in a resource. +func (c *ConfigClient) CreateExclusion(ctx context.Context, req *loggingpb.CreateExclusionRequest, opts ...gax.CallOption) (*loggingpb.LogExclusion, error) { + return c.internalClient.CreateExclusion(ctx, req, opts...) +} + +// UpdateExclusion changes one or more properties of an existing exclusion. +func (c *ConfigClient) UpdateExclusion(ctx context.Context, req *loggingpb.UpdateExclusionRequest, opts ...gax.CallOption) (*loggingpb.LogExclusion, error) { + return c.internalClient.UpdateExclusion(ctx, req, opts...) +} + +// DeleteExclusion deletes an exclusion. +func (c *ConfigClient) DeleteExclusion(ctx context.Context, req *loggingpb.DeleteExclusionRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteExclusion(ctx, req, opts...) +} + +// GetCmekSettings gets the Logs Router CMEK settings for the given resource. +// +// Note: CMEK for the Logs Router can currently only be configured for GCP +// organizations. Once configured, it applies to all projects and folders in +// the GCP organization. +// +// See Enabling CMEK for Logs +// Router (at https://cloud.google.com/logging/docs/routing/managed-encryption) +// for more information. +func (c *ConfigClient) GetCmekSettings(ctx context.Context, req *loggingpb.GetCmekSettingsRequest, opts ...gax.CallOption) (*loggingpb.CmekSettings, error) { + return c.internalClient.GetCmekSettings(ctx, req, opts...) +} + +// UpdateCmekSettings updates the Logs Router CMEK settings for the given resource. +// +// Note: CMEK for the Logs Router can currently only be configured for GCP +// organizations. Once configured, it applies to all projects and folders in +// the GCP organization. +// +// UpdateCmekSettings +// will fail if 1) kms_key_name is invalid, or 2) the associated service +// account does not have the required +// roles/cloudkms.cryptoKeyEncrypterDecrypter role assigned for the key, or +// 3) access to the key is disabled. +// +// See Enabling CMEK for Logs +// Router (at https://cloud.google.com/logging/docs/routing/managed-encryption) +// for more information. +func (c *ConfigClient) UpdateCmekSettings(ctx context.Context, req *loggingpb.UpdateCmekSettingsRequest, opts ...gax.CallOption) (*loggingpb.CmekSettings, error) { + return c.internalClient.UpdateCmekSettings(ctx, req, opts...) +} + +// configGRPCClient is a client for interacting with Cloud Logging API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type configGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ConfigClient + CallOptions **ConfigCallOptions + // The gRPC API client. configClient loggingpb.ConfigServiceV2Client - // The call options for this service. - CallOptions *ConfigCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewConfigClient creates a new config service v2 client. +// NewConfigClient creates a new config service v2 client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for configuring sinks used to route log entries. func NewConfigClient(ctx context.Context, opts ...option.ClientOption) (*ConfigClient, error) { - clientOpts := defaultConfigClientOptions() - + clientOpts := defaultConfigGRPCClientOptions() if newConfigClientHook != nil { hookOpts, err := newConfigClientHook(ctx, clientHookParams{}) if err != nil { @@ -231,45 +458,47 @@ func NewConfigClient(ctx context.Context, opts ...option.ClientOption) (*ConfigC if err != nil { return nil, err } - c := &ConfigClient{ + client := ConfigClient{CallOptions: defaultConfigCallOptions()} + + c := &configGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultConfigCallOptions(), - - configClient: loggingpb.NewConfigServiceV2Client(connPool), + configClient: loggingpb.NewConfigServiceV2Client(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ConfigClient) Connection() *grpc.ClientConn { +func (c *configGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ConfigClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ConfigClient) setGoogleClientInfo(keyval ...string) { +func (c *configGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListBuckets lists buckets. -func (c *ConfigClient) ListBuckets(ctx context.Context, req *loggingpb.ListBucketsRequest, opts ...gax.CallOption) *LogBucketIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *configGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *configGRPCClient) ListBuckets(ctx context.Context, req *loggingpb.ListBucketsRequest, opts ...gax.CallOption) *LogBucketIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListBuckets[0:len(c.CallOptions.ListBuckets):len(c.CallOptions.ListBuckets)], opts...) + opts = append((*c.CallOptions).ListBuckets[0:len((*c.CallOptions).ListBuckets):len((*c.CallOptions).ListBuckets)], opts...) it := &LogBucketIterator{} req = proto.Clone(req).(*loggingpb.ListBucketsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*loggingpb.LogBucket, string, error) { @@ -306,11 +535,10 @@ func (c *ConfigClient) ListBuckets(ctx context.Context, req *loggingpb.ListBucke return it } -// GetBucket gets a bucket. -func (c *ConfigClient) GetBucket(ctx context.Context, req *loggingpb.GetBucketRequest, opts ...gax.CallOption) (*loggingpb.LogBucket, error) { +func (c *configGRPCClient) GetBucket(ctx context.Context, req *loggingpb.GetBucketRequest, opts ...gax.CallOption) (*loggingpb.LogBucket, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetBucket[0:len(c.CallOptions.GetBucket):len(c.CallOptions.GetBucket)], opts...) + opts = append((*c.CallOptions).GetBucket[0:len((*c.CallOptions).GetBucket):len((*c.CallOptions).GetBucket)], opts...) var resp *loggingpb.LogBucket err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -323,12 +551,10 @@ func (c *ConfigClient) GetBucket(ctx context.Context, req *loggingpb.GetBucketRe return resp, nil } -// CreateBucket creates a bucket that can be used to store log entries. Once a bucket has -// been created, the region cannot be changed. -func (c *ConfigClient) CreateBucket(ctx context.Context, req *loggingpb.CreateBucketRequest, opts ...gax.CallOption) (*loggingpb.LogBucket, error) { +func (c *configGRPCClient) CreateBucket(ctx context.Context, req *loggingpb.CreateBucketRequest, opts ...gax.CallOption) (*loggingpb.LogBucket, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateBucket[0:len(c.CallOptions.CreateBucket):len(c.CallOptions.CreateBucket)], opts...) + opts = append((*c.CallOptions).CreateBucket[0:len((*c.CallOptions).CreateBucket):len((*c.CallOptions).CreateBucket)], opts...) var resp *loggingpb.LogBucket err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -341,20 +567,10 @@ func (c *ConfigClient) CreateBucket(ctx context.Context, req *loggingpb.CreateBu return resp, nil } -// UpdateBucket updates a bucket. This method replaces the following fields in the -// existing bucket with values from the new bucket: retention_period -// -// If the retention period is decreased and the bucket is locked, -// FAILED_PRECONDITION will be returned. -// -// If the bucket has a LifecycleState of DELETE_REQUESTED, FAILED_PRECONDITION -// will be returned. -// -// A buckets region may not be modified after it is created. -func (c *ConfigClient) UpdateBucket(ctx context.Context, req *loggingpb.UpdateBucketRequest, opts ...gax.CallOption) (*loggingpb.LogBucket, error) { +func (c *configGRPCClient) UpdateBucket(ctx context.Context, req *loggingpb.UpdateBucketRequest, opts ...gax.CallOption) (*loggingpb.LogBucket, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateBucket[0:len(c.CallOptions.UpdateBucket):len(c.CallOptions.UpdateBucket)], opts...) + opts = append((*c.CallOptions).UpdateBucket[0:len((*c.CallOptions).UpdateBucket):len((*c.CallOptions).UpdateBucket)], opts...) var resp *loggingpb.LogBucket err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -367,14 +583,10 @@ func (c *ConfigClient) UpdateBucket(ctx context.Context, req *loggingpb.UpdateBu return resp, nil } -// DeleteBucket deletes a bucket. -// Moves the bucket to the DELETE_REQUESTED state. After 7 days, the -// bucket will be purged and all logs in the bucket will be permanently -// deleted. -func (c *ConfigClient) DeleteBucket(ctx context.Context, req *loggingpb.DeleteBucketRequest, opts ...gax.CallOption) error { +func (c *configGRPCClient) DeleteBucket(ctx context.Context, req *loggingpb.DeleteBucketRequest, opts ...gax.CallOption) error { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteBucket[0:len(c.CallOptions.DeleteBucket):len(c.CallOptions.DeleteBucket)], opts...) + opts = append((*c.CallOptions).DeleteBucket[0:len((*c.CallOptions).DeleteBucket):len((*c.CallOptions).DeleteBucket)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.configClient.DeleteBucket(ctx, req, settings.GRPC...) @@ -383,12 +595,10 @@ func (c *ConfigClient) DeleteBucket(ctx context.Context, req *loggingpb.DeleteBu return err } -// UndeleteBucket undeletes a bucket. A bucket that has been deleted may be undeleted within -// the grace period of 7 days. -func (c *ConfigClient) UndeleteBucket(ctx context.Context, req *loggingpb.UndeleteBucketRequest, opts ...gax.CallOption) error { +func (c *configGRPCClient) UndeleteBucket(ctx context.Context, req *loggingpb.UndeleteBucketRequest, opts ...gax.CallOption) error { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UndeleteBucket[0:len(c.CallOptions.UndeleteBucket):len(c.CallOptions.UndeleteBucket)], opts...) + opts = append((*c.CallOptions).UndeleteBucket[0:len((*c.CallOptions).UndeleteBucket):len((*c.CallOptions).UndeleteBucket)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.configClient.UndeleteBucket(ctx, req, settings.GRPC...) @@ -397,11 +607,10 @@ func (c *ConfigClient) UndeleteBucket(ctx context.Context, req *loggingpb.Undele return err } -// ListViews lists views on a bucket. -func (c *ConfigClient) ListViews(ctx context.Context, req *loggingpb.ListViewsRequest, opts ...gax.CallOption) *LogViewIterator { +func (c *configGRPCClient) ListViews(ctx context.Context, req *loggingpb.ListViewsRequest, opts ...gax.CallOption) *LogViewIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListViews[0:len(c.CallOptions.ListViews):len(c.CallOptions.ListViews)], opts...) + opts = append((*c.CallOptions).ListViews[0:len((*c.CallOptions).ListViews):len((*c.CallOptions).ListViews)], opts...) it := &LogViewIterator{} req = proto.Clone(req).(*loggingpb.ListViewsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*loggingpb.LogView, string, error) { @@ -438,11 +647,10 @@ func (c *ConfigClient) ListViews(ctx context.Context, req *loggingpb.ListViewsRe return it } -// GetView gets a view. -func (c *ConfigClient) GetView(ctx context.Context, req *loggingpb.GetViewRequest, opts ...gax.CallOption) (*loggingpb.LogView, error) { +func (c *configGRPCClient) GetView(ctx context.Context, req *loggingpb.GetViewRequest, opts ...gax.CallOption) (*loggingpb.LogView, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetView[0:len(c.CallOptions.GetView):len(c.CallOptions.GetView)], opts...) + opts = append((*c.CallOptions).GetView[0:len((*c.CallOptions).GetView):len((*c.CallOptions).GetView)], opts...) var resp *loggingpb.LogView err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -455,12 +663,10 @@ func (c *ConfigClient) GetView(ctx context.Context, req *loggingpb.GetViewReques return resp, nil } -// CreateView creates a view over logs in a bucket. A bucket may contain a maximum of -// 50 views. -func (c *ConfigClient) CreateView(ctx context.Context, req *loggingpb.CreateViewRequest, opts ...gax.CallOption) (*loggingpb.LogView, error) { +func (c *configGRPCClient) CreateView(ctx context.Context, req *loggingpb.CreateViewRequest, opts ...gax.CallOption) (*loggingpb.LogView, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateView[0:len(c.CallOptions.CreateView):len(c.CallOptions.CreateView)], opts...) + opts = append((*c.CallOptions).CreateView[0:len((*c.CallOptions).CreateView):len((*c.CallOptions).CreateView)], opts...) var resp *loggingpb.LogView err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -473,12 +679,10 @@ func (c *ConfigClient) CreateView(ctx context.Context, req *loggingpb.CreateView return resp, nil } -// UpdateView updates a view. This method replaces the following fields in the existing -// view with values from the new view: filter. -func (c *ConfigClient) UpdateView(ctx context.Context, req *loggingpb.UpdateViewRequest, opts ...gax.CallOption) (*loggingpb.LogView, error) { +func (c *configGRPCClient) UpdateView(ctx context.Context, req *loggingpb.UpdateViewRequest, opts ...gax.CallOption) (*loggingpb.LogView, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateView[0:len(c.CallOptions.UpdateView):len(c.CallOptions.UpdateView)], opts...) + opts = append((*c.CallOptions).UpdateView[0:len((*c.CallOptions).UpdateView):len((*c.CallOptions).UpdateView)], opts...) var resp *loggingpb.LogView err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -491,11 +695,10 @@ func (c *ConfigClient) UpdateView(ctx context.Context, req *loggingpb.UpdateView return resp, nil } -// DeleteView deletes a view from a bucket. -func (c *ConfigClient) DeleteView(ctx context.Context, req *loggingpb.DeleteViewRequest, opts ...gax.CallOption) error { +func (c *configGRPCClient) DeleteView(ctx context.Context, req *loggingpb.DeleteViewRequest, opts ...gax.CallOption) error { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteView[0:len(c.CallOptions.DeleteView):len(c.CallOptions.DeleteView)], opts...) + opts = append((*c.CallOptions).DeleteView[0:len((*c.CallOptions).DeleteView):len((*c.CallOptions).DeleteView)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.configClient.DeleteView(ctx, req, settings.GRPC...) @@ -504,11 +707,10 @@ func (c *ConfigClient) DeleteView(ctx context.Context, req *loggingpb.DeleteView return err } -// ListSinks lists sinks. -func (c *ConfigClient) ListSinks(ctx context.Context, req *loggingpb.ListSinksRequest, opts ...gax.CallOption) *LogSinkIterator { +func (c *configGRPCClient) ListSinks(ctx context.Context, req *loggingpb.ListSinksRequest, opts ...gax.CallOption) *LogSinkIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSinks[0:len(c.CallOptions.ListSinks):len(c.CallOptions.ListSinks)], opts...) + opts = append((*c.CallOptions).ListSinks[0:len((*c.CallOptions).ListSinks):len((*c.CallOptions).ListSinks)], opts...) it := &LogSinkIterator{} req = proto.Clone(req).(*loggingpb.ListSinksRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*loggingpb.LogSink, string, error) { @@ -545,8 +747,7 @@ func (c *ConfigClient) ListSinks(ctx context.Context, req *loggingpb.ListSinksRe return it } -// GetSink gets a sink. -func (c *ConfigClient) GetSink(ctx context.Context, req *loggingpb.GetSinkRequest, opts ...gax.CallOption) (*loggingpb.LogSink, error) { +func (c *configGRPCClient) GetSink(ctx context.Context, req *loggingpb.GetSinkRequest, opts ...gax.CallOption) (*loggingpb.LogSink, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -554,7 +755,7 @@ func (c *ConfigClient) GetSink(ctx context.Context, req *loggingpb.GetSinkReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "sink_name", url.QueryEscape(req.GetSinkName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSink[0:len(c.CallOptions.GetSink):len(c.CallOptions.GetSink)], opts...) + opts = append((*c.CallOptions).GetSink[0:len((*c.CallOptions).GetSink):len((*c.CallOptions).GetSink)], opts...) var resp *loggingpb.LogSink err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -567,11 +768,7 @@ func (c *ConfigClient) GetSink(ctx context.Context, req *loggingpb.GetSinkReques return resp, nil } -// CreateSink creates a sink that exports specified log entries to a destination. The -// export of newly-ingested log entries begins immediately, unless the sink’s -// writer_identity is not permitted to write to the destination. A sink can -// export log entries only from the resource owning the sink. -func (c *ConfigClient) CreateSink(ctx context.Context, req *loggingpb.CreateSinkRequest, opts ...gax.CallOption) (*loggingpb.LogSink, error) { +func (c *configGRPCClient) CreateSink(ctx context.Context, req *loggingpb.CreateSinkRequest, opts ...gax.CallOption) (*loggingpb.LogSink, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -579,7 +776,7 @@ func (c *ConfigClient) CreateSink(ctx context.Context, req *loggingpb.CreateSink } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSink[0:len(c.CallOptions.CreateSink):len(c.CallOptions.CreateSink)], opts...) + opts = append((*c.CallOptions).CreateSink[0:len((*c.CallOptions).CreateSink):len((*c.CallOptions).CreateSink)], opts...) var resp *loggingpb.LogSink err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -592,12 +789,7 @@ func (c *ConfigClient) CreateSink(ctx context.Context, req *loggingpb.CreateSink return resp, nil } -// UpdateSink updates a sink. This method replaces the following fields in the existing -// sink with values from the new sink: destination, and filter. -// -// The updated sink might also have a new writer_identity; see the -// unique_writer_identity field. -func (c *ConfigClient) UpdateSink(ctx context.Context, req *loggingpb.UpdateSinkRequest, opts ...gax.CallOption) (*loggingpb.LogSink, error) { +func (c *configGRPCClient) UpdateSink(ctx context.Context, req *loggingpb.UpdateSinkRequest, opts ...gax.CallOption) (*loggingpb.LogSink, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -605,7 +797,7 @@ func (c *ConfigClient) UpdateSink(ctx context.Context, req *loggingpb.UpdateSink } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "sink_name", url.QueryEscape(req.GetSinkName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSink[0:len(c.CallOptions.UpdateSink):len(c.CallOptions.UpdateSink)], opts...) + opts = append((*c.CallOptions).UpdateSink[0:len((*c.CallOptions).UpdateSink):len((*c.CallOptions).UpdateSink)], opts...) var resp *loggingpb.LogSink err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -618,9 +810,7 @@ func (c *ConfigClient) UpdateSink(ctx context.Context, req *loggingpb.UpdateSink return resp, nil } -// DeleteSink deletes a sink. If the sink has a unique writer_identity, then that -// service account is also deleted. -func (c *ConfigClient) DeleteSink(ctx context.Context, req *loggingpb.DeleteSinkRequest, opts ...gax.CallOption) error { +func (c *configGRPCClient) DeleteSink(ctx context.Context, req *loggingpb.DeleteSinkRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -628,7 +818,7 @@ func (c *ConfigClient) DeleteSink(ctx context.Context, req *loggingpb.DeleteSink } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "sink_name", url.QueryEscape(req.GetSinkName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteSink[0:len(c.CallOptions.DeleteSink):len(c.CallOptions.DeleteSink)], opts...) + opts = append((*c.CallOptions).DeleteSink[0:len((*c.CallOptions).DeleteSink):len((*c.CallOptions).DeleteSink)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.configClient.DeleteSink(ctx, req, settings.GRPC...) @@ -637,11 +827,10 @@ func (c *ConfigClient) DeleteSink(ctx context.Context, req *loggingpb.DeleteSink return err } -// ListExclusions lists all the exclusions in a parent resource. -func (c *ConfigClient) ListExclusions(ctx context.Context, req *loggingpb.ListExclusionsRequest, opts ...gax.CallOption) *LogExclusionIterator { +func (c *configGRPCClient) ListExclusions(ctx context.Context, req *loggingpb.ListExclusionsRequest, opts ...gax.CallOption) *LogExclusionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListExclusions[0:len(c.CallOptions.ListExclusions):len(c.CallOptions.ListExclusions)], opts...) + opts = append((*c.CallOptions).ListExclusions[0:len((*c.CallOptions).ListExclusions):len((*c.CallOptions).ListExclusions)], opts...) it := &LogExclusionIterator{} req = proto.Clone(req).(*loggingpb.ListExclusionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*loggingpb.LogExclusion, string, error) { @@ -678,8 +867,7 @@ func (c *ConfigClient) ListExclusions(ctx context.Context, req *loggingpb.ListEx return it } -// GetExclusion gets the description of an exclusion. -func (c *ConfigClient) GetExclusion(ctx context.Context, req *loggingpb.GetExclusionRequest, opts ...gax.CallOption) (*loggingpb.LogExclusion, error) { +func (c *configGRPCClient) GetExclusion(ctx context.Context, req *loggingpb.GetExclusionRequest, opts ...gax.CallOption) (*loggingpb.LogExclusion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -687,7 +875,7 @@ func (c *ConfigClient) GetExclusion(ctx context.Context, req *loggingpb.GetExclu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetExclusion[0:len(c.CallOptions.GetExclusion):len(c.CallOptions.GetExclusion)], opts...) + opts = append((*c.CallOptions).GetExclusion[0:len((*c.CallOptions).GetExclusion):len((*c.CallOptions).GetExclusion)], opts...) var resp *loggingpb.LogExclusion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -700,10 +888,7 @@ func (c *ConfigClient) GetExclusion(ctx context.Context, req *loggingpb.GetExclu return resp, nil } -// CreateExclusion creates a new exclusion in a specified parent resource. -// Only log entries belonging to that resource can be excluded. -// You can have up to 10 exclusions in a resource. -func (c *ConfigClient) CreateExclusion(ctx context.Context, req *loggingpb.CreateExclusionRequest, opts ...gax.CallOption) (*loggingpb.LogExclusion, error) { +func (c *configGRPCClient) CreateExclusion(ctx context.Context, req *loggingpb.CreateExclusionRequest, opts ...gax.CallOption) (*loggingpb.LogExclusion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -711,7 +896,7 @@ func (c *ConfigClient) CreateExclusion(ctx context.Context, req *loggingpb.Creat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateExclusion[0:len(c.CallOptions.CreateExclusion):len(c.CallOptions.CreateExclusion)], opts...) + opts = append((*c.CallOptions).CreateExclusion[0:len((*c.CallOptions).CreateExclusion):len((*c.CallOptions).CreateExclusion)], opts...) var resp *loggingpb.LogExclusion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -724,8 +909,7 @@ func (c *ConfigClient) CreateExclusion(ctx context.Context, req *loggingpb.Creat return resp, nil } -// UpdateExclusion changes one or more properties of an existing exclusion. -func (c *ConfigClient) UpdateExclusion(ctx context.Context, req *loggingpb.UpdateExclusionRequest, opts ...gax.CallOption) (*loggingpb.LogExclusion, error) { +func (c *configGRPCClient) UpdateExclusion(ctx context.Context, req *loggingpb.UpdateExclusionRequest, opts ...gax.CallOption) (*loggingpb.LogExclusion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -733,7 +917,7 @@ func (c *ConfigClient) UpdateExclusion(ctx context.Context, req *loggingpb.Updat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateExclusion[0:len(c.CallOptions.UpdateExclusion):len(c.CallOptions.UpdateExclusion)], opts...) + opts = append((*c.CallOptions).UpdateExclusion[0:len((*c.CallOptions).UpdateExclusion):len((*c.CallOptions).UpdateExclusion)], opts...) var resp *loggingpb.LogExclusion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -746,8 +930,7 @@ func (c *ConfigClient) UpdateExclusion(ctx context.Context, req *loggingpb.Updat return resp, nil } -// DeleteExclusion deletes an exclusion. -func (c *ConfigClient) DeleteExclusion(ctx context.Context, req *loggingpb.DeleteExclusionRequest, opts ...gax.CallOption) error { +func (c *configGRPCClient) DeleteExclusion(ctx context.Context, req *loggingpb.DeleteExclusionRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -755,7 +938,7 @@ func (c *ConfigClient) DeleteExclusion(ctx context.Context, req *loggingpb.Delet } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteExclusion[0:len(c.CallOptions.DeleteExclusion):len(c.CallOptions.DeleteExclusion)], opts...) + opts = append((*c.CallOptions).DeleteExclusion[0:len((*c.CallOptions).DeleteExclusion):len((*c.CallOptions).DeleteExclusion)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.configClient.DeleteExclusion(ctx, req, settings.GRPC...) @@ -764,19 +947,10 @@ func (c *ConfigClient) DeleteExclusion(ctx context.Context, req *loggingpb.Delet return err } -// GetCmekSettings gets the Logs Router CMEK settings for the given resource. -// -// Note: CMEK for the Logs Router can currently only be configured for GCP -// organizations. Once configured, it applies to all projects and folders in -// the GCP organization. -// -// See Enabling CMEK for Logs -// Router (at https://cloud.google.com/logging/docs/routing/managed-encryption) -// for more information. -func (c *ConfigClient) GetCmekSettings(ctx context.Context, req *loggingpb.GetCmekSettingsRequest, opts ...gax.CallOption) (*loggingpb.CmekSettings, error) { +func (c *configGRPCClient) GetCmekSettings(ctx context.Context, req *loggingpb.GetCmekSettingsRequest, opts ...gax.CallOption) (*loggingpb.CmekSettings, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCmekSettings[0:len(c.CallOptions.GetCmekSettings):len(c.CallOptions.GetCmekSettings)], opts...) + opts = append((*c.CallOptions).GetCmekSettings[0:len((*c.CallOptions).GetCmekSettings):len((*c.CallOptions).GetCmekSettings)], opts...) var resp *loggingpb.CmekSettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -789,25 +963,10 @@ func (c *ConfigClient) GetCmekSettings(ctx context.Context, req *loggingpb.GetCm return resp, nil } -// UpdateCmekSettings updates the Logs Router CMEK settings for the given resource. -// -// Note: CMEK for the Logs Router can currently only be configured for GCP -// organizations. Once configured, it applies to all projects and folders in -// the GCP organization. -// -// UpdateCmekSettings -// will fail if 1) kms_key_name is invalid, or 2) the associated service -// account does not have the required -// roles/cloudkms.cryptoKeyEncrypterDecrypter role assigned for the key, or -// 3) access to the key is disabled. -// -// See Enabling CMEK for Logs -// Router (at https://cloud.google.com/logging/docs/routing/managed-encryption) -// for more information. -func (c *ConfigClient) UpdateCmekSettings(ctx context.Context, req *loggingpb.UpdateCmekSettingsRequest, opts ...gax.CallOption) (*loggingpb.CmekSettings, error) { +func (c *configGRPCClient) UpdateCmekSettings(ctx context.Context, req *loggingpb.UpdateCmekSettingsRequest, opts ...gax.CallOption) (*loggingpb.CmekSettings, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCmekSettings[0:len(c.CallOptions.UpdateCmekSettings):len(c.CallOptions.UpdateCmekSettings)], opts...) + opts = append((*c.CallOptions).UpdateCmekSettings[0:len((*c.CallOptions).UpdateCmekSettings):len((*c.CallOptions).UpdateCmekSettings)], opts...) var resp *loggingpb.CmekSettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/logging/apiv2/config_client_example_test.go b/logging/apiv2/config_client_example_test.go index 9ddfe373eb08..ac15032ccd2b 100644 --- a/logging/apiv2/config_client_example_test.go +++ b/logging/apiv2/config_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewConfigClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleConfigClient_ListBuckets() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.ListBucketsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleConfigClient_ListBuckets() { } func ExampleConfigClient_GetBucket() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.GetBucketRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleConfigClient_GetBucket() { } func ExampleConfigClient_CreateBucket() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.CreateBucketRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleConfigClient_CreateBucket() { } func ExampleConfigClient_UpdateBucket() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.UpdateBucketRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleConfigClient_DeleteBucket() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.DeleteBucketRequest{ // TODO: Fill request struct fields. @@ -143,6 +141,7 @@ func ExampleConfigClient_UndeleteBucket() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.UndeleteBucketRequest{ // TODO: Fill request struct fields. @@ -154,14 +153,12 @@ func ExampleConfigClient_UndeleteBucket() { } func ExampleConfigClient_ListViews() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.ListViewsRequest{ // TODO: Fill request struct fields. @@ -181,13 +178,12 @@ func ExampleConfigClient_ListViews() { } func ExampleConfigClient_GetView() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.GetViewRequest{ // TODO: Fill request struct fields. @@ -201,13 +197,12 @@ func ExampleConfigClient_GetView() { } func ExampleConfigClient_CreateView() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.CreateViewRequest{ // TODO: Fill request struct fields. @@ -221,13 +216,12 @@ func ExampleConfigClient_CreateView() { } func ExampleConfigClient_UpdateView() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.UpdateViewRequest{ // TODO: Fill request struct fields. @@ -246,6 +240,7 @@ func ExampleConfigClient_DeleteView() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.DeleteViewRequest{ // TODO: Fill request struct fields. @@ -257,14 +252,12 @@ func ExampleConfigClient_DeleteView() { } func ExampleConfigClient_ListSinks() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.ListSinksRequest{ // TODO: Fill request struct fields. @@ -284,13 +277,12 @@ func ExampleConfigClient_ListSinks() { } func ExampleConfigClient_GetSink() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.GetSinkRequest{ // TODO: Fill request struct fields. @@ -304,13 +296,12 @@ func ExampleConfigClient_GetSink() { } func ExampleConfigClient_CreateSink() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.CreateSinkRequest{ // TODO: Fill request struct fields. @@ -324,13 +315,12 @@ func ExampleConfigClient_CreateSink() { } func ExampleConfigClient_UpdateSink() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.UpdateSinkRequest{ // TODO: Fill request struct fields. @@ -349,6 +339,7 @@ func ExampleConfigClient_DeleteSink() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.DeleteSinkRequest{ // TODO: Fill request struct fields. @@ -360,14 +351,12 @@ func ExampleConfigClient_DeleteSink() { } func ExampleConfigClient_ListExclusions() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.ListExclusionsRequest{ // TODO: Fill request struct fields. @@ -387,13 +376,12 @@ func ExampleConfigClient_ListExclusions() { } func ExampleConfigClient_GetExclusion() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.GetExclusionRequest{ // TODO: Fill request struct fields. @@ -407,13 +395,12 @@ func ExampleConfigClient_GetExclusion() { } func ExampleConfigClient_CreateExclusion() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.CreateExclusionRequest{ // TODO: Fill request struct fields. @@ -427,13 +414,12 @@ func ExampleConfigClient_CreateExclusion() { } func ExampleConfigClient_UpdateExclusion() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.UpdateExclusionRequest{ // TODO: Fill request struct fields. @@ -452,6 +438,7 @@ func ExampleConfigClient_DeleteExclusion() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.DeleteExclusionRequest{ // TODO: Fill request struct fields. @@ -463,13 +450,12 @@ func ExampleConfigClient_DeleteExclusion() { } func ExampleConfigClient_GetCmekSettings() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.GetCmekSettingsRequest{ // TODO: Fill request struct fields. @@ -483,13 +469,12 @@ func ExampleConfigClient_GetCmekSettings() { } func ExampleConfigClient_UpdateCmekSettings() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewConfigClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.UpdateCmekSettingsRequest{ // TODO: Fill request struct fields. diff --git a/logging/apiv2/doc.go b/logging/apiv2/doc.go index f4dd7cc056bf..df3261af5739 100644 --- a/logging/apiv2/doc.go +++ b/logging/apiv2/doc.go @@ -20,7 +20,8 @@ // Writes log entries and manages your Cloud Logging configuration. The table // entries below are presented in alphabetical order, not in order of common // use. For explanations of the concepts found in the table entries, read the -// documentation at https://cloud.google.com/logging/docs. +// documentation at https://cloud.google.com/logging/docs (at +// https://cloud.google.com/logging/docs). // // Use of Context // @@ -31,7 +32,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package logging // import "cloud.google.com/go/logging/apiv2" import ( @@ -51,7 +52,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/logging/apiv2/logging_client.go b/logging/apiv2/logging_client.go index 2ee165ce1cd6..f89de0088acc 100644 --- a/logging/apiv2/logging_client.go +++ b/logging/apiv2/logging_client.go @@ -48,7 +48,7 @@ type CallOptions struct { TailLogEntries []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("logging.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("logging.mtls.googleapis.com:443"), @@ -143,32 +143,123 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Logging API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + DeleteLog(context.Context, *loggingpb.DeleteLogRequest, ...gax.CallOption) error + WriteLogEntries(context.Context, *loggingpb.WriteLogEntriesRequest, ...gax.CallOption) (*loggingpb.WriteLogEntriesResponse, error) + ListLogEntries(context.Context, *loggingpb.ListLogEntriesRequest, ...gax.CallOption) *LogEntryIterator + ListMonitoredResourceDescriptors(context.Context, *loggingpb.ListMonitoredResourceDescriptorsRequest, ...gax.CallOption) *MonitoredResourceDescriptorIterator + ListLogs(context.Context, *loggingpb.ListLogsRequest, ...gax.CallOption) *StringIterator + TailLogEntries(context.Context, ...gax.CallOption) (loggingpb.LoggingServiceV2_TailLogEntriesClient, error) +} + // Client is a client for interacting with Cloud Logging API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for ingesting and querying logs. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// DeleteLog deletes all the log entries in a log. The log reappears if it receives new +// entries. Log entries written shortly before the delete operation might not +// be deleted. Entries received after the delete operation with a timestamp +// before the operation will be deleted. +func (c *Client) DeleteLog(ctx context.Context, req *loggingpb.DeleteLogRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteLog(ctx, req, opts...) +} + +// WriteLogEntries writes log entries to Logging. This API method is the +// only way to send log entries to Logging. This method +// is used, directly or indirectly, by the Logging agent +// (fluentd) and all logging libraries configured to use Logging. +// A single request may contain log entries for a maximum of 1000 +// different resources (projects, organizations, billing accounts or +// folders) +func (c *Client) WriteLogEntries(ctx context.Context, req *loggingpb.WriteLogEntriesRequest, opts ...gax.CallOption) (*loggingpb.WriteLogEntriesResponse, error) { + return c.internalClient.WriteLogEntries(ctx, req, opts...) +} + +// ListLogEntries lists log entries. Use this method to retrieve log entries that originated +// from a project/folder/organization/billing account. For ways to export log +// entries, see Exporting +// Logs (at https://cloud.google.com/logging/docs/export). +func (c *Client) ListLogEntries(ctx context.Context, req *loggingpb.ListLogEntriesRequest, opts ...gax.CallOption) *LogEntryIterator { + return c.internalClient.ListLogEntries(ctx, req, opts...) +} + +// ListMonitoredResourceDescriptors lists the descriptors for monitored resource types used by Logging. +func (c *Client) ListMonitoredResourceDescriptors(ctx context.Context, req *loggingpb.ListMonitoredResourceDescriptorsRequest, opts ...gax.CallOption) *MonitoredResourceDescriptorIterator { + return c.internalClient.ListMonitoredResourceDescriptors(ctx, req, opts...) +} + +// ListLogs lists the logs in projects, organizations, folders, or billing accounts. +// Only logs that have entries are listed. +func (c *Client) ListLogs(ctx context.Context, req *loggingpb.ListLogsRequest, opts ...gax.CallOption) *StringIterator { + return c.internalClient.ListLogs(ctx, req, opts...) +} + +// TailLogEntries streaming read of log entries as they are ingested. Until the stream is +// terminated, it will continue reading logs. +func (c *Client) TailLogEntries(ctx context.Context, opts ...gax.CallOption) (loggingpb.LoggingServiceV2_TailLogEntriesClient, error) { + return c.internalClient.TailLogEntries(ctx, opts...) +} + +// gRPCClient is a client for interacting with Cloud Logging API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client loggingpb.LoggingServiceV2Client - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new logging service v2 client. +// NewClient creates a new logging service v2 client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for ingesting and querying logs. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -186,45 +277,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: loggingpb.NewLoggingServiceV2Client(connPool), + client: loggingpb.NewLoggingServiceV2Client(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// DeleteLog deletes all the log entries in a log. The log reappears if it receives new -// entries. Log entries written shortly before the delete operation might not -// be deleted. Entries received after the delete operation with a timestamp -// before the operation will be deleted. -func (c *Client) DeleteLog(ctx context.Context, req *loggingpb.DeleteLogRequest, opts ...gax.CallOption) error { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) DeleteLog(ctx context.Context, req *loggingpb.DeleteLogRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -232,7 +322,7 @@ func (c *Client) DeleteLog(ctx context.Context, req *loggingpb.DeleteLogRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "log_name", url.QueryEscape(req.GetLogName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteLog[0:len(c.CallOptions.DeleteLog):len(c.CallOptions.DeleteLog)], opts...) + opts = append((*c.CallOptions).DeleteLog[0:len((*c.CallOptions).DeleteLog):len((*c.CallOptions).DeleteLog)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteLog(ctx, req, settings.GRPC...) @@ -241,21 +331,14 @@ func (c *Client) DeleteLog(ctx context.Context, req *loggingpb.DeleteLogRequest, return err } -// WriteLogEntries writes log entries to Logging. This API method is the -// only way to send log entries to Logging. This method -// is used, directly or indirectly, by the Logging agent -// (fluentd) and all logging libraries configured to use Logging. -// A single request may contain log entries for a maximum of 1000 -// different resources (projects, organizations, billing accounts or -// folders) -func (c *Client) WriteLogEntries(ctx context.Context, req *loggingpb.WriteLogEntriesRequest, opts ...gax.CallOption) (*loggingpb.WriteLogEntriesResponse, error) { +func (c *gRPCClient) WriteLogEntries(ctx context.Context, req *loggingpb.WriteLogEntriesRequest, opts ...gax.CallOption) (*loggingpb.WriteLogEntriesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.WriteLogEntries[0:len(c.CallOptions.WriteLogEntries):len(c.CallOptions.WriteLogEntries)], opts...) + opts = append((*c.CallOptions).WriteLogEntries[0:len((*c.CallOptions).WriteLogEntries):len((*c.CallOptions).WriteLogEntries)], opts...) var resp *loggingpb.WriteLogEntriesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -268,13 +351,9 @@ func (c *Client) WriteLogEntries(ctx context.Context, req *loggingpb.WriteLogEnt return resp, nil } -// ListLogEntries lists log entries. Use this method to retrieve log entries that originated -// from a project/folder/organization/billing account. For ways to export log -// entries, see Exporting -// Logs (at https://cloud.google.com/logging/docs/export). -func (c *Client) ListLogEntries(ctx context.Context, req *loggingpb.ListLogEntriesRequest, opts ...gax.CallOption) *LogEntryIterator { +func (c *gRPCClient) ListLogEntries(ctx context.Context, req *loggingpb.ListLogEntriesRequest, opts ...gax.CallOption) *LogEntryIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListLogEntries[0:len(c.CallOptions.ListLogEntries):len(c.CallOptions.ListLogEntries)], opts...) + opts = append((*c.CallOptions).ListLogEntries[0:len((*c.CallOptions).ListLogEntries):len((*c.CallOptions).ListLogEntries)], opts...) it := &LogEntryIterator{} req = proto.Clone(req).(*loggingpb.ListLogEntriesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*loggingpb.LogEntry, string, error) { @@ -311,10 +390,9 @@ func (c *Client) ListLogEntries(ctx context.Context, req *loggingpb.ListLogEntri return it } -// ListMonitoredResourceDescriptors lists the descriptors for monitored resource types used by Logging. -func (c *Client) ListMonitoredResourceDescriptors(ctx context.Context, req *loggingpb.ListMonitoredResourceDescriptorsRequest, opts ...gax.CallOption) *MonitoredResourceDescriptorIterator { +func (c *gRPCClient) ListMonitoredResourceDescriptors(ctx context.Context, req *loggingpb.ListMonitoredResourceDescriptorsRequest, opts ...gax.CallOption) *MonitoredResourceDescriptorIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListMonitoredResourceDescriptors[0:len(c.CallOptions.ListMonitoredResourceDescriptors):len(c.CallOptions.ListMonitoredResourceDescriptors)], opts...) + opts = append((*c.CallOptions).ListMonitoredResourceDescriptors[0:len((*c.CallOptions).ListMonitoredResourceDescriptors):len((*c.CallOptions).ListMonitoredResourceDescriptors)], opts...) it := &MonitoredResourceDescriptorIterator{} req = proto.Clone(req).(*loggingpb.ListMonitoredResourceDescriptorsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoredrespb.MonitoredResourceDescriptor, string, error) { @@ -351,12 +429,10 @@ func (c *Client) ListMonitoredResourceDescriptors(ctx context.Context, req *logg return it } -// ListLogs lists the logs in projects, organizations, folders, or billing accounts. -// Only logs that have entries are listed. -func (c *Client) ListLogs(ctx context.Context, req *loggingpb.ListLogsRequest, opts ...gax.CallOption) *StringIterator { +func (c *gRPCClient) ListLogs(ctx context.Context, req *loggingpb.ListLogsRequest, opts ...gax.CallOption) *StringIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListLogs[0:len(c.CallOptions.ListLogs):len(c.CallOptions.ListLogs)], opts...) + opts = append((*c.CallOptions).ListLogs[0:len((*c.CallOptions).ListLogs):len((*c.CallOptions).ListLogs)], opts...) it := &StringIterator{} req = proto.Clone(req).(*loggingpb.ListLogsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]string, string, error) { @@ -393,12 +469,10 @@ func (c *Client) ListLogs(ctx context.Context, req *loggingpb.ListLogsRequest, o return it } -// TailLogEntries streaming read of log entries as they are ingested. Until the stream is -// terminated, it will continue reading logs. -func (c *Client) TailLogEntries(ctx context.Context, opts ...gax.CallOption) (loggingpb.LoggingServiceV2_TailLogEntriesClient, error) { +func (c *gRPCClient) TailLogEntries(ctx context.Context, opts ...gax.CallOption) (loggingpb.LoggingServiceV2_TailLogEntriesClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.TailLogEntries[0:len(c.CallOptions.TailLogEntries):len(c.CallOptions.TailLogEntries)], opts...) var resp loggingpb.LoggingServiceV2_TailLogEntriesClient + opts = append((*c.CallOptions).TailLogEntries[0:len((*c.CallOptions).TailLogEntries):len((*c.CallOptions).TailLogEntries)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.client.TailLogEntries(ctx, settings.GRPC...) diff --git a/logging/apiv2/logging_client_example_test.go b/logging/apiv2/logging_client_example_test.go index 12c96f3e4bee..9401b6199bcb 100644 --- a/logging/apiv2/logging_client_example_test.go +++ b/logging/apiv2/logging_client_example_test.go @@ -31,6 +31,8 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } @@ -41,6 +43,7 @@ func ExampleClient_DeleteLog() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.DeleteLogRequest{ // TODO: Fill request struct fields. @@ -52,13 +55,12 @@ func ExampleClient_DeleteLog() { } func ExampleClient_WriteLogEntries() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.WriteLogEntriesRequest{ // TODO: Fill request struct fields. @@ -72,14 +74,12 @@ func ExampleClient_WriteLogEntries() { } func ExampleClient_ListLogEntries() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := logging.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.ListLogEntriesRequest{ // TODO: Fill request struct fields. @@ -99,14 +99,12 @@ func ExampleClient_ListLogEntries() { } func ExampleClient_ListMonitoredResourceDescriptors() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := logging.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.ListMonitoredResourceDescriptorsRequest{ // TODO: Fill request struct fields. @@ -126,14 +124,12 @@ func ExampleClient_ListMonitoredResourceDescriptors() { } func ExampleClient_ListLogs() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := logging.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.ListLogsRequest{ // TODO: Fill request struct fields. @@ -153,13 +149,12 @@ func ExampleClient_ListLogs() { } func ExampleClient_TailLogEntries() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.TailLogEntries(ctx) if err != nil { // TODO: Handle error. diff --git a/logging/apiv2/metrics_client.go b/logging/apiv2/metrics_client.go index 051282083db7..a322208c2a61 100644 --- a/logging/apiv2/metrics_client.go +++ b/logging/apiv2/metrics_client.go @@ -46,7 +46,7 @@ type MetricsCallOptions struct { DeleteLogMetric []gax.CallOption } -func defaultMetricsClientOptions() []option.ClientOption { +func defaultMetricsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("logging.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("logging.mtls.googleapis.com:443"), @@ -116,32 +116,103 @@ func defaultMetricsCallOptions() *MetricsCallOptions { } } +// internalMetricsClient is an interface that defines the methods availaible from Cloud Logging API. +type internalMetricsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListLogMetrics(context.Context, *loggingpb.ListLogMetricsRequest, ...gax.CallOption) *LogMetricIterator + GetLogMetric(context.Context, *loggingpb.GetLogMetricRequest, ...gax.CallOption) (*loggingpb.LogMetric, error) + CreateLogMetric(context.Context, *loggingpb.CreateLogMetricRequest, ...gax.CallOption) (*loggingpb.LogMetric, error) + UpdateLogMetric(context.Context, *loggingpb.UpdateLogMetricRequest, ...gax.CallOption) (*loggingpb.LogMetric, error) + DeleteLogMetric(context.Context, *loggingpb.DeleteLogMetricRequest, ...gax.CallOption) error +} + // MetricsClient is a client for interacting with Cloud Logging API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for configuring logs-based metrics. type MetricsClient struct { + // The internal transport-dependent client. + internalClient internalMetricsClient + + // The call options for this service. + CallOptions *MetricsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *MetricsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *MetricsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *MetricsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListLogMetrics lists logs-based metrics. +func (c *MetricsClient) ListLogMetrics(ctx context.Context, req *loggingpb.ListLogMetricsRequest, opts ...gax.CallOption) *LogMetricIterator { + return c.internalClient.ListLogMetrics(ctx, req, opts...) +} + +// GetLogMetric gets a logs-based metric. +func (c *MetricsClient) GetLogMetric(ctx context.Context, req *loggingpb.GetLogMetricRequest, opts ...gax.CallOption) (*loggingpb.LogMetric, error) { + return c.internalClient.GetLogMetric(ctx, req, opts...) +} + +// CreateLogMetric creates a logs-based metric. +func (c *MetricsClient) CreateLogMetric(ctx context.Context, req *loggingpb.CreateLogMetricRequest, opts ...gax.CallOption) (*loggingpb.LogMetric, error) { + return c.internalClient.CreateLogMetric(ctx, req, opts...) +} + +// UpdateLogMetric creates or updates a logs-based metric. +func (c *MetricsClient) UpdateLogMetric(ctx context.Context, req *loggingpb.UpdateLogMetricRequest, opts ...gax.CallOption) (*loggingpb.LogMetric, error) { + return c.internalClient.UpdateLogMetric(ctx, req, opts...) +} + +// DeleteLogMetric deletes a logs-based metric. +func (c *MetricsClient) DeleteLogMetric(ctx context.Context, req *loggingpb.DeleteLogMetricRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteLogMetric(ctx, req, opts...) +} + +// metricsGRPCClient is a client for interacting with Cloud Logging API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type metricsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing MetricsClient + CallOptions **MetricsCallOptions + // The gRPC API client. metricsClient loggingpb.MetricsServiceV2Client - // The call options for this service. - CallOptions *MetricsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewMetricsClient creates a new metrics service v2 client. +// NewMetricsClient creates a new metrics service v2 client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for configuring logs-based metrics. func NewMetricsClient(ctx context.Context, opts ...option.ClientOption) (*MetricsClient, error) { - clientOpts := defaultMetricsClientOptions() - + clientOpts := defaultMetricsGRPCClientOptions() if newMetricsClientHook != nil { hookOpts, err := newMetricsClientHook(ctx, clientHookParams{}) if err != nil { @@ -159,45 +230,47 @@ func NewMetricsClient(ctx context.Context, opts ...option.ClientOption) (*Metric if err != nil { return nil, err } - c := &MetricsClient{ + client := MetricsClient{CallOptions: defaultMetricsCallOptions()} + + c := &metricsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultMetricsCallOptions(), - - metricsClient: loggingpb.NewMetricsServiceV2Client(connPool), + metricsClient: loggingpb.NewMetricsServiceV2Client(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *MetricsClient) Connection() *grpc.ClientConn { +func (c *metricsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *MetricsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *MetricsClient) setGoogleClientInfo(keyval ...string) { +func (c *metricsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListLogMetrics lists logs-based metrics. -func (c *MetricsClient) ListLogMetrics(ctx context.Context, req *loggingpb.ListLogMetricsRequest, opts ...gax.CallOption) *LogMetricIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *metricsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *metricsGRPCClient) ListLogMetrics(ctx context.Context, req *loggingpb.ListLogMetricsRequest, opts ...gax.CallOption) *LogMetricIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListLogMetrics[0:len(c.CallOptions.ListLogMetrics):len(c.CallOptions.ListLogMetrics)], opts...) + opts = append((*c.CallOptions).ListLogMetrics[0:len((*c.CallOptions).ListLogMetrics):len((*c.CallOptions).ListLogMetrics)], opts...) it := &LogMetricIterator{} req = proto.Clone(req).(*loggingpb.ListLogMetricsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*loggingpb.LogMetric, string, error) { @@ -234,8 +307,7 @@ func (c *MetricsClient) ListLogMetrics(ctx context.Context, req *loggingpb.ListL return it } -// GetLogMetric gets a logs-based metric. -func (c *MetricsClient) GetLogMetric(ctx context.Context, req *loggingpb.GetLogMetricRequest, opts ...gax.CallOption) (*loggingpb.LogMetric, error) { +func (c *metricsGRPCClient) GetLogMetric(ctx context.Context, req *loggingpb.GetLogMetricRequest, opts ...gax.CallOption) (*loggingpb.LogMetric, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -243,7 +315,7 @@ func (c *MetricsClient) GetLogMetric(ctx context.Context, req *loggingpb.GetLogM } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "metric_name", url.QueryEscape(req.GetMetricName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetLogMetric[0:len(c.CallOptions.GetLogMetric):len(c.CallOptions.GetLogMetric)], opts...) + opts = append((*c.CallOptions).GetLogMetric[0:len((*c.CallOptions).GetLogMetric):len((*c.CallOptions).GetLogMetric)], opts...) var resp *loggingpb.LogMetric err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -256,8 +328,7 @@ func (c *MetricsClient) GetLogMetric(ctx context.Context, req *loggingpb.GetLogM return resp, nil } -// CreateLogMetric creates a logs-based metric. -func (c *MetricsClient) CreateLogMetric(ctx context.Context, req *loggingpb.CreateLogMetricRequest, opts ...gax.CallOption) (*loggingpb.LogMetric, error) { +func (c *metricsGRPCClient) CreateLogMetric(ctx context.Context, req *loggingpb.CreateLogMetricRequest, opts ...gax.CallOption) (*loggingpb.LogMetric, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -265,7 +336,7 @@ func (c *MetricsClient) CreateLogMetric(ctx context.Context, req *loggingpb.Crea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateLogMetric[0:len(c.CallOptions.CreateLogMetric):len(c.CallOptions.CreateLogMetric)], opts...) + opts = append((*c.CallOptions).CreateLogMetric[0:len((*c.CallOptions).CreateLogMetric):len((*c.CallOptions).CreateLogMetric)], opts...) var resp *loggingpb.LogMetric err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -278,8 +349,7 @@ func (c *MetricsClient) CreateLogMetric(ctx context.Context, req *loggingpb.Crea return resp, nil } -// UpdateLogMetric creates or updates a logs-based metric. -func (c *MetricsClient) UpdateLogMetric(ctx context.Context, req *loggingpb.UpdateLogMetricRequest, opts ...gax.CallOption) (*loggingpb.LogMetric, error) { +func (c *metricsGRPCClient) UpdateLogMetric(ctx context.Context, req *loggingpb.UpdateLogMetricRequest, opts ...gax.CallOption) (*loggingpb.LogMetric, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -287,7 +357,7 @@ func (c *MetricsClient) UpdateLogMetric(ctx context.Context, req *loggingpb.Upda } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "metric_name", url.QueryEscape(req.GetMetricName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateLogMetric[0:len(c.CallOptions.UpdateLogMetric):len(c.CallOptions.UpdateLogMetric)], opts...) + opts = append((*c.CallOptions).UpdateLogMetric[0:len((*c.CallOptions).UpdateLogMetric):len((*c.CallOptions).UpdateLogMetric)], opts...) var resp *loggingpb.LogMetric err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -300,8 +370,7 @@ func (c *MetricsClient) UpdateLogMetric(ctx context.Context, req *loggingpb.Upda return resp, nil } -// DeleteLogMetric deletes a logs-based metric. -func (c *MetricsClient) DeleteLogMetric(ctx context.Context, req *loggingpb.DeleteLogMetricRequest, opts ...gax.CallOption) error { +func (c *metricsGRPCClient) DeleteLogMetric(ctx context.Context, req *loggingpb.DeleteLogMetricRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -309,7 +378,7 @@ func (c *MetricsClient) DeleteLogMetric(ctx context.Context, req *loggingpb.Dele } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "metric_name", url.QueryEscape(req.GetMetricName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteLogMetric[0:len(c.CallOptions.DeleteLogMetric):len(c.CallOptions.DeleteLogMetric)], opts...) + opts = append((*c.CallOptions).DeleteLogMetric[0:len((*c.CallOptions).DeleteLogMetric):len((*c.CallOptions).DeleteLogMetric)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.metricsClient.DeleteLogMetric(ctx, req, settings.GRPC...) diff --git a/logging/apiv2/metrics_client_example_test.go b/logging/apiv2/metrics_client_example_test.go index 9cc6669b4b95..d817c8a3fa30 100644 --- a/logging/apiv2/metrics_client_example_test.go +++ b/logging/apiv2/metrics_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewMetricsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleMetricsClient_ListLogMetrics() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := logging.NewMetricsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.ListLogMetricsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleMetricsClient_ListLogMetrics() { } func ExampleMetricsClient_GetLogMetric() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewMetricsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.GetLogMetricRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleMetricsClient_GetLogMetric() { } func ExampleMetricsClient_CreateLogMetric() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewMetricsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.CreateLogMetricRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleMetricsClient_CreateLogMetric() { } func ExampleMetricsClient_UpdateLogMetric() { - // import loggingpb "google.golang.org/genproto/googleapis/logging/v2" - ctx := context.Background() c, err := logging.NewMetricsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.UpdateLogMetricRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleMetricsClient_DeleteLogMetric() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &loggingpb.DeleteLogMetricRequest{ // TODO: Fill request struct fields. diff --git a/logging/go.mod b/logging/go.mod index 29fd22543ec9..014b0712a30c 100644 --- a/logging/go.mod +++ b/logging/go.mod @@ -10,7 +10,7 @@ require ( github.com/googleapis/gax-go/v2 v2.0.5 go.opencensus.io v0.23.0 golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c - google.golang.org/api v0.46.0 - google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a + google.golang.org/api v0.47.0 + google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d google.golang.org/grpc v1.37.1 ) diff --git a/logging/go.sum b/logging/go.sum index 4013a11716b3..98db987d9cbf 100644 --- a/logging/go.sum +++ b/logging/go.sum @@ -147,6 +147,7 @@ github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -182,8 +183,9 @@ golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5 h1:2M3HP5CCK1Si9FQhwnzYhXdG6DXeebvUHFpre8QvbyI= golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 h1:VLliZ0d+/avPrXXH+OakdXhpJuEoBZuwh1m2j7U6Iug= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= @@ -193,8 +195,9 @@ golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.1 h1:Kvvh58BN8Y9/lBi7hTekvtMpm07eUZ0ck5pRHpsMWrY= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -228,6 +231,7 @@ golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420 h1:a8jGStKg0XqKDlKqjLrXn0ioF5MH36pT7Z0BRTqLhbk= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -241,7 +245,6 @@ golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210427180440-81ed05c6b58c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c h1:pkQiBZBvdos9qq4wBAHqlzuZHEXo07pqV06ef90u1WI= golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -291,9 +294,11 @@ golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210503080704-8803ae5d1324 h1:pAwJxDByZctfPwzlNGrDN2BQLsdPb9NkhoTJtUkAO28= -golang.org/x/sys v0.0.0-20210503080704-8803ae5d1324/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015 h1:hZR0X1kPW+nwyJ9xRxqZk1vx5RUObAPBdKVvXPDUH/E= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -352,8 +357,9 @@ golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.0 h1:po9/4sTYwZU9lPhi1tOrb4hCv3qrhiQ77LZfGa2OjwY= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.1 h1:wGiQel/hW0NnEkJUk8lbzkX2gFJU6PFxf1v5OlCfuOs= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -380,8 +386,8 @@ google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34q google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= -google.golang.org/api v0.46.0 h1:jkDWHOBIoNSD0OQpq4rtBVu+Rh325MPjXG1rakAp8JU= -google.golang.org/api v0.46.0/go.mod h1:ceL4oozhkAiTID8XMmJBsIxID/9wMXJVVFXPg4ylg3I= +google.golang.org/api v0.47.0 h1:sQLWZQvP6jPGIP4JGPkJu4zHswrv81iobiyszr3b/0I= +google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -429,9 +435,9 @@ google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= -google.golang.org/genproto v0.0.0-20210429181445-86c259c2b4ab/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= -google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a h1:VA0wtJaR+W1I11P2f535J7D/YxyvEFMTMvcmyeZ9FBE= -google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d h1:bRz6UmsZEz/CzoTjUDp4ZcdguhSWi6CyU299wMQBpZU= +google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= @@ -450,7 +456,6 @@ google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA5 google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.37.1 h1:ARnQJNWxGyYJpdf/JXscNlQr/uv607ZPU9Z7ogHi+iI= google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= diff --git a/longrunning/autogen/doc.go b/longrunning/autogen/doc.go index 366f95be9f8b..a7e1f1a03540 100644 --- a/longrunning/autogen/doc.go +++ b/longrunning/autogen/doc.go @@ -17,6 +17,8 @@ // Package longrunning is an auto-generated package for the // Long Running Operations API. // +// NOTE: This package is in alpha. It is not stable, and is likely to change. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -26,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package longrunning // import "cloud.google.com/go/longrunning/autogen" import ( @@ -46,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/longrunning/autogen/operations_client.go b/longrunning/autogen/operations_client.go index 08c81fc8ab8e..b2af17068979 100644 --- a/longrunning/autogen/operations_client.go +++ b/longrunning/autogen/operations_client.go @@ -46,7 +46,7 @@ type OperationsCallOptions struct { WaitOperation []gax.CallOption } -func defaultOperationsClientOptions() []option.ClientOption { +func defaultOperationsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("longrunning.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("longrunning.mtls.googleapis.com:443"), @@ -108,27 +108,138 @@ func defaultOperationsCallOptions() *OperationsCallOptions { } } +// internalOperationsClient is an interface that defines the methods availaible from Long Running Operations API. +type internalOperationsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListOperations(context.Context, *longrunningpb.ListOperationsRequest, ...gax.CallOption) *OperationIterator + GetOperation(context.Context, *longrunningpb.GetOperationRequest, ...gax.CallOption) (*longrunningpb.Operation, error) + DeleteOperation(context.Context, *longrunningpb.DeleteOperationRequest, ...gax.CallOption) error + CancelOperation(context.Context, *longrunningpb.CancelOperationRequest, ...gax.CallOption) error + WaitOperation(context.Context, *longrunningpb.WaitOperationRequest, ...gax.CallOption) (*longrunningpb.Operation, error) +} + // OperationsClient is a client for interacting with Long Running Operations API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Manages long-running operations with an API service. +// +// When an API method normally takes long time to complete, it can be designed +// to return Operation to the client, and the client can use this +// interface to receive the real response asynchronously by polling the +// operation resource, or pass the operation resource to another API (such as +// Google Cloud Pub/Sub API) to receive the response. Any API service that +// returns long-running operations should implement the Operations interface +// so developers can have a consistent client experience. type OperationsClient struct { + // The internal transport-dependent client. + internalClient internalOperationsClient + + // The call options for this service. + CallOptions *OperationsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *OperationsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *OperationsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *OperationsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListOperations lists operations that match the specified filter in the request. If the +// server doesn’t support this method, it returns UNIMPLEMENTED. +// +// NOTE: the name binding allows API services to override the binding +// to use different resource name schemes, such as users/*/operations. To +// override the binding, API services can add a binding such as +// "/v1/{name=users/*}/operations" to their service configuration. +// For backwards compatibility, the default name includes the operations +// collection id, however overriding users must ensure the name binding +// is the parent resource, without the operations collection id. +func (c *OperationsClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { + return c.internalClient.ListOperations(ctx, req, opts...) +} + +// GetOperation gets the latest state of a long-running operation. Clients can use this +// method to poll the operation result at intervals as recommended by the API +// service. +func (c *OperationsClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + return c.internalClient.GetOperation(ctx, req, opts...) +} + +// DeleteOperation deletes a long-running operation. This method indicates that the client is +// no longer interested in the operation result. It does not cancel the +// operation. If the server doesn’t support this method, it returns +// google.rpc.Code.UNIMPLEMENTED. +func (c *OperationsClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteOperation(ctx, req, opts...) +} + +// CancelOperation starts asynchronous cancellation on a long-running operation. The server +// makes a best effort to cancel the operation, but success is not +// guaranteed. If the server doesn’t support this method, it returns +// google.rpc.Code.UNIMPLEMENTED. Clients can use +// Operations.GetOperation or +// other methods to check whether the cancellation succeeded or whether the +// operation completed despite cancellation. On successful cancellation, +// the operation is not deleted; instead, it becomes an operation with +// an Operation.error value with a google.rpc.Status.code of 1, +// corresponding to Code.CANCELLED. +func (c *OperationsClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { + return c.internalClient.CancelOperation(ctx, req, opts...) +} + +// WaitOperation waits until the specified long-running operation is done or reaches at most +// a specified timeout, returning the latest state. If the operation is +// already done, the latest state is immediately returned. If the timeout +// specified is greater than the default HTTP/RPC timeout, the HTTP/RPC +// timeout is used. If the server does not support this method, it returns +// google.rpc.Code.UNIMPLEMENTED. +// Note that this method is on a best-effort basis. It may return the latest +// state before the specified timeout (including immediately), meaning even an +// immediate response is no guarantee that the operation is done. +func (c *OperationsClient) WaitOperation(ctx context.Context, req *longrunningpb.WaitOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { + return c.internalClient.WaitOperation(ctx, req, opts...) +} + +// operationsGRPCClient is a client for interacting with Long Running Operations API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type operationsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing OperationsClient + CallOptions **OperationsCallOptions + // The gRPC API client. operationsClient longrunningpb.OperationsClient - // The call options for this service. - CallOptions *OperationsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewOperationsClient creates a new operations client. +// NewOperationsClient creates a new operations client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Manages long-running operations with an API service. // @@ -140,8 +251,7 @@ type OperationsClient struct { // returns long-running operations should implement the Operations interface // so developers can have a consistent client experience. func NewOperationsClient(ctx context.Context, opts ...option.ClientOption) (*OperationsClient, error) { - clientOpts := defaultOperationsClientOptions() - + clientOpts := defaultOperationsGRPCClientOptions() if newOperationsClientHook != nil { hookOpts, err := newOperationsClientHook(ctx, clientHookParams{}) if err != nil { @@ -159,54 +269,47 @@ func NewOperationsClient(ctx context.Context, opts ...option.ClientOption) (*Ope if err != nil { return nil, err } - c := &OperationsClient{ + client := OperationsClient{CallOptions: defaultOperationsCallOptions()} + + c := &operationsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultOperationsCallOptions(), - operationsClient: longrunningpb.NewOperationsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *OperationsClient) Connection() *grpc.ClientConn { +func (c *operationsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *OperationsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *OperationsClient) setGoogleClientInfo(keyval ...string) { +func (c *operationsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListOperations lists operations that match the specified filter in the request. If the -// server doesn’t support this method, it returns UNIMPLEMENTED. -// -// NOTE: the name binding allows API services to override the binding -// to use different resource name schemes, such as users/*/operations. To -// override the binding, API services can add a binding such as -// "/v1/{name=users/*}/operations" to their service configuration. -// For backwards compatibility, the default name includes the operations -// collection id, however overriding users must ensure the name binding -// is the parent resource, without the operations collection id. -func (c *OperationsClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *operationsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *operationsGRPCClient) ListOperations(ctx context.Context, req *longrunningpb.ListOperationsRequest, opts ...gax.CallOption) *OperationIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListOperations[0:len(c.CallOptions.ListOperations):len(c.CallOptions.ListOperations)], opts...) + opts = append((*c.CallOptions).ListOperations[0:len((*c.CallOptions).ListOperations):len((*c.CallOptions).ListOperations)], opts...) it := &OperationIterator{} req = proto.Clone(req).(*longrunningpb.ListOperationsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { @@ -243,10 +346,7 @@ func (c *OperationsClient) ListOperations(ctx context.Context, req *longrunningp return it } -// GetOperation gets the latest state of a long-running operation. Clients can use this -// method to poll the operation result at intervals as recommended by the API -// service. -func (c *OperationsClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { +func (c *operationsGRPCClient) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -254,7 +354,7 @@ func (c *OperationsClient) GetOperation(ctx context.Context, req *longrunningpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetOperation[0:len(c.CallOptions.GetOperation):len(c.CallOptions.GetOperation)], opts...) + opts = append((*c.CallOptions).GetOperation[0:len((*c.CallOptions).GetOperation):len((*c.CallOptions).GetOperation)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -267,11 +367,7 @@ func (c *OperationsClient) GetOperation(ctx context.Context, req *longrunningpb. return resp, nil } -// DeleteOperation deletes a long-running operation. This method indicates that the client is -// no longer interested in the operation result. It does not cancel the -// operation. If the server doesn’t support this method, it returns -// google.rpc.Code.UNIMPLEMENTED. -func (c *OperationsClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { +func (c *operationsGRPCClient) DeleteOperation(ctx context.Context, req *longrunningpb.DeleteOperationRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -279,7 +375,7 @@ func (c *OperationsClient) DeleteOperation(ctx context.Context, req *longrunning } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteOperation[0:len(c.CallOptions.DeleteOperation):len(c.CallOptions.DeleteOperation)], opts...) + opts = append((*c.CallOptions).DeleteOperation[0:len((*c.CallOptions).DeleteOperation):len((*c.CallOptions).DeleteOperation)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.operationsClient.DeleteOperation(ctx, req, settings.GRPC...) @@ -288,17 +384,7 @@ func (c *OperationsClient) DeleteOperation(ctx context.Context, req *longrunning return err } -// CancelOperation starts asynchronous cancellation on a long-running operation. The server -// makes a best effort to cancel the operation, but success is not -// guaranteed. If the server doesn’t support this method, it returns -// google.rpc.Code.UNIMPLEMENTED. Clients can use -// Operations.GetOperation or -// other methods to check whether the cancellation succeeded or whether the -// operation completed despite cancellation. On successful cancellation, -// the operation is not deleted; instead, it becomes an operation with -// an Operation.error value with a google.rpc.Status.code of 1, -// corresponding to Code.CANCELLED. -func (c *OperationsClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { +func (c *operationsGRPCClient) CancelOperation(ctx context.Context, req *longrunningpb.CancelOperationRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -306,7 +392,7 @@ func (c *OperationsClient) CancelOperation(ctx context.Context, req *longrunning } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CancelOperation[0:len(c.CallOptions.CancelOperation):len(c.CallOptions.CancelOperation)], opts...) + opts = append((*c.CallOptions).CancelOperation[0:len((*c.CallOptions).CancelOperation):len((*c.CallOptions).CancelOperation)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.operationsClient.CancelOperation(ctx, req, settings.GRPC...) @@ -315,18 +401,9 @@ func (c *OperationsClient) CancelOperation(ctx context.Context, req *longrunning return err } -// WaitOperation waits until the specified long-running operation is done or reaches at most -// a specified timeout, returning the latest state. If the operation is -// already done, the latest state is immediately returned. If the timeout -// specified is greater than the default HTTP/RPC timeout, the HTTP/RPC -// timeout is used. If the server does not support this method, it returns -// google.rpc.Code.UNIMPLEMENTED. -// Note that this method is on a best-effort basis. It may return the latest -// state before the specified timeout (including immediately), meaning even an -// immediate response is no guarantee that the operation is done. -func (c *OperationsClient) WaitOperation(ctx context.Context, req *longrunningpb.WaitOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { +func (c *operationsGRPCClient) WaitOperation(ctx context.Context, req *longrunningpb.WaitOperationRequest, opts ...gax.CallOption) (*longrunningpb.Operation, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.WaitOperation[0:len(c.CallOptions.WaitOperation):len(c.CallOptions.WaitOperation)], opts...) + opts = append((*c.CallOptions).WaitOperation[0:len((*c.CallOptions).WaitOperation):len((*c.CallOptions).WaitOperation)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/longrunning/autogen/operations_client_example_test.go b/longrunning/autogen/operations_client_example_test.go index b7abfbe37e68..b60f32e06778 100644 --- a/longrunning/autogen/operations_client_example_test.go +++ b/longrunning/autogen/operations_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewOperationsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleOperationsClient_ListOperations() { - // import longrunningpb "google.golang.org/genproto/googleapis/longrunning" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := longrunning.NewOperationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &longrunningpb.ListOperationsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleOperationsClient_ListOperations() { } func ExampleOperationsClient_GetOperation() { - // import longrunningpb "google.golang.org/genproto/googleapis/longrunning" - ctx := context.Background() c, err := longrunning.NewOperationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &longrunningpb.GetOperationRequest{ // TODO: Fill request struct fields. @@ -87,6 +86,7 @@ func ExampleOperationsClient_DeleteOperation() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &longrunningpb.DeleteOperationRequest{ // TODO: Fill request struct fields. @@ -103,6 +103,7 @@ func ExampleOperationsClient_CancelOperation() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &longrunningpb.CancelOperationRequest{ // TODO: Fill request struct fields. @@ -114,13 +115,12 @@ func ExampleOperationsClient_CancelOperation() { } func ExampleOperationsClient_WaitOperation() { - // import longrunningpb "google.golang.org/genproto/googleapis/longrunning" - ctx := context.Background() c, err := longrunning.NewOperationsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &longrunningpb.WaitOperationRequest{ // TODO: Fill request struct fields. diff --git a/managedidentities/apiv1/doc.go b/managedidentities/apiv1/doc.go index 6795e088f099..bcf86f05f767 100644 --- a/managedidentities/apiv1/doc.go +++ b/managedidentities/apiv1/doc.go @@ -30,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package managedidentities // import "cloud.google.com/go/managedidentities/apiv1" import ( @@ -50,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/managedidentities/apiv1/managed_identities_client.go b/managedidentities/apiv1/managed_identities_client.go index 154d4780aa95..4fb05c69601d 100644 --- a/managedidentities/apiv1/managed_identities_client.go +++ b/managedidentities/apiv1/managed_identities_client.go @@ -53,7 +53,7 @@ type CallOptions struct { ValidateTrust []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("managedidentities.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("managedidentities.mtls.googleapis.com:443"), @@ -80,32 +80,227 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Managed Service for Microsoft Active Directory API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateMicrosoftAdDomain(context.Context, *managedidentitiespb.CreateMicrosoftAdDomainRequest, ...gax.CallOption) (*CreateMicrosoftAdDomainOperation, error) + CreateMicrosoftAdDomainOperation(name string) *CreateMicrosoftAdDomainOperation + ResetAdminPassword(context.Context, *managedidentitiespb.ResetAdminPasswordRequest, ...gax.CallOption) (*managedidentitiespb.ResetAdminPasswordResponse, error) + ListDomains(context.Context, *managedidentitiespb.ListDomainsRequest, ...gax.CallOption) *DomainIterator + GetDomain(context.Context, *managedidentitiespb.GetDomainRequest, ...gax.CallOption) (*managedidentitiespb.Domain, error) + UpdateDomain(context.Context, *managedidentitiespb.UpdateDomainRequest, ...gax.CallOption) (*UpdateDomainOperation, error) + UpdateDomainOperation(name string) *UpdateDomainOperation + DeleteDomain(context.Context, *managedidentitiespb.DeleteDomainRequest, ...gax.CallOption) (*DeleteDomainOperation, error) + DeleteDomainOperation(name string) *DeleteDomainOperation + AttachTrust(context.Context, *managedidentitiespb.AttachTrustRequest, ...gax.CallOption) (*AttachTrustOperation, error) + AttachTrustOperation(name string) *AttachTrustOperation + ReconfigureTrust(context.Context, *managedidentitiespb.ReconfigureTrustRequest, ...gax.CallOption) (*ReconfigureTrustOperation, error) + ReconfigureTrustOperation(name string) *ReconfigureTrustOperation + DetachTrust(context.Context, *managedidentitiespb.DetachTrustRequest, ...gax.CallOption) (*DetachTrustOperation, error) + DetachTrustOperation(name string) *DetachTrustOperation + ValidateTrust(context.Context, *managedidentitiespb.ValidateTrustRequest, ...gax.CallOption) (*ValidateTrustOperation, error) + ValidateTrustOperation(name string) *ValidateTrustOperation +} + // Client is a client for interacting with Managed Service for Microsoft Active Directory API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// API Overview +// +// The managedidentites.googleapis.com service implements the Google Cloud +// Managed Identites API for identity services +// (e.g. Microsoft Active Directory). +// +// The Managed Identities service provides methods to manage +// (create/read/update/delete) domains, reset managed identities admin password, +// add/remove domain controllers in GCP regions and add/remove VPC peering. +// +// Data Model +// +// The Managed Identities service exposes the following resources: +// +// Locations as global, named as follows: +// projects/{project_id}/locations/global. +// +// Domains, named as follows: +// /projects/{project_id}/locations/global/domain/{domain_name}. +// +// The {domain_name} refers to fully qualified domain name in the customer +// project e.g. mydomain.myorganization.com (at http://mydomain.myorganization.com), with the following restrictions: +// +// Must contain only lowercase letters, numbers, periods and hyphens. +// +// Must start with a letter. +// +// Must contain between 2-64 characters. +// +// Must end with a number or a letter. +// +// Must not start with period. +// +// First segement length (mydomain form example above) shouldn’t exceed +// 15 chars. +// +// The last segment cannot be fully numeric. +// +// Must be unique within the customer project. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateMicrosoftAdDomain creates a Microsoft AD domain. +func (c *Client) CreateMicrosoftAdDomain(ctx context.Context, req *managedidentitiespb.CreateMicrosoftAdDomainRequest, opts ...gax.CallOption) (*CreateMicrosoftAdDomainOperation, error) { + return c.internalClient.CreateMicrosoftAdDomain(ctx, req, opts...) +} + +// CreateMicrosoftAdDomainOperation returns a new CreateMicrosoftAdDomainOperation from a given name. +// The name must be that of a previously created CreateMicrosoftAdDomainOperation, possibly from a different process. +func (c *Client) CreateMicrosoftAdDomainOperation(name string) *CreateMicrosoftAdDomainOperation { + return c.internalClient.CreateMicrosoftAdDomainOperation(name) +} + +// ResetAdminPassword resets a domain’s administrator password. +func (c *Client) ResetAdminPassword(ctx context.Context, req *managedidentitiespb.ResetAdminPasswordRequest, opts ...gax.CallOption) (*managedidentitiespb.ResetAdminPasswordResponse, error) { + return c.internalClient.ResetAdminPassword(ctx, req, opts...) +} + +// ListDomains lists domains in a project. +func (c *Client) ListDomains(ctx context.Context, req *managedidentitiespb.ListDomainsRequest, opts ...gax.CallOption) *DomainIterator { + return c.internalClient.ListDomains(ctx, req, opts...) +} + +// GetDomain gets information about a domain. +func (c *Client) GetDomain(ctx context.Context, req *managedidentitiespb.GetDomainRequest, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { + return c.internalClient.GetDomain(ctx, req, opts...) +} + +// UpdateDomain updates the metadata and configuration of a domain. +func (c *Client) UpdateDomain(ctx context.Context, req *managedidentitiespb.UpdateDomainRequest, opts ...gax.CallOption) (*UpdateDomainOperation, error) { + return c.internalClient.UpdateDomain(ctx, req, opts...) +} + +// UpdateDomainOperation returns a new UpdateDomainOperation from a given name. +// The name must be that of a previously created UpdateDomainOperation, possibly from a different process. +func (c *Client) UpdateDomainOperation(name string) *UpdateDomainOperation { + return c.internalClient.UpdateDomainOperation(name) +} + +// DeleteDomain deletes a domain. +func (c *Client) DeleteDomain(ctx context.Context, req *managedidentitiespb.DeleteDomainRequest, opts ...gax.CallOption) (*DeleteDomainOperation, error) { + return c.internalClient.DeleteDomain(ctx, req, opts...) +} + +// DeleteDomainOperation returns a new DeleteDomainOperation from a given name. +// The name must be that of a previously created DeleteDomainOperation, possibly from a different process. +func (c *Client) DeleteDomainOperation(name string) *DeleteDomainOperation { + return c.internalClient.DeleteDomainOperation(name) +} + +// AttachTrust adds an AD trust to a domain. +func (c *Client) AttachTrust(ctx context.Context, req *managedidentitiespb.AttachTrustRequest, opts ...gax.CallOption) (*AttachTrustOperation, error) { + return c.internalClient.AttachTrust(ctx, req, opts...) +} + +// AttachTrustOperation returns a new AttachTrustOperation from a given name. +// The name must be that of a previously created AttachTrustOperation, possibly from a different process. +func (c *Client) AttachTrustOperation(name string) *AttachTrustOperation { + return c.internalClient.AttachTrustOperation(name) +} + +// ReconfigureTrust updates the DNS conditional forwarder. +func (c *Client) ReconfigureTrust(ctx context.Context, req *managedidentitiespb.ReconfigureTrustRequest, opts ...gax.CallOption) (*ReconfigureTrustOperation, error) { + return c.internalClient.ReconfigureTrust(ctx, req, opts...) +} + +// ReconfigureTrustOperation returns a new ReconfigureTrustOperation from a given name. +// The name must be that of a previously created ReconfigureTrustOperation, possibly from a different process. +func (c *Client) ReconfigureTrustOperation(name string) *ReconfigureTrustOperation { + return c.internalClient.ReconfigureTrustOperation(name) +} + +// DetachTrust removes an AD trust. +func (c *Client) DetachTrust(ctx context.Context, req *managedidentitiespb.DetachTrustRequest, opts ...gax.CallOption) (*DetachTrustOperation, error) { + return c.internalClient.DetachTrust(ctx, req, opts...) +} + +// DetachTrustOperation returns a new DetachTrustOperation from a given name. +// The name must be that of a previously created DetachTrustOperation, possibly from a different process. +func (c *Client) DetachTrustOperation(name string) *DetachTrustOperation { + return c.internalClient.DetachTrustOperation(name) +} + +// ValidateTrust validates a trust state, that the target domain is reachable, and that the +// target domain is able to accept incoming trust requests. +func (c *Client) ValidateTrust(ctx context.Context, req *managedidentitiespb.ValidateTrustRequest, opts ...gax.CallOption) (*ValidateTrustOperation, error) { + return c.internalClient.ValidateTrust(ctx, req, opts...) +} + +// ValidateTrustOperation returns a new ValidateTrustOperation from a given name. +// The name must be that of a previously created ValidateTrustOperation, possibly from a different process. +func (c *Client) ValidateTrustOperation(name string) *ValidateTrustOperation { + return c.internalClient.ValidateTrustOperation(name) +} + +// gRPCClient is a client for interacting with Managed Service for Microsoft Active Directory API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client managedidentitiespb.ManagedIdentitiesServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new managed identities service client. +// NewClient creates a new managed identities service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // API Overview // @@ -147,8 +342,7 @@ type Client struct { // // Must be unique within the customer project. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -166,16 +360,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: managedidentitiespb.NewManagedIdentitiesServiceClient(connPool), + client: managedidentitiespb.NewManagedIdentitiesServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -185,33 +382,33 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateMicrosoftAdDomain creates a Microsoft AD domain. -func (c *Client) CreateMicrosoftAdDomain(ctx context.Context, req *managedidentitiespb.CreateMicrosoftAdDomainRequest, opts ...gax.CallOption) (*CreateMicrosoftAdDomainOperation, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateMicrosoftAdDomain(ctx context.Context, req *managedidentitiespb.CreateMicrosoftAdDomainRequest, opts ...gax.CallOption) (*CreateMicrosoftAdDomainOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -219,7 +416,7 @@ func (c *Client) CreateMicrosoftAdDomain(ctx context.Context, req *managedidenti } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateMicrosoftAdDomain[0:len(c.CallOptions.CreateMicrosoftAdDomain):len(c.CallOptions.CreateMicrosoftAdDomain)], opts...) + opts = append((*c.CallOptions).CreateMicrosoftAdDomain[0:len((*c.CallOptions).CreateMicrosoftAdDomain):len((*c.CallOptions).CreateMicrosoftAdDomain)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -230,12 +427,11 @@ func (c *Client) CreateMicrosoftAdDomain(ctx context.Context, req *managedidenti return nil, err } return &CreateMicrosoftAdDomainOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ResetAdminPassword resets a domain’s administrator password. -func (c *Client) ResetAdminPassword(ctx context.Context, req *managedidentitiespb.ResetAdminPasswordRequest, opts ...gax.CallOption) (*managedidentitiespb.ResetAdminPasswordResponse, error) { +func (c *gRPCClient) ResetAdminPassword(ctx context.Context, req *managedidentitiespb.ResetAdminPasswordRequest, opts ...gax.CallOption) (*managedidentitiespb.ResetAdminPasswordResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -243,7 +439,7 @@ func (c *Client) ResetAdminPassword(ctx context.Context, req *managedidentitiesp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ResetAdminPassword[0:len(c.CallOptions.ResetAdminPassword):len(c.CallOptions.ResetAdminPassword)], opts...) + opts = append((*c.CallOptions).ResetAdminPassword[0:len((*c.CallOptions).ResetAdminPassword):len((*c.CallOptions).ResetAdminPassword)], opts...) var resp *managedidentitiespb.ResetAdminPasswordResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -256,11 +452,10 @@ func (c *Client) ResetAdminPassword(ctx context.Context, req *managedidentitiesp return resp, nil } -// ListDomains lists domains in a project. -func (c *Client) ListDomains(ctx context.Context, req *managedidentitiespb.ListDomainsRequest, opts ...gax.CallOption) *DomainIterator { +func (c *gRPCClient) ListDomains(ctx context.Context, req *managedidentitiespb.ListDomainsRequest, opts ...gax.CallOption) *DomainIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDomains[0:len(c.CallOptions.ListDomains):len(c.CallOptions.ListDomains)], opts...) + opts = append((*c.CallOptions).ListDomains[0:len((*c.CallOptions).ListDomains):len((*c.CallOptions).ListDomains)], opts...) it := &DomainIterator{} req = proto.Clone(req).(*managedidentitiespb.ListDomainsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*managedidentitiespb.Domain, string, error) { @@ -297,8 +492,7 @@ func (c *Client) ListDomains(ctx context.Context, req *managedidentitiespb.ListD return it } -// GetDomain gets information about a domain. -func (c *Client) GetDomain(ctx context.Context, req *managedidentitiespb.GetDomainRequest, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { +func (c *gRPCClient) GetDomain(ctx context.Context, req *managedidentitiespb.GetDomainRequest, opts ...gax.CallOption) (*managedidentitiespb.Domain, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -306,7 +500,7 @@ func (c *Client) GetDomain(ctx context.Context, req *managedidentitiespb.GetDoma } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetDomain[0:len(c.CallOptions.GetDomain):len(c.CallOptions.GetDomain)], opts...) + opts = append((*c.CallOptions).GetDomain[0:len((*c.CallOptions).GetDomain):len((*c.CallOptions).GetDomain)], opts...) var resp *managedidentitiespb.Domain err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -319,8 +513,7 @@ func (c *Client) GetDomain(ctx context.Context, req *managedidentitiespb.GetDoma return resp, nil } -// UpdateDomain updates the metadata and configuration of a domain. -func (c *Client) UpdateDomain(ctx context.Context, req *managedidentitiespb.UpdateDomainRequest, opts ...gax.CallOption) (*UpdateDomainOperation, error) { +func (c *gRPCClient) UpdateDomain(ctx context.Context, req *managedidentitiespb.UpdateDomainRequest, opts ...gax.CallOption) (*UpdateDomainOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -328,7 +521,7 @@ func (c *Client) UpdateDomain(ctx context.Context, req *managedidentitiespb.Upda } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "domain.name", url.QueryEscape(req.GetDomain().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateDomain[0:len(c.CallOptions.UpdateDomain):len(c.CallOptions.UpdateDomain)], opts...) + opts = append((*c.CallOptions).UpdateDomain[0:len((*c.CallOptions).UpdateDomain):len((*c.CallOptions).UpdateDomain)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -339,12 +532,11 @@ func (c *Client) UpdateDomain(ctx context.Context, req *managedidentitiespb.Upda return nil, err } return &UpdateDomainOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteDomain deletes a domain. -func (c *Client) DeleteDomain(ctx context.Context, req *managedidentitiespb.DeleteDomainRequest, opts ...gax.CallOption) (*DeleteDomainOperation, error) { +func (c *gRPCClient) DeleteDomain(ctx context.Context, req *managedidentitiespb.DeleteDomainRequest, opts ...gax.CallOption) (*DeleteDomainOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -352,7 +544,7 @@ func (c *Client) DeleteDomain(ctx context.Context, req *managedidentitiespb.Dele } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteDomain[0:len(c.CallOptions.DeleteDomain):len(c.CallOptions.DeleteDomain)], opts...) + opts = append((*c.CallOptions).DeleteDomain[0:len((*c.CallOptions).DeleteDomain):len((*c.CallOptions).DeleteDomain)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -363,12 +555,11 @@ func (c *Client) DeleteDomain(ctx context.Context, req *managedidentitiespb.Dele return nil, err } return &DeleteDomainOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// AttachTrust adds an AD trust to a domain. -func (c *Client) AttachTrust(ctx context.Context, req *managedidentitiespb.AttachTrustRequest, opts ...gax.CallOption) (*AttachTrustOperation, error) { +func (c *gRPCClient) AttachTrust(ctx context.Context, req *managedidentitiespb.AttachTrustRequest, opts ...gax.CallOption) (*AttachTrustOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -376,7 +567,7 @@ func (c *Client) AttachTrust(ctx context.Context, req *managedidentitiespb.Attac } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AttachTrust[0:len(c.CallOptions.AttachTrust):len(c.CallOptions.AttachTrust)], opts...) + opts = append((*c.CallOptions).AttachTrust[0:len((*c.CallOptions).AttachTrust):len((*c.CallOptions).AttachTrust)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -387,12 +578,11 @@ func (c *Client) AttachTrust(ctx context.Context, req *managedidentitiespb.Attac return nil, err } return &AttachTrustOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ReconfigureTrust updates the DNS conditional forwarder. -func (c *Client) ReconfigureTrust(ctx context.Context, req *managedidentitiespb.ReconfigureTrustRequest, opts ...gax.CallOption) (*ReconfigureTrustOperation, error) { +func (c *gRPCClient) ReconfigureTrust(ctx context.Context, req *managedidentitiespb.ReconfigureTrustRequest, opts ...gax.CallOption) (*ReconfigureTrustOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -400,7 +590,7 @@ func (c *Client) ReconfigureTrust(ctx context.Context, req *managedidentitiespb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ReconfigureTrust[0:len(c.CallOptions.ReconfigureTrust):len(c.CallOptions.ReconfigureTrust)], opts...) + opts = append((*c.CallOptions).ReconfigureTrust[0:len((*c.CallOptions).ReconfigureTrust):len((*c.CallOptions).ReconfigureTrust)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -411,12 +601,11 @@ func (c *Client) ReconfigureTrust(ctx context.Context, req *managedidentitiespb. return nil, err } return &ReconfigureTrustOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DetachTrust removes an AD trust. -func (c *Client) DetachTrust(ctx context.Context, req *managedidentitiespb.DetachTrustRequest, opts ...gax.CallOption) (*DetachTrustOperation, error) { +func (c *gRPCClient) DetachTrust(ctx context.Context, req *managedidentitiespb.DetachTrustRequest, opts ...gax.CallOption) (*DetachTrustOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -424,7 +613,7 @@ func (c *Client) DetachTrust(ctx context.Context, req *managedidentitiespb.Detac } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DetachTrust[0:len(c.CallOptions.DetachTrust):len(c.CallOptions.DetachTrust)], opts...) + opts = append((*c.CallOptions).DetachTrust[0:len((*c.CallOptions).DetachTrust):len((*c.CallOptions).DetachTrust)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -435,13 +624,11 @@ func (c *Client) DetachTrust(ctx context.Context, req *managedidentitiespb.Detac return nil, err } return &DetachTrustOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ValidateTrust validates a trust state, that the target domain is reachable, and that the -// target domain is able to accept incoming trust requests. -func (c *Client) ValidateTrust(ctx context.Context, req *managedidentitiespb.ValidateTrustRequest, opts ...gax.CallOption) (*ValidateTrustOperation, error) { +func (c *gRPCClient) ValidateTrust(ctx context.Context, req *managedidentitiespb.ValidateTrustRequest, opts ...gax.CallOption) (*ValidateTrustOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -449,7 +636,7 @@ func (c *Client) ValidateTrust(ctx context.Context, req *managedidentitiespb.Val } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ValidateTrust[0:len(c.CallOptions.ValidateTrust):len(c.CallOptions.ValidateTrust)], opts...) + opts = append((*c.CallOptions).ValidateTrust[0:len((*c.CallOptions).ValidateTrust):len((*c.CallOptions).ValidateTrust)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -460,7 +647,7 @@ func (c *Client) ValidateTrust(ctx context.Context, req *managedidentitiespb.Val return nil, err } return &ValidateTrustOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -471,9 +658,9 @@ type AttachTrustOperation struct { // AttachTrustOperation returns a new AttachTrustOperation from a given name. // The name must be that of a previously created AttachTrustOperation, possibly from a different process. -func (c *Client) AttachTrustOperation(name string) *AttachTrustOperation { +func (c *gRPCClient) AttachTrustOperation(name string) *AttachTrustOperation { return &AttachTrustOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -540,9 +727,9 @@ type CreateMicrosoftAdDomainOperation struct { // CreateMicrosoftAdDomainOperation returns a new CreateMicrosoftAdDomainOperation from a given name. // The name must be that of a previously created CreateMicrosoftAdDomainOperation, possibly from a different process. -func (c *Client) CreateMicrosoftAdDomainOperation(name string) *CreateMicrosoftAdDomainOperation { +func (c *gRPCClient) CreateMicrosoftAdDomainOperation(name string) *CreateMicrosoftAdDomainOperation { return &CreateMicrosoftAdDomainOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -609,9 +796,9 @@ type DeleteDomainOperation struct { // DeleteDomainOperation returns a new DeleteDomainOperation from a given name. // The name must be that of a previously created DeleteDomainOperation, possibly from a different process. -func (c *Client) DeleteDomainOperation(name string) *DeleteDomainOperation { +func (c *gRPCClient) DeleteDomainOperation(name string) *DeleteDomainOperation { return &DeleteDomainOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -667,9 +854,9 @@ type DetachTrustOperation struct { // DetachTrustOperation returns a new DetachTrustOperation from a given name. // The name must be that of a previously created DetachTrustOperation, possibly from a different process. -func (c *Client) DetachTrustOperation(name string) *DetachTrustOperation { +func (c *gRPCClient) DetachTrustOperation(name string) *DetachTrustOperation { return &DetachTrustOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -736,9 +923,9 @@ type ReconfigureTrustOperation struct { // ReconfigureTrustOperation returns a new ReconfigureTrustOperation from a given name. // The name must be that of a previously created ReconfigureTrustOperation, possibly from a different process. -func (c *Client) ReconfigureTrustOperation(name string) *ReconfigureTrustOperation { +func (c *gRPCClient) ReconfigureTrustOperation(name string) *ReconfigureTrustOperation { return &ReconfigureTrustOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -805,9 +992,9 @@ type UpdateDomainOperation struct { // UpdateDomainOperation returns a new UpdateDomainOperation from a given name. // The name must be that of a previously created UpdateDomainOperation, possibly from a different process. -func (c *Client) UpdateDomainOperation(name string) *UpdateDomainOperation { +func (c *gRPCClient) UpdateDomainOperation(name string) *UpdateDomainOperation { return &UpdateDomainOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -874,9 +1061,9 @@ type ValidateTrustOperation struct { // ValidateTrustOperation returns a new ValidateTrustOperation from a given name. // The name must be that of a previously created ValidateTrustOperation, possibly from a different process. -func (c *Client) ValidateTrustOperation(name string) *ValidateTrustOperation { +func (c *gRPCClient) ValidateTrustOperation(name string) *ValidateTrustOperation { return &ValidateTrustOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/managedidentities/apiv1/managed_identities_client_example_test.go b/managedidentities/apiv1/managed_identities_client_example_test.go index e86c2fc8eb23..caad6b0341c2 100644 --- a/managedidentities/apiv1/managed_identities_client_example_test.go +++ b/managedidentities/apiv1/managed_identities_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateMicrosoftAdDomain() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.CreateMicrosoftAdDomainRequest{ // TODO: Fill request struct fields. @@ -60,13 +61,12 @@ func ExampleClient_CreateMicrosoftAdDomain() { } func ExampleClient_ResetAdminPassword() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.ResetAdminPasswordRequest{ // TODO: Fill request struct fields. @@ -80,14 +80,12 @@ func ExampleClient_ResetAdminPassword() { } func ExampleClient_ListDomains() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.ListDomainsRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleClient_ListDomains() { } func ExampleClient_GetDomain() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.GetDomainRequest{ // TODO: Fill request struct fields. @@ -127,13 +124,12 @@ func ExampleClient_GetDomain() { } func ExampleClient_UpdateDomain() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.UpdateDomainRequest{ // TODO: Fill request struct fields. @@ -152,13 +148,12 @@ func ExampleClient_UpdateDomain() { } func ExampleClient_DeleteDomain() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.DeleteDomainRequest{ // TODO: Fill request struct fields. @@ -175,13 +170,12 @@ func ExampleClient_DeleteDomain() { } func ExampleClient_AttachTrust() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.AttachTrustRequest{ // TODO: Fill request struct fields. @@ -200,13 +194,12 @@ func ExampleClient_AttachTrust() { } func ExampleClient_ReconfigureTrust() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.ReconfigureTrustRequest{ // TODO: Fill request struct fields. @@ -225,13 +218,12 @@ func ExampleClient_ReconfigureTrust() { } func ExampleClient_DetachTrust() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.DetachTrustRequest{ // TODO: Fill request struct fields. @@ -250,13 +242,12 @@ func ExampleClient_DetachTrust() { } func ExampleClient_ValidateTrust() { - // import managedidentitiespb "google.golang.org/genproto/googleapis/cloud/managedidentities/v1" - ctx := context.Background() c, err := managedidentities.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &managedidentitiespb.ValidateTrustRequest{ // TODO: Fill request struct fields. diff --git a/mediatranslation/apiv1beta1/doc.go b/mediatranslation/apiv1beta1/doc.go index 5167861ed8bf..188186d134e6 100644 --- a/mediatranslation/apiv1beta1/doc.go +++ b/mediatranslation/apiv1beta1/doc.go @@ -17,6 +17,8 @@ // Package mediatranslation is an auto-generated package for the // Media Translation API. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -26,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package mediatranslation // import "cloud.google.com/go/mediatranslation/apiv1beta1" import ( @@ -46,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/mediatranslation/apiv1beta1/speech_translation_client.go b/mediatranslation/apiv1beta1/speech_translation_client.go index 3dae2b114985..e6d2dc48e53c 100644 --- a/mediatranslation/apiv1beta1/speech_translation_client.go +++ b/mediatranslation/apiv1beta1/speech_translation_client.go @@ -36,7 +36,7 @@ type SpeechTranslationCallOptions struct { StreamingTranslateSpeech []gax.CallOption } -func defaultSpeechTranslationClientOptions() []option.ClientOption { +func defaultSpeechTranslationGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("mediatranslation.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("mediatranslation.mtls.googleapis.com:443"), @@ -54,32 +54,80 @@ func defaultSpeechTranslationCallOptions() *SpeechTranslationCallOptions { } } +// internalSpeechTranslationClient is an interface that defines the methods availaible from Media Translation API. +type internalSpeechTranslationClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + StreamingTranslateSpeech(context.Context, ...gax.CallOption) (mediatranslationpb.SpeechTranslationService_StreamingTranslateSpeechClient, error) +} + // SpeechTranslationClient is a client for interacting with Media Translation API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Provides translation from/to media types. type SpeechTranslationClient struct { + // The internal transport-dependent client. + internalClient internalSpeechTranslationClient + + // The call options for this service. + CallOptions *SpeechTranslationCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *SpeechTranslationClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *SpeechTranslationClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *SpeechTranslationClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// StreamingTranslateSpeech performs bidirectional streaming speech translation: receive results while +// sending audio. This method is only available via the gRPC API (not REST). +func (c *SpeechTranslationClient) StreamingTranslateSpeech(ctx context.Context, opts ...gax.CallOption) (mediatranslationpb.SpeechTranslationService_StreamingTranslateSpeechClient, error) { + return c.internalClient.StreamingTranslateSpeech(ctx, opts...) +} + +// speechTranslationGRPCClient is a client for interacting with Media Translation API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type speechTranslationGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing SpeechTranslationClient + CallOptions **SpeechTranslationCallOptions + // The gRPC API client. speechTranslationClient mediatranslationpb.SpeechTranslationServiceClient - // The call options for this service. - CallOptions *SpeechTranslationCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewSpeechTranslationClient creates a new speech translation service client. +// NewSpeechTranslationClient creates a new speech translation service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Provides translation from/to media types. func NewSpeechTranslationClient(ctx context.Context, opts ...option.ClientOption) (*SpeechTranslationClient, error) { - clientOpts := defaultSpeechTranslationClientOptions() - + clientOpts := defaultSpeechTranslationGRPCClientOptions() if newSpeechTranslationClientHook != nil { hookOpts, err := newSpeechTranslationClientHook(ctx, clientHookParams{}) if err != nil { @@ -97,46 +145,47 @@ func NewSpeechTranslationClient(ctx context.Context, opts ...option.ClientOption if err != nil { return nil, err } - c := &SpeechTranslationClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultSpeechTranslationCallOptions(), + client := SpeechTranslationClient{CallOptions: defaultSpeechTranslationCallOptions()} + c := &speechTranslationGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, speechTranslationClient: mediatranslationpb.NewSpeechTranslationServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *SpeechTranslationClient) Connection() *grpc.ClientConn { +func (c *speechTranslationGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *SpeechTranslationClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *SpeechTranslationClient) setGoogleClientInfo(keyval ...string) { +func (c *speechTranslationGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// StreamingTranslateSpeech performs bidirectional streaming speech translation: receive results while -// sending audio. This method is only available via the gRPC API (not REST). -func (c *SpeechTranslationClient) StreamingTranslateSpeech(ctx context.Context, opts ...gax.CallOption) (mediatranslationpb.SpeechTranslationService_StreamingTranslateSpeechClient, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *speechTranslationGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *speechTranslationGRPCClient) StreamingTranslateSpeech(ctx context.Context, opts ...gax.CallOption) (mediatranslationpb.SpeechTranslationService_StreamingTranslateSpeechClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.StreamingTranslateSpeech[0:len(c.CallOptions.StreamingTranslateSpeech):len(c.CallOptions.StreamingTranslateSpeech)], opts...) var resp mediatranslationpb.SpeechTranslationService_StreamingTranslateSpeechClient + opts = append((*c.CallOptions).StreamingTranslateSpeech[0:len((*c.CallOptions).StreamingTranslateSpeech):len((*c.CallOptions).StreamingTranslateSpeech)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.speechTranslationClient.StreamingTranslateSpeech(ctx, settings.GRPC...) diff --git a/mediatranslation/apiv1beta1/speech_translation_client_example_test.go b/mediatranslation/apiv1beta1/speech_translation_client_example_test.go index a463fc395e70..57cc92c95eb2 100644 --- a/mediatranslation/apiv1beta1/speech_translation_client_example_test.go +++ b/mediatranslation/apiv1beta1/speech_translation_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewSpeechTranslationClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleSpeechTranslationClient_StreamingTranslateSpeech() { - // import mediatranslationpb "google.golang.org/genproto/googleapis/cloud/mediatranslation/v1beta1" - ctx := context.Background() c, err := mediatranslation.NewSpeechTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.StreamingTranslateSpeech(ctx) if err != nil { // TODO: Handle error. diff --git a/memcache/apiv1/cloud_memcache_client.go b/memcache/apiv1/cloud_memcache_client.go index 9a375f89dbb0..4c89cb1ee715 100644 --- a/memcache/apiv1/cloud_memcache_client.go +++ b/memcache/apiv1/cloud_memcache_client.go @@ -50,7 +50,7 @@ type CloudMemcacheCallOptions struct { ApplyParameters []gax.CallOption } -func defaultCloudMemcacheClientOptions() []option.ClientOption { +func defaultCloudMemcacheGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("memcache.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("memcache.mtls.googleapis.com:443"), @@ -74,32 +74,177 @@ func defaultCloudMemcacheCallOptions() *CloudMemcacheCallOptions { } } +// internalCloudMemcacheClient is an interface that defines the methods availaible from Cloud Memorystore for Memcached API. +type internalCloudMemcacheClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListInstances(context.Context, *memcachepb.ListInstancesRequest, ...gax.CallOption) *InstanceIterator + GetInstance(context.Context, *memcachepb.GetInstanceRequest, ...gax.CallOption) (*memcachepb.Instance, error) + CreateInstance(context.Context, *memcachepb.CreateInstanceRequest, ...gax.CallOption) (*CreateInstanceOperation, error) + CreateInstanceOperation(name string) *CreateInstanceOperation + UpdateInstance(context.Context, *memcachepb.UpdateInstanceRequest, ...gax.CallOption) (*UpdateInstanceOperation, error) + UpdateInstanceOperation(name string) *UpdateInstanceOperation + UpdateParameters(context.Context, *memcachepb.UpdateParametersRequest, ...gax.CallOption) (*UpdateParametersOperation, error) + UpdateParametersOperation(name string) *UpdateParametersOperation + DeleteInstance(context.Context, *memcachepb.DeleteInstanceRequest, ...gax.CallOption) (*DeleteInstanceOperation, error) + DeleteInstanceOperation(name string) *DeleteInstanceOperation + ApplyParameters(context.Context, *memcachepb.ApplyParametersRequest, ...gax.CallOption) (*ApplyParametersOperation, error) + ApplyParametersOperation(name string) *ApplyParametersOperation +} + // CloudMemcacheClient is a client for interacting with Cloud Memorystore for Memcached API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Configures and manages Cloud Memorystore for Memcached instances. +// +// The memcache.googleapis.com service implements the Google Cloud Memorystore +// for Memcached API and defines the following resource model for managing +// Memorystore Memcached (also called Memcached below) instances: +// +// The service works with a collection of cloud projects, named: /projects/* +// +// Each project has a collection of available locations, named: /locations/* +// +// Each location has a collection of Memcached instances, named: +// /instances/* +// +// As such, Memcached instances are resources of the form: +// /projects/{project_id}/locations/{location_id}/instances/{instance_id} +// +// Note that location_id must be a GCP region; for example: +// +// projects/my-memcached-project/locations/us-central1/instances/my-memcached type CloudMemcacheClient struct { + // The internal transport-dependent client. + internalClient internalCloudMemcacheClient + + // The call options for this service. + CallOptions *CloudMemcacheCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CloudMemcacheClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CloudMemcacheClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CloudMemcacheClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListInstances lists Instances in a given location. +func (c *CloudMemcacheClient) ListInstances(ctx context.Context, req *memcachepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { + return c.internalClient.ListInstances(ctx, req, opts...) +} + +// GetInstance gets details of a single Instance. +func (c *CloudMemcacheClient) GetInstance(ctx context.Context, req *memcachepb.GetInstanceRequest, opts ...gax.CallOption) (*memcachepb.Instance, error) { + return c.internalClient.GetInstance(ctx, req, opts...) +} + +// CreateInstance creates a new Instance in a given location. +func (c *CloudMemcacheClient) CreateInstance(ctx context.Context, req *memcachepb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { + return c.internalClient.CreateInstance(ctx, req, opts...) +} + +// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. +// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. +func (c *CloudMemcacheClient) CreateInstanceOperation(name string) *CreateInstanceOperation { + return c.internalClient.CreateInstanceOperation(name) +} + +// UpdateInstance updates an existing Instance in a given project and location. +func (c *CloudMemcacheClient) UpdateInstance(ctx context.Context, req *memcachepb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { + return c.internalClient.UpdateInstance(ctx, req, opts...) +} + +// UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. +// The name must be that of a previously created UpdateInstanceOperation, possibly from a different process. +func (c *CloudMemcacheClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { + return c.internalClient.UpdateInstanceOperation(name) +} + +// UpdateParameters updates the defined Memcached Parameters for an existing Instance. +// This method only stages the parameters, it must be followed by +// ApplyParameters to apply the parameters to nodes of the Memcached Instance. +func (c *CloudMemcacheClient) UpdateParameters(ctx context.Context, req *memcachepb.UpdateParametersRequest, opts ...gax.CallOption) (*UpdateParametersOperation, error) { + return c.internalClient.UpdateParameters(ctx, req, opts...) +} + +// UpdateParametersOperation returns a new UpdateParametersOperation from a given name. +// The name must be that of a previously created UpdateParametersOperation, possibly from a different process. +func (c *CloudMemcacheClient) UpdateParametersOperation(name string) *UpdateParametersOperation { + return c.internalClient.UpdateParametersOperation(name) +} + +// DeleteInstance deletes a single Instance. +func (c *CloudMemcacheClient) DeleteInstance(ctx context.Context, req *memcachepb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { + return c.internalClient.DeleteInstance(ctx, req, opts...) +} + +// DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. +// The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. +func (c *CloudMemcacheClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { + return c.internalClient.DeleteInstanceOperation(name) +} + +// ApplyParameters applyParameters will restart the set of specified nodes in order to update +// them to the current set of parameters for the Memcached Instance. +func (c *CloudMemcacheClient) ApplyParameters(ctx context.Context, req *memcachepb.ApplyParametersRequest, opts ...gax.CallOption) (*ApplyParametersOperation, error) { + return c.internalClient.ApplyParameters(ctx, req, opts...) +} + +// ApplyParametersOperation returns a new ApplyParametersOperation from a given name. +// The name must be that of a previously created ApplyParametersOperation, possibly from a different process. +func (c *CloudMemcacheClient) ApplyParametersOperation(name string) *ApplyParametersOperation { + return c.internalClient.ApplyParametersOperation(name) +} + +// cloudMemcacheGRPCClient is a client for interacting with Cloud Memorystore for Memcached API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudMemcacheGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CloudMemcacheClient + CallOptions **CloudMemcacheCallOptions + // The gRPC API client. cloudMemcacheClient memcachepb.CloudMemcacheClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CloudMemcacheCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCloudMemcacheClient creates a new cloud memcache client. +// NewCloudMemcacheClient creates a new cloud memcache client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Configures and manages Cloud Memorystore for Memcached instances. // @@ -121,8 +266,7 @@ type CloudMemcacheClient struct { // // projects/my-memcached-project/locations/us-central1/instances/my-memcached func NewCloudMemcacheClient(ctx context.Context, opts ...option.ClientOption) (*CloudMemcacheClient, error) { - clientOpts := defaultCloudMemcacheClientOptions() - + clientOpts := defaultCloudMemcacheGRPCClientOptions() if newCloudMemcacheClientHook != nil { hookOpts, err := newCloudMemcacheClientHook(ctx, clientHookParams{}) if err != nil { @@ -140,16 +284,19 @@ func NewCloudMemcacheClient(ctx context.Context, opts ...option.ClientOption) (* if err != nil { return nil, err } - c := &CloudMemcacheClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultCloudMemcacheCallOptions(), + client := CloudMemcacheClient{CallOptions: defaultCloudMemcacheCallOptions()} + c := &cloudMemcacheGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, cloudMemcacheClient: memcachepb.NewCloudMemcacheClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -159,36 +306,36 @@ func NewCloudMemcacheClient(ctx context.Context, opts ...option.ClientOption) (* // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CloudMemcacheClient) Connection() *grpc.ClientConn { +func (c *cloudMemcacheGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CloudMemcacheClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CloudMemcacheClient) setGoogleClientInfo(keyval ...string) { +func (c *cloudMemcacheGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListInstances lists Instances in a given location. -func (c *CloudMemcacheClient) ListInstances(ctx context.Context, req *memcachepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudMemcacheGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *cloudMemcacheGRPCClient) ListInstances(ctx context.Context, req *memcachepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListInstances[0:len(c.CallOptions.ListInstances):len(c.CallOptions.ListInstances)], opts...) + opts = append((*c.CallOptions).ListInstances[0:len((*c.CallOptions).ListInstances):len((*c.CallOptions).ListInstances)], opts...) it := &InstanceIterator{} req = proto.Clone(req).(*memcachepb.ListInstancesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*memcachepb.Instance, string, error) { @@ -225,8 +372,7 @@ func (c *CloudMemcacheClient) ListInstances(ctx context.Context, req *memcachepb return it } -// GetInstance gets details of a single Instance. -func (c *CloudMemcacheClient) GetInstance(ctx context.Context, req *memcachepb.GetInstanceRequest, opts ...gax.CallOption) (*memcachepb.Instance, error) { +func (c *cloudMemcacheGRPCClient) GetInstance(ctx context.Context, req *memcachepb.GetInstanceRequest, opts ...gax.CallOption) (*memcachepb.Instance, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 1200000*time.Millisecond) defer cancel() @@ -234,7 +380,7 @@ func (c *CloudMemcacheClient) GetInstance(ctx context.Context, req *memcachepb.G } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetInstance[0:len(c.CallOptions.GetInstance):len(c.CallOptions.GetInstance)], opts...) + opts = append((*c.CallOptions).GetInstance[0:len((*c.CallOptions).GetInstance):len((*c.CallOptions).GetInstance)], opts...) var resp *memcachepb.Instance err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -247,8 +393,7 @@ func (c *CloudMemcacheClient) GetInstance(ctx context.Context, req *memcachepb.G return resp, nil } -// CreateInstance creates a new Instance in a given location. -func (c *CloudMemcacheClient) CreateInstance(ctx context.Context, req *memcachepb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { +func (c *cloudMemcacheGRPCClient) CreateInstance(ctx context.Context, req *memcachepb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 1200000*time.Millisecond) defer cancel() @@ -256,7 +401,7 @@ func (c *CloudMemcacheClient) CreateInstance(ctx context.Context, req *memcachep } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateInstance[0:len(c.CallOptions.CreateInstance):len(c.CallOptions.CreateInstance)], opts...) + opts = append((*c.CallOptions).CreateInstance[0:len((*c.CallOptions).CreateInstance):len((*c.CallOptions).CreateInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -267,12 +412,11 @@ func (c *CloudMemcacheClient) CreateInstance(ctx context.Context, req *memcachep return nil, err } return &CreateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateInstance updates an existing Instance in a given project and location. -func (c *CloudMemcacheClient) UpdateInstance(ctx context.Context, req *memcachepb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { +func (c *cloudMemcacheGRPCClient) UpdateInstance(ctx context.Context, req *memcachepb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 1200000*time.Millisecond) defer cancel() @@ -280,7 +424,7 @@ func (c *CloudMemcacheClient) UpdateInstance(ctx context.Context, req *memcachep } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance.name", url.QueryEscape(req.GetInstance().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateInstance[0:len(c.CallOptions.UpdateInstance):len(c.CallOptions.UpdateInstance)], opts...) + opts = append((*c.CallOptions).UpdateInstance[0:len((*c.CallOptions).UpdateInstance):len((*c.CallOptions).UpdateInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -291,14 +435,11 @@ func (c *CloudMemcacheClient) UpdateInstance(ctx context.Context, req *memcachep return nil, err } return &UpdateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateParameters updates the defined Memcached Parameters for an existing Instance. -// This method only stages the parameters, it must be followed by -// ApplyParameters to apply the parameters to nodes of the Memcached Instance. -func (c *CloudMemcacheClient) UpdateParameters(ctx context.Context, req *memcachepb.UpdateParametersRequest, opts ...gax.CallOption) (*UpdateParametersOperation, error) { +func (c *cloudMemcacheGRPCClient) UpdateParameters(ctx context.Context, req *memcachepb.UpdateParametersRequest, opts ...gax.CallOption) (*UpdateParametersOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 1200000*time.Millisecond) defer cancel() @@ -306,7 +447,7 @@ func (c *CloudMemcacheClient) UpdateParameters(ctx context.Context, req *memcach } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateParameters[0:len(c.CallOptions.UpdateParameters):len(c.CallOptions.UpdateParameters)], opts...) + opts = append((*c.CallOptions).UpdateParameters[0:len((*c.CallOptions).UpdateParameters):len((*c.CallOptions).UpdateParameters)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -317,12 +458,11 @@ func (c *CloudMemcacheClient) UpdateParameters(ctx context.Context, req *memcach return nil, err } return &UpdateParametersOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteInstance deletes a single Instance. -func (c *CloudMemcacheClient) DeleteInstance(ctx context.Context, req *memcachepb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { +func (c *cloudMemcacheGRPCClient) DeleteInstance(ctx context.Context, req *memcachepb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 1200000*time.Millisecond) defer cancel() @@ -330,7 +470,7 @@ func (c *CloudMemcacheClient) DeleteInstance(ctx context.Context, req *memcachep } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteInstance[0:len(c.CallOptions.DeleteInstance):len(c.CallOptions.DeleteInstance)], opts...) + opts = append((*c.CallOptions).DeleteInstance[0:len((*c.CallOptions).DeleteInstance):len((*c.CallOptions).DeleteInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -341,13 +481,11 @@ func (c *CloudMemcacheClient) DeleteInstance(ctx context.Context, req *memcachep return nil, err } return &DeleteInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ApplyParameters applyParameters will restart the set of specified nodes in order to update -// them to the current set of parameters for the Memcached Instance. -func (c *CloudMemcacheClient) ApplyParameters(ctx context.Context, req *memcachepb.ApplyParametersRequest, opts ...gax.CallOption) (*ApplyParametersOperation, error) { +func (c *cloudMemcacheGRPCClient) ApplyParameters(ctx context.Context, req *memcachepb.ApplyParametersRequest, opts ...gax.CallOption) (*ApplyParametersOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 1200000*time.Millisecond) defer cancel() @@ -355,7 +493,7 @@ func (c *CloudMemcacheClient) ApplyParameters(ctx context.Context, req *memcache } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ApplyParameters[0:len(c.CallOptions.ApplyParameters):len(c.CallOptions.ApplyParameters)], opts...) + opts = append((*c.CallOptions).ApplyParameters[0:len((*c.CallOptions).ApplyParameters):len((*c.CallOptions).ApplyParameters)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -366,7 +504,7 @@ func (c *CloudMemcacheClient) ApplyParameters(ctx context.Context, req *memcache return nil, err } return &ApplyParametersOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -377,9 +515,9 @@ type ApplyParametersOperation struct { // ApplyParametersOperation returns a new ApplyParametersOperation from a given name. // The name must be that of a previously created ApplyParametersOperation, possibly from a different process. -func (c *CloudMemcacheClient) ApplyParametersOperation(name string) *ApplyParametersOperation { +func (c *cloudMemcacheGRPCClient) ApplyParametersOperation(name string) *ApplyParametersOperation { return &ApplyParametersOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -446,9 +584,9 @@ type CreateInstanceOperation struct { // CreateInstanceOperation returns a new CreateInstanceOperation from a given name. // The name must be that of a previously created CreateInstanceOperation, possibly from a different process. -func (c *CloudMemcacheClient) CreateInstanceOperation(name string) *CreateInstanceOperation { +func (c *cloudMemcacheGRPCClient) CreateInstanceOperation(name string) *CreateInstanceOperation { return &CreateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -515,9 +653,9 @@ type DeleteInstanceOperation struct { // DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. // The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. -func (c *CloudMemcacheClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { +func (c *cloudMemcacheGRPCClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { return &DeleteInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -573,9 +711,9 @@ type UpdateInstanceOperation struct { // UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. // The name must be that of a previously created UpdateInstanceOperation, possibly from a different process. -func (c *CloudMemcacheClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { +func (c *cloudMemcacheGRPCClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { return &UpdateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -642,9 +780,9 @@ type UpdateParametersOperation struct { // UpdateParametersOperation returns a new UpdateParametersOperation from a given name. // The name must be that of a previously created UpdateParametersOperation, possibly from a different process. -func (c *CloudMemcacheClient) UpdateParametersOperation(name string) *UpdateParametersOperation { +func (c *cloudMemcacheGRPCClient) UpdateParametersOperation(name string) *UpdateParametersOperation { return &UpdateParametersOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/memcache/apiv1/cloud_memcache_client_example_test.go b/memcache/apiv1/cloud_memcache_client_example_test.go index 5955d8bca149..80383fc1a7af 100644 --- a/memcache/apiv1/cloud_memcache_client_example_test.go +++ b/memcache/apiv1/cloud_memcache_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewCloudMemcacheClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCloudMemcacheClient_ListInstances() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.ListInstancesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleCloudMemcacheClient_ListInstances() { } func ExampleCloudMemcacheClient_GetInstance() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.GetInstanceRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleCloudMemcacheClient_GetInstance() { } func ExampleCloudMemcacheClient_CreateInstance() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.CreateInstanceRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleCloudMemcacheClient_CreateInstance() { } func ExampleCloudMemcacheClient_UpdateInstance() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.UpdateInstanceRequest{ // TODO: Fill request struct fields. @@ -132,13 +129,12 @@ func ExampleCloudMemcacheClient_UpdateInstance() { } func ExampleCloudMemcacheClient_UpdateParameters() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.UpdateParametersRequest{ // TODO: Fill request struct fields. @@ -157,13 +153,12 @@ func ExampleCloudMemcacheClient_UpdateParameters() { } func ExampleCloudMemcacheClient_DeleteInstance() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.DeleteInstanceRequest{ // TODO: Fill request struct fields. @@ -180,13 +175,12 @@ func ExampleCloudMemcacheClient_DeleteInstance() { } func ExampleCloudMemcacheClient_ApplyParameters() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.ApplyParametersRequest{ // TODO: Fill request struct fields. diff --git a/memcache/apiv1/doc.go b/memcache/apiv1/doc.go index 96d5a1c8d28b..4e2b025e07ce 100644 --- a/memcache/apiv1/doc.go +++ b/memcache/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package memcache // import "cloud.google.com/go/memcache/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/memcache/apiv1beta2/cloud_memcache_client.go b/memcache/apiv1beta2/cloud_memcache_client.go index fe6cab4655da..65917acc5358 100644 --- a/memcache/apiv1beta2/cloud_memcache_client.go +++ b/memcache/apiv1beta2/cloud_memcache_client.go @@ -51,7 +51,7 @@ type CloudMemcacheCallOptions struct { ApplySoftwareUpdate []gax.CallOption } -func defaultCloudMemcacheClientOptions() []option.ClientOption { +func defaultCloudMemcacheGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("memcache.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("memcache.mtls.googleapis.com:443"), @@ -76,32 +76,191 @@ func defaultCloudMemcacheCallOptions() *CloudMemcacheCallOptions { } } +// internalCloudMemcacheClient is an interface that defines the methods availaible from Cloud Memorystore for Memcached API. +type internalCloudMemcacheClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListInstances(context.Context, *memcachepb.ListInstancesRequest, ...gax.CallOption) *InstanceIterator + GetInstance(context.Context, *memcachepb.GetInstanceRequest, ...gax.CallOption) (*memcachepb.Instance, error) + CreateInstance(context.Context, *memcachepb.CreateInstanceRequest, ...gax.CallOption) (*CreateInstanceOperation, error) + CreateInstanceOperation(name string) *CreateInstanceOperation + UpdateInstance(context.Context, *memcachepb.UpdateInstanceRequest, ...gax.CallOption) (*UpdateInstanceOperation, error) + UpdateInstanceOperation(name string) *UpdateInstanceOperation + UpdateParameters(context.Context, *memcachepb.UpdateParametersRequest, ...gax.CallOption) (*UpdateParametersOperation, error) + UpdateParametersOperation(name string) *UpdateParametersOperation + DeleteInstance(context.Context, *memcachepb.DeleteInstanceRequest, ...gax.CallOption) (*DeleteInstanceOperation, error) + DeleteInstanceOperation(name string) *DeleteInstanceOperation + ApplyParameters(context.Context, *memcachepb.ApplyParametersRequest, ...gax.CallOption) (*ApplyParametersOperation, error) + ApplyParametersOperation(name string) *ApplyParametersOperation + ApplySoftwareUpdate(context.Context, *memcachepb.ApplySoftwareUpdateRequest, ...gax.CallOption) (*ApplySoftwareUpdateOperation, error) + ApplySoftwareUpdateOperation(name string) *ApplySoftwareUpdateOperation +} + // CloudMemcacheClient is a client for interacting with Cloud Memorystore for Memcached API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Configures and manages Cloud Memorystore for Memcached instances. +// +// The memcache.googleapis.com service implements the Google Cloud Memorystore +// for Memcached API and defines the following resource model for managing +// Memorystore Memcached (also called Memcached below) instances: +// +// The service works with a collection of cloud projects, named: /projects/* +// +// Each project has a collection of available locations, named: /locations/* +// +// Each location has a collection of Memcached instances, named: +// /instances/* +// +// As such, Memcached instances are resources of the form: +// /projects/{project_id}/locations/{location_id}/instances/{instance_id} +// +// Note that location_id must be a GCP region; for example: +// +// projects/my-memcached-project/locations/us-central1/instances/my-memcached type CloudMemcacheClient struct { + // The internal transport-dependent client. + internalClient internalCloudMemcacheClient + + // The call options for this service. + CallOptions *CloudMemcacheCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CloudMemcacheClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CloudMemcacheClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CloudMemcacheClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListInstances lists Instances in a given location. +func (c *CloudMemcacheClient) ListInstances(ctx context.Context, req *memcachepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { + return c.internalClient.ListInstances(ctx, req, opts...) +} + +// GetInstance gets details of a single Instance. +func (c *CloudMemcacheClient) GetInstance(ctx context.Context, req *memcachepb.GetInstanceRequest, opts ...gax.CallOption) (*memcachepb.Instance, error) { + return c.internalClient.GetInstance(ctx, req, opts...) +} + +// CreateInstance creates a new Instance in a given location. +func (c *CloudMemcacheClient) CreateInstance(ctx context.Context, req *memcachepb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { + return c.internalClient.CreateInstance(ctx, req, opts...) +} + +// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. +// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. +func (c *CloudMemcacheClient) CreateInstanceOperation(name string) *CreateInstanceOperation { + return c.internalClient.CreateInstanceOperation(name) +} + +// UpdateInstance updates an existing Instance in a given project and location. +func (c *CloudMemcacheClient) UpdateInstance(ctx context.Context, req *memcachepb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { + return c.internalClient.UpdateInstance(ctx, req, opts...) +} + +// UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. +// The name must be that of a previously created UpdateInstanceOperation, possibly from a different process. +func (c *CloudMemcacheClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { + return c.internalClient.UpdateInstanceOperation(name) +} + +// UpdateParameters updates the defined Memcached parameters for an existing instance. +// This method only stages the parameters, it must be followed by +// ApplyParameters to apply the parameters to nodes of the Memcached +// instance. +func (c *CloudMemcacheClient) UpdateParameters(ctx context.Context, req *memcachepb.UpdateParametersRequest, opts ...gax.CallOption) (*UpdateParametersOperation, error) { + return c.internalClient.UpdateParameters(ctx, req, opts...) +} + +// UpdateParametersOperation returns a new UpdateParametersOperation from a given name. +// The name must be that of a previously created UpdateParametersOperation, possibly from a different process. +func (c *CloudMemcacheClient) UpdateParametersOperation(name string) *UpdateParametersOperation { + return c.internalClient.UpdateParametersOperation(name) +} + +// DeleteInstance deletes a single Instance. +func (c *CloudMemcacheClient) DeleteInstance(ctx context.Context, req *memcachepb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { + return c.internalClient.DeleteInstance(ctx, req, opts...) +} + +// DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. +// The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. +func (c *CloudMemcacheClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { + return c.internalClient.DeleteInstanceOperation(name) +} + +// ApplyParameters ApplyParameters restarts the set of specified nodes in order to update +// them to the current set of parameters for the Memcached Instance. +func (c *CloudMemcacheClient) ApplyParameters(ctx context.Context, req *memcachepb.ApplyParametersRequest, opts ...gax.CallOption) (*ApplyParametersOperation, error) { + return c.internalClient.ApplyParameters(ctx, req, opts...) +} + +// ApplyParametersOperation returns a new ApplyParametersOperation from a given name. +// The name must be that of a previously created ApplyParametersOperation, possibly from a different process. +func (c *CloudMemcacheClient) ApplyParametersOperation(name string) *ApplyParametersOperation { + return c.internalClient.ApplyParametersOperation(name) +} + +// ApplySoftwareUpdate updates software on the selected nodes of the Instance. +func (c *CloudMemcacheClient) ApplySoftwareUpdate(ctx context.Context, req *memcachepb.ApplySoftwareUpdateRequest, opts ...gax.CallOption) (*ApplySoftwareUpdateOperation, error) { + return c.internalClient.ApplySoftwareUpdate(ctx, req, opts...) +} + +// ApplySoftwareUpdateOperation returns a new ApplySoftwareUpdateOperation from a given name. +// The name must be that of a previously created ApplySoftwareUpdateOperation, possibly from a different process. +func (c *CloudMemcacheClient) ApplySoftwareUpdateOperation(name string) *ApplySoftwareUpdateOperation { + return c.internalClient.ApplySoftwareUpdateOperation(name) +} + +// cloudMemcacheGRPCClient is a client for interacting with Cloud Memorystore for Memcached API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudMemcacheGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CloudMemcacheClient + CallOptions **CloudMemcacheCallOptions + // The gRPC API client. cloudMemcacheClient memcachepb.CloudMemcacheClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CloudMemcacheCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCloudMemcacheClient creates a new cloud memcache client. +// NewCloudMemcacheClient creates a new cloud memcache client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Configures and manages Cloud Memorystore for Memcached instances. // @@ -123,8 +282,7 @@ type CloudMemcacheClient struct { // // projects/my-memcached-project/locations/us-central1/instances/my-memcached func NewCloudMemcacheClient(ctx context.Context, opts ...option.ClientOption) (*CloudMemcacheClient, error) { - clientOpts := defaultCloudMemcacheClientOptions() - + clientOpts := defaultCloudMemcacheGRPCClientOptions() if newCloudMemcacheClientHook != nil { hookOpts, err := newCloudMemcacheClientHook(ctx, clientHookParams{}) if err != nil { @@ -142,16 +300,19 @@ func NewCloudMemcacheClient(ctx context.Context, opts ...option.ClientOption) (* if err != nil { return nil, err } - c := &CloudMemcacheClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultCloudMemcacheCallOptions(), + client := CloudMemcacheClient{CallOptions: defaultCloudMemcacheCallOptions()} + c := &cloudMemcacheGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, cloudMemcacheClient: memcachepb.NewCloudMemcacheClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -161,36 +322,36 @@ func NewCloudMemcacheClient(ctx context.Context, opts ...option.ClientOption) (* // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CloudMemcacheClient) Connection() *grpc.ClientConn { +func (c *cloudMemcacheGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CloudMemcacheClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CloudMemcacheClient) setGoogleClientInfo(keyval ...string) { +func (c *cloudMemcacheGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListInstances lists Instances in a given location. -func (c *CloudMemcacheClient) ListInstances(ctx context.Context, req *memcachepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudMemcacheGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *cloudMemcacheGRPCClient) ListInstances(ctx context.Context, req *memcachepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListInstances[0:len(c.CallOptions.ListInstances):len(c.CallOptions.ListInstances)], opts...) + opts = append((*c.CallOptions).ListInstances[0:len((*c.CallOptions).ListInstances):len((*c.CallOptions).ListInstances)], opts...) it := &InstanceIterator{} req = proto.Clone(req).(*memcachepb.ListInstancesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*memcachepb.Instance, string, error) { @@ -227,8 +388,7 @@ func (c *CloudMemcacheClient) ListInstances(ctx context.Context, req *memcachepb return it } -// GetInstance gets details of a single Instance. -func (c *CloudMemcacheClient) GetInstance(ctx context.Context, req *memcachepb.GetInstanceRequest, opts ...gax.CallOption) (*memcachepb.Instance, error) { +func (c *cloudMemcacheGRPCClient) GetInstance(ctx context.Context, req *memcachepb.GetInstanceRequest, opts ...gax.CallOption) (*memcachepb.Instance, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 1200000*time.Millisecond) defer cancel() @@ -236,7 +396,7 @@ func (c *CloudMemcacheClient) GetInstance(ctx context.Context, req *memcachepb.G } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetInstance[0:len(c.CallOptions.GetInstance):len(c.CallOptions.GetInstance)], opts...) + opts = append((*c.CallOptions).GetInstance[0:len((*c.CallOptions).GetInstance):len((*c.CallOptions).GetInstance)], opts...) var resp *memcachepb.Instance err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -249,8 +409,7 @@ func (c *CloudMemcacheClient) GetInstance(ctx context.Context, req *memcachepb.G return resp, nil } -// CreateInstance creates a new Instance in a given location. -func (c *CloudMemcacheClient) CreateInstance(ctx context.Context, req *memcachepb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { +func (c *cloudMemcacheGRPCClient) CreateInstance(ctx context.Context, req *memcachepb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 1200000*time.Millisecond) defer cancel() @@ -258,7 +417,7 @@ func (c *CloudMemcacheClient) CreateInstance(ctx context.Context, req *memcachep } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateInstance[0:len(c.CallOptions.CreateInstance):len(c.CallOptions.CreateInstance)], opts...) + opts = append((*c.CallOptions).CreateInstance[0:len((*c.CallOptions).CreateInstance):len((*c.CallOptions).CreateInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -269,12 +428,11 @@ func (c *CloudMemcacheClient) CreateInstance(ctx context.Context, req *memcachep return nil, err } return &CreateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateInstance updates an existing Instance in a given project and location. -func (c *CloudMemcacheClient) UpdateInstance(ctx context.Context, req *memcachepb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { +func (c *cloudMemcacheGRPCClient) UpdateInstance(ctx context.Context, req *memcachepb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 1200000*time.Millisecond) defer cancel() @@ -282,7 +440,7 @@ func (c *CloudMemcacheClient) UpdateInstance(ctx context.Context, req *memcachep } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource.name", url.QueryEscape(req.GetResource().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateInstance[0:len(c.CallOptions.UpdateInstance):len(c.CallOptions.UpdateInstance)], opts...) + opts = append((*c.CallOptions).UpdateInstance[0:len((*c.CallOptions).UpdateInstance):len((*c.CallOptions).UpdateInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -293,15 +451,11 @@ func (c *CloudMemcacheClient) UpdateInstance(ctx context.Context, req *memcachep return nil, err } return &UpdateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateParameters updates the defined Memcached parameters for an existing instance. -// This method only stages the parameters, it must be followed by -// ApplyParameters to apply the parameters to nodes of the Memcached -// instance. -func (c *CloudMemcacheClient) UpdateParameters(ctx context.Context, req *memcachepb.UpdateParametersRequest, opts ...gax.CallOption) (*UpdateParametersOperation, error) { +func (c *cloudMemcacheGRPCClient) UpdateParameters(ctx context.Context, req *memcachepb.UpdateParametersRequest, opts ...gax.CallOption) (*UpdateParametersOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 1200000*time.Millisecond) defer cancel() @@ -309,7 +463,7 @@ func (c *CloudMemcacheClient) UpdateParameters(ctx context.Context, req *memcach } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateParameters[0:len(c.CallOptions.UpdateParameters):len(c.CallOptions.UpdateParameters)], opts...) + opts = append((*c.CallOptions).UpdateParameters[0:len((*c.CallOptions).UpdateParameters):len((*c.CallOptions).UpdateParameters)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -320,12 +474,11 @@ func (c *CloudMemcacheClient) UpdateParameters(ctx context.Context, req *memcach return nil, err } return &UpdateParametersOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteInstance deletes a single Instance. -func (c *CloudMemcacheClient) DeleteInstance(ctx context.Context, req *memcachepb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { +func (c *cloudMemcacheGRPCClient) DeleteInstance(ctx context.Context, req *memcachepb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 1200000*time.Millisecond) defer cancel() @@ -333,7 +486,7 @@ func (c *CloudMemcacheClient) DeleteInstance(ctx context.Context, req *memcachep } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteInstance[0:len(c.CallOptions.DeleteInstance):len(c.CallOptions.DeleteInstance)], opts...) + opts = append((*c.CallOptions).DeleteInstance[0:len((*c.CallOptions).DeleteInstance):len((*c.CallOptions).DeleteInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -344,13 +497,11 @@ func (c *CloudMemcacheClient) DeleteInstance(ctx context.Context, req *memcachep return nil, err } return &DeleteInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ApplyParameters ApplyParameters restarts the set of specified nodes in order to update -// them to the current set of parameters for the Memcached Instance. -func (c *CloudMemcacheClient) ApplyParameters(ctx context.Context, req *memcachepb.ApplyParametersRequest, opts ...gax.CallOption) (*ApplyParametersOperation, error) { +func (c *cloudMemcacheGRPCClient) ApplyParameters(ctx context.Context, req *memcachepb.ApplyParametersRequest, opts ...gax.CallOption) (*ApplyParametersOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 1200000*time.Millisecond) defer cancel() @@ -358,7 +509,7 @@ func (c *CloudMemcacheClient) ApplyParameters(ctx context.Context, req *memcache } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ApplyParameters[0:len(c.CallOptions.ApplyParameters):len(c.CallOptions.ApplyParameters)], opts...) + opts = append((*c.CallOptions).ApplyParameters[0:len((*c.CallOptions).ApplyParameters):len((*c.CallOptions).ApplyParameters)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -369,12 +520,11 @@ func (c *CloudMemcacheClient) ApplyParameters(ctx context.Context, req *memcache return nil, err } return &ApplyParametersOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ApplySoftwareUpdate updates software on the selected nodes of the Instance. -func (c *CloudMemcacheClient) ApplySoftwareUpdate(ctx context.Context, req *memcachepb.ApplySoftwareUpdateRequest, opts ...gax.CallOption) (*ApplySoftwareUpdateOperation, error) { +func (c *cloudMemcacheGRPCClient) ApplySoftwareUpdate(ctx context.Context, req *memcachepb.ApplySoftwareUpdateRequest, opts ...gax.CallOption) (*ApplySoftwareUpdateOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 1200000*time.Millisecond) defer cancel() @@ -382,7 +532,7 @@ func (c *CloudMemcacheClient) ApplySoftwareUpdate(ctx context.Context, req *memc } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance", url.QueryEscape(req.GetInstance()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ApplySoftwareUpdate[0:len(c.CallOptions.ApplySoftwareUpdate):len(c.CallOptions.ApplySoftwareUpdate)], opts...) + opts = append((*c.CallOptions).ApplySoftwareUpdate[0:len((*c.CallOptions).ApplySoftwareUpdate):len((*c.CallOptions).ApplySoftwareUpdate)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -393,7 +543,7 @@ func (c *CloudMemcacheClient) ApplySoftwareUpdate(ctx context.Context, req *memc return nil, err } return &ApplySoftwareUpdateOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -404,9 +554,9 @@ type ApplyParametersOperation struct { // ApplyParametersOperation returns a new ApplyParametersOperation from a given name. // The name must be that of a previously created ApplyParametersOperation, possibly from a different process. -func (c *CloudMemcacheClient) ApplyParametersOperation(name string) *ApplyParametersOperation { +func (c *cloudMemcacheGRPCClient) ApplyParametersOperation(name string) *ApplyParametersOperation { return &ApplyParametersOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -473,9 +623,9 @@ type ApplySoftwareUpdateOperation struct { // ApplySoftwareUpdateOperation returns a new ApplySoftwareUpdateOperation from a given name. // The name must be that of a previously created ApplySoftwareUpdateOperation, possibly from a different process. -func (c *CloudMemcacheClient) ApplySoftwareUpdateOperation(name string) *ApplySoftwareUpdateOperation { +func (c *cloudMemcacheGRPCClient) ApplySoftwareUpdateOperation(name string) *ApplySoftwareUpdateOperation { return &ApplySoftwareUpdateOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -542,9 +692,9 @@ type CreateInstanceOperation struct { // CreateInstanceOperation returns a new CreateInstanceOperation from a given name. // The name must be that of a previously created CreateInstanceOperation, possibly from a different process. -func (c *CloudMemcacheClient) CreateInstanceOperation(name string) *CreateInstanceOperation { +func (c *cloudMemcacheGRPCClient) CreateInstanceOperation(name string) *CreateInstanceOperation { return &CreateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -611,9 +761,9 @@ type DeleteInstanceOperation struct { // DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. // The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. -func (c *CloudMemcacheClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { +func (c *cloudMemcacheGRPCClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { return &DeleteInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -669,9 +819,9 @@ type UpdateInstanceOperation struct { // UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. // The name must be that of a previously created UpdateInstanceOperation, possibly from a different process. -func (c *CloudMemcacheClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { +func (c *cloudMemcacheGRPCClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { return &UpdateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -738,9 +888,9 @@ type UpdateParametersOperation struct { // UpdateParametersOperation returns a new UpdateParametersOperation from a given name. // The name must be that of a previously created UpdateParametersOperation, possibly from a different process. -func (c *CloudMemcacheClient) UpdateParametersOperation(name string) *UpdateParametersOperation { +func (c *cloudMemcacheGRPCClient) UpdateParametersOperation(name string) *UpdateParametersOperation { return &UpdateParametersOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/memcache/apiv1beta2/cloud_memcache_client_example_test.go b/memcache/apiv1beta2/cloud_memcache_client_example_test.go index d2e028ec9323..40c88b46687a 100644 --- a/memcache/apiv1beta2/cloud_memcache_client_example_test.go +++ b/memcache/apiv1beta2/cloud_memcache_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewCloudMemcacheClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCloudMemcacheClient_ListInstances() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1beta2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.ListInstancesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleCloudMemcacheClient_ListInstances() { } func ExampleCloudMemcacheClient_GetInstance() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1beta2" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.GetInstanceRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleCloudMemcacheClient_GetInstance() { } func ExampleCloudMemcacheClient_CreateInstance() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1beta2" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.CreateInstanceRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleCloudMemcacheClient_CreateInstance() { } func ExampleCloudMemcacheClient_UpdateInstance() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1beta2" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.UpdateInstanceRequest{ // TODO: Fill request struct fields. @@ -132,13 +129,12 @@ func ExampleCloudMemcacheClient_UpdateInstance() { } func ExampleCloudMemcacheClient_UpdateParameters() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1beta2" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.UpdateParametersRequest{ // TODO: Fill request struct fields. @@ -157,13 +153,12 @@ func ExampleCloudMemcacheClient_UpdateParameters() { } func ExampleCloudMemcacheClient_DeleteInstance() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1beta2" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.DeleteInstanceRequest{ // TODO: Fill request struct fields. @@ -180,13 +175,12 @@ func ExampleCloudMemcacheClient_DeleteInstance() { } func ExampleCloudMemcacheClient_ApplyParameters() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1beta2" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.ApplyParametersRequest{ // TODO: Fill request struct fields. @@ -205,13 +199,12 @@ func ExampleCloudMemcacheClient_ApplyParameters() { } func ExampleCloudMemcacheClient_ApplySoftwareUpdate() { - // import memcachepb "google.golang.org/genproto/googleapis/cloud/memcache/v1beta2" - ctx := context.Background() c, err := memcache.NewCloudMemcacheClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &memcachepb.ApplySoftwareUpdateRequest{ // TODO: Fill request struct fields. diff --git a/memcache/apiv1beta2/doc.go b/memcache/apiv1beta2/doc.go index f5f18c962c2f..35620f5911af 100644 --- a/memcache/apiv1beta2/doc.go +++ b/memcache/apiv1beta2/doc.go @@ -20,6 +20,8 @@ // Google Cloud Memorystore for Memcached API is used for creating and // managing Memcached instances in GCP. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package memcache // import "cloud.google.com/go/memcache/apiv1beta2" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/metastore/apiv1/dataproc_metastore_client.go b/metastore/apiv1/dataproc_metastore_client.go index cd87d48dd711..3cec9968002f 100644 --- a/metastore/apiv1/dataproc_metastore_client.go +++ b/metastore/apiv1/dataproc_metastore_client.go @@ -54,7 +54,7 @@ type DataprocMetastoreCallOptions struct { ExportMetadata []gax.CallOption } -func defaultDataprocMetastoreClientOptions() []option.ClientOption { +func defaultDataprocMetastoreGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("metastore.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("metastore.mtls.googleapis.com:443"), @@ -121,32 +121,201 @@ func defaultDataprocMetastoreCallOptions() *DataprocMetastoreCallOptions { } } +// internalDataprocMetastoreClient is an interface that defines the methods availaible from Dataproc Metastore API. +type internalDataprocMetastoreClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListServices(context.Context, *metastorepb.ListServicesRequest, ...gax.CallOption) *ServiceIterator + GetService(context.Context, *metastorepb.GetServiceRequest, ...gax.CallOption) (*metastorepb.Service, error) + CreateService(context.Context, *metastorepb.CreateServiceRequest, ...gax.CallOption) (*CreateServiceOperation, error) + CreateServiceOperation(name string) *CreateServiceOperation + UpdateService(context.Context, *metastorepb.UpdateServiceRequest, ...gax.CallOption) (*UpdateServiceOperation, error) + UpdateServiceOperation(name string) *UpdateServiceOperation + DeleteService(context.Context, *metastorepb.DeleteServiceRequest, ...gax.CallOption) (*DeleteServiceOperation, error) + DeleteServiceOperation(name string) *DeleteServiceOperation + ListMetadataImports(context.Context, *metastorepb.ListMetadataImportsRequest, ...gax.CallOption) *MetadataImportIterator + GetMetadataImport(context.Context, *metastorepb.GetMetadataImportRequest, ...gax.CallOption) (*metastorepb.MetadataImport, error) + CreateMetadataImport(context.Context, *metastorepb.CreateMetadataImportRequest, ...gax.CallOption) (*CreateMetadataImportOperation, error) + CreateMetadataImportOperation(name string) *CreateMetadataImportOperation + UpdateMetadataImport(context.Context, *metastorepb.UpdateMetadataImportRequest, ...gax.CallOption) (*UpdateMetadataImportOperation, error) + UpdateMetadataImportOperation(name string) *UpdateMetadataImportOperation + ExportMetadata(context.Context, *metastorepb.ExportMetadataRequest, ...gax.CallOption) (*ExportMetadataOperation, error) + ExportMetadataOperation(name string) *ExportMetadataOperation +} + // DataprocMetastoreClient is a client for interacting with Dataproc Metastore API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Configures and manages metastore services. +// Metastore services are fully managed, highly available, auto-scaled, +// auto-healing, OSS-native deployments of technical metadata management +// software. Each metastore service exposes a network endpoint through which +// metadata queries are served. Metadata queries can originate from a variety +// of sources, including Apache Hive, Apache Presto, and Apache Spark. +// +// The Dataproc Metastore API defines the following resource model: +// +// The service works with a collection of Google Cloud projects, named: +// /projects/* +// +// Each project has a collection of available locations, named: /locations/* +// (a location must refer to a Google Cloud region) +// +// Each location has a collection of services, named: /services/* +// +// Dataproc Metastore services are resources with names of the form: +// +// /projects/{project_number}/locations/{location_id}/services/{service_id}. type DataprocMetastoreClient struct { + // The internal transport-dependent client. + internalClient internalDataprocMetastoreClient + + // The call options for this service. + CallOptions *DataprocMetastoreCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *DataprocMetastoreClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *DataprocMetastoreClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *DataprocMetastoreClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListServices lists services in a project and location. +func (c *DataprocMetastoreClient) ListServices(ctx context.Context, req *metastorepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { + return c.internalClient.ListServices(ctx, req, opts...) +} + +// GetService gets the details of a single service. +func (c *DataprocMetastoreClient) GetService(ctx context.Context, req *metastorepb.GetServiceRequest, opts ...gax.CallOption) (*metastorepb.Service, error) { + return c.internalClient.GetService(ctx, req, opts...) +} + +// CreateService creates a metastore service in a project and location. +func (c *DataprocMetastoreClient) CreateService(ctx context.Context, req *metastorepb.CreateServiceRequest, opts ...gax.CallOption) (*CreateServiceOperation, error) { + return c.internalClient.CreateService(ctx, req, opts...) +} + +// CreateServiceOperation returns a new CreateServiceOperation from a given name. +// The name must be that of a previously created CreateServiceOperation, possibly from a different process. +func (c *DataprocMetastoreClient) CreateServiceOperation(name string) *CreateServiceOperation { + return c.internalClient.CreateServiceOperation(name) +} + +// UpdateService updates the parameters of a single service. +func (c *DataprocMetastoreClient) UpdateService(ctx context.Context, req *metastorepb.UpdateServiceRequest, opts ...gax.CallOption) (*UpdateServiceOperation, error) { + return c.internalClient.UpdateService(ctx, req, opts...) +} + +// UpdateServiceOperation returns a new UpdateServiceOperation from a given name. +// The name must be that of a previously created UpdateServiceOperation, possibly from a different process. +func (c *DataprocMetastoreClient) UpdateServiceOperation(name string) *UpdateServiceOperation { + return c.internalClient.UpdateServiceOperation(name) +} + +// DeleteService deletes a single service. +func (c *DataprocMetastoreClient) DeleteService(ctx context.Context, req *metastorepb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { + return c.internalClient.DeleteService(ctx, req, opts...) +} + +// DeleteServiceOperation returns a new DeleteServiceOperation from a given name. +// The name must be that of a previously created DeleteServiceOperation, possibly from a different process. +func (c *DataprocMetastoreClient) DeleteServiceOperation(name string) *DeleteServiceOperation { + return c.internalClient.DeleteServiceOperation(name) +} + +// ListMetadataImports lists imports in a service. +func (c *DataprocMetastoreClient) ListMetadataImports(ctx context.Context, req *metastorepb.ListMetadataImportsRequest, opts ...gax.CallOption) *MetadataImportIterator { + return c.internalClient.ListMetadataImports(ctx, req, opts...) +} + +// GetMetadataImport gets details of a single import. +func (c *DataprocMetastoreClient) GetMetadataImport(ctx context.Context, req *metastorepb.GetMetadataImportRequest, opts ...gax.CallOption) (*metastorepb.MetadataImport, error) { + return c.internalClient.GetMetadataImport(ctx, req, opts...) +} + +// CreateMetadataImport creates a new MetadataImport in a given project and location. +func (c *DataprocMetastoreClient) CreateMetadataImport(ctx context.Context, req *metastorepb.CreateMetadataImportRequest, opts ...gax.CallOption) (*CreateMetadataImportOperation, error) { + return c.internalClient.CreateMetadataImport(ctx, req, opts...) +} + +// CreateMetadataImportOperation returns a new CreateMetadataImportOperation from a given name. +// The name must be that of a previously created CreateMetadataImportOperation, possibly from a different process. +func (c *DataprocMetastoreClient) CreateMetadataImportOperation(name string) *CreateMetadataImportOperation { + return c.internalClient.CreateMetadataImportOperation(name) +} + +// UpdateMetadataImport updates a single import. +// Only the description field of MetadataImport is supported to be updated. +func (c *DataprocMetastoreClient) UpdateMetadataImport(ctx context.Context, req *metastorepb.UpdateMetadataImportRequest, opts ...gax.CallOption) (*UpdateMetadataImportOperation, error) { + return c.internalClient.UpdateMetadataImport(ctx, req, opts...) +} + +// UpdateMetadataImportOperation returns a new UpdateMetadataImportOperation from a given name. +// The name must be that of a previously created UpdateMetadataImportOperation, possibly from a different process. +func (c *DataprocMetastoreClient) UpdateMetadataImportOperation(name string) *UpdateMetadataImportOperation { + return c.internalClient.UpdateMetadataImportOperation(name) +} + +// ExportMetadata exports metadata from a service. +func (c *DataprocMetastoreClient) ExportMetadata(ctx context.Context, req *metastorepb.ExportMetadataRequest, opts ...gax.CallOption) (*ExportMetadataOperation, error) { + return c.internalClient.ExportMetadata(ctx, req, opts...) +} + +// ExportMetadataOperation returns a new ExportMetadataOperation from a given name. +// The name must be that of a previously created ExportMetadataOperation, possibly from a different process. +func (c *DataprocMetastoreClient) ExportMetadataOperation(name string) *ExportMetadataOperation { + return c.internalClient.ExportMetadataOperation(name) +} + +// dataprocMetastoreGRPCClient is a client for interacting with Dataproc Metastore API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type dataprocMetastoreGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing DataprocMetastoreClient + CallOptions **DataprocMetastoreCallOptions + // The gRPC API client. dataprocMetastoreClient metastorepb.DataprocMetastoreClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *DataprocMetastoreCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewDataprocMetastoreClient creates a new dataproc metastore client. +// NewDataprocMetastoreClient creates a new dataproc metastore client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Configures and manages metastore services. // Metastore services are fully managed, highly available, auto-scaled, @@ -169,8 +338,7 @@ type DataprocMetastoreClient struct { // // /projects/{project_number}/locations/{location_id}/services/{service_id}. func NewDataprocMetastoreClient(ctx context.Context, opts ...option.ClientOption) (*DataprocMetastoreClient, error) { - clientOpts := defaultDataprocMetastoreClientOptions() - + clientOpts := defaultDataprocMetastoreGRPCClientOptions() if newDataprocMetastoreClientHook != nil { hookOpts, err := newDataprocMetastoreClientHook(ctx, clientHookParams{}) if err != nil { @@ -188,16 +356,19 @@ func NewDataprocMetastoreClient(ctx context.Context, opts ...option.ClientOption if err != nil { return nil, err } - c := &DataprocMetastoreClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultDataprocMetastoreCallOptions(), + client := DataprocMetastoreClient{CallOptions: defaultDataprocMetastoreCallOptions()} + c := &dataprocMetastoreGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, dataprocMetastoreClient: metastorepb.NewDataprocMetastoreClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -207,36 +378,36 @@ func NewDataprocMetastoreClient(ctx context.Context, opts ...option.ClientOption // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *DataprocMetastoreClient) Connection() *grpc.ClientConn { +func (c *dataprocMetastoreGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *DataprocMetastoreClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *DataprocMetastoreClient) setGoogleClientInfo(keyval ...string) { +func (c *dataprocMetastoreGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListServices lists services in a project and location. -func (c *DataprocMetastoreClient) ListServices(ctx context.Context, req *metastorepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *dataprocMetastoreGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *dataprocMetastoreGRPCClient) ListServices(ctx context.Context, req *metastorepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListServices[0:len(c.CallOptions.ListServices):len(c.CallOptions.ListServices)], opts...) + opts = append((*c.CallOptions).ListServices[0:len((*c.CallOptions).ListServices):len((*c.CallOptions).ListServices)], opts...) it := &ServiceIterator{} req = proto.Clone(req).(*metastorepb.ListServicesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*metastorepb.Service, string, error) { @@ -273,8 +444,7 @@ func (c *DataprocMetastoreClient) ListServices(ctx context.Context, req *metasto return it } -// GetService gets the details of a single service. -func (c *DataprocMetastoreClient) GetService(ctx context.Context, req *metastorepb.GetServiceRequest, opts ...gax.CallOption) (*metastorepb.Service, error) { +func (c *dataprocMetastoreGRPCClient) GetService(ctx context.Context, req *metastorepb.GetServiceRequest, opts ...gax.CallOption) (*metastorepb.Service, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -282,7 +452,7 @@ func (c *DataprocMetastoreClient) GetService(ctx context.Context, req *metastore } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetService[0:len(c.CallOptions.GetService):len(c.CallOptions.GetService)], opts...) + opts = append((*c.CallOptions).GetService[0:len((*c.CallOptions).GetService):len((*c.CallOptions).GetService)], opts...) var resp *metastorepb.Service err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -295,8 +465,7 @@ func (c *DataprocMetastoreClient) GetService(ctx context.Context, req *metastore return resp, nil } -// CreateService creates a metastore service in a project and location. -func (c *DataprocMetastoreClient) CreateService(ctx context.Context, req *metastorepb.CreateServiceRequest, opts ...gax.CallOption) (*CreateServiceOperation, error) { +func (c *dataprocMetastoreGRPCClient) CreateService(ctx context.Context, req *metastorepb.CreateServiceRequest, opts ...gax.CallOption) (*CreateServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -304,7 +473,7 @@ func (c *DataprocMetastoreClient) CreateService(ctx context.Context, req *metast } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateService[0:len(c.CallOptions.CreateService):len(c.CallOptions.CreateService)], opts...) + opts = append((*c.CallOptions).CreateService[0:len((*c.CallOptions).CreateService):len((*c.CallOptions).CreateService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -315,12 +484,11 @@ func (c *DataprocMetastoreClient) CreateService(ctx context.Context, req *metast return nil, err } return &CreateServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateService updates the parameters of a single service. -func (c *DataprocMetastoreClient) UpdateService(ctx context.Context, req *metastorepb.UpdateServiceRequest, opts ...gax.CallOption) (*UpdateServiceOperation, error) { +func (c *dataprocMetastoreGRPCClient) UpdateService(ctx context.Context, req *metastorepb.UpdateServiceRequest, opts ...gax.CallOption) (*UpdateServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -328,7 +496,7 @@ func (c *DataprocMetastoreClient) UpdateService(ctx context.Context, req *metast } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service.name", url.QueryEscape(req.GetService().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateService[0:len(c.CallOptions.UpdateService):len(c.CallOptions.UpdateService)], opts...) + opts = append((*c.CallOptions).UpdateService[0:len((*c.CallOptions).UpdateService):len((*c.CallOptions).UpdateService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -339,12 +507,11 @@ func (c *DataprocMetastoreClient) UpdateService(ctx context.Context, req *metast return nil, err } return &UpdateServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteService deletes a single service. -func (c *DataprocMetastoreClient) DeleteService(ctx context.Context, req *metastorepb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { +func (c *dataprocMetastoreGRPCClient) DeleteService(ctx context.Context, req *metastorepb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -352,7 +519,7 @@ func (c *DataprocMetastoreClient) DeleteService(ctx context.Context, req *metast } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteService[0:len(c.CallOptions.DeleteService):len(c.CallOptions.DeleteService)], opts...) + opts = append((*c.CallOptions).DeleteService[0:len((*c.CallOptions).DeleteService):len((*c.CallOptions).DeleteService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -363,15 +530,14 @@ func (c *DataprocMetastoreClient) DeleteService(ctx context.Context, req *metast return nil, err } return &DeleteServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListMetadataImports lists imports in a service. -func (c *DataprocMetastoreClient) ListMetadataImports(ctx context.Context, req *metastorepb.ListMetadataImportsRequest, opts ...gax.CallOption) *MetadataImportIterator { +func (c *dataprocMetastoreGRPCClient) ListMetadataImports(ctx context.Context, req *metastorepb.ListMetadataImportsRequest, opts ...gax.CallOption) *MetadataImportIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListMetadataImports[0:len(c.CallOptions.ListMetadataImports):len(c.CallOptions.ListMetadataImports)], opts...) + opts = append((*c.CallOptions).ListMetadataImports[0:len((*c.CallOptions).ListMetadataImports):len((*c.CallOptions).ListMetadataImports)], opts...) it := &MetadataImportIterator{} req = proto.Clone(req).(*metastorepb.ListMetadataImportsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*metastorepb.MetadataImport, string, error) { @@ -408,8 +574,7 @@ func (c *DataprocMetastoreClient) ListMetadataImports(ctx context.Context, req * return it } -// GetMetadataImport gets details of a single import. -func (c *DataprocMetastoreClient) GetMetadataImport(ctx context.Context, req *metastorepb.GetMetadataImportRequest, opts ...gax.CallOption) (*metastorepb.MetadataImport, error) { +func (c *dataprocMetastoreGRPCClient) GetMetadataImport(ctx context.Context, req *metastorepb.GetMetadataImportRequest, opts ...gax.CallOption) (*metastorepb.MetadataImport, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -417,7 +582,7 @@ func (c *DataprocMetastoreClient) GetMetadataImport(ctx context.Context, req *me } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetMetadataImport[0:len(c.CallOptions.GetMetadataImport):len(c.CallOptions.GetMetadataImport)], opts...) + opts = append((*c.CallOptions).GetMetadataImport[0:len((*c.CallOptions).GetMetadataImport):len((*c.CallOptions).GetMetadataImport)], opts...) var resp *metastorepb.MetadataImport err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -430,8 +595,7 @@ func (c *DataprocMetastoreClient) GetMetadataImport(ctx context.Context, req *me return resp, nil } -// CreateMetadataImport creates a new MetadataImport in a given project and location. -func (c *DataprocMetastoreClient) CreateMetadataImport(ctx context.Context, req *metastorepb.CreateMetadataImportRequest, opts ...gax.CallOption) (*CreateMetadataImportOperation, error) { +func (c *dataprocMetastoreGRPCClient) CreateMetadataImport(ctx context.Context, req *metastorepb.CreateMetadataImportRequest, opts ...gax.CallOption) (*CreateMetadataImportOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -439,7 +603,7 @@ func (c *DataprocMetastoreClient) CreateMetadataImport(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateMetadataImport[0:len(c.CallOptions.CreateMetadataImport):len(c.CallOptions.CreateMetadataImport)], opts...) + opts = append((*c.CallOptions).CreateMetadataImport[0:len((*c.CallOptions).CreateMetadataImport):len((*c.CallOptions).CreateMetadataImport)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -450,13 +614,11 @@ func (c *DataprocMetastoreClient) CreateMetadataImport(ctx context.Context, req return nil, err } return &CreateMetadataImportOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateMetadataImport updates a single import. -// Only the description field of MetadataImport is supported to be updated. -func (c *DataprocMetastoreClient) UpdateMetadataImport(ctx context.Context, req *metastorepb.UpdateMetadataImportRequest, opts ...gax.CallOption) (*UpdateMetadataImportOperation, error) { +func (c *dataprocMetastoreGRPCClient) UpdateMetadataImport(ctx context.Context, req *metastorepb.UpdateMetadataImportRequest, opts ...gax.CallOption) (*UpdateMetadataImportOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -464,7 +626,7 @@ func (c *DataprocMetastoreClient) UpdateMetadataImport(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "metadata_import.name", url.QueryEscape(req.GetMetadataImport().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateMetadataImport[0:len(c.CallOptions.UpdateMetadataImport):len(c.CallOptions.UpdateMetadataImport)], opts...) + opts = append((*c.CallOptions).UpdateMetadataImport[0:len((*c.CallOptions).UpdateMetadataImport):len((*c.CallOptions).UpdateMetadataImport)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -475,12 +637,11 @@ func (c *DataprocMetastoreClient) UpdateMetadataImport(ctx context.Context, req return nil, err } return &UpdateMetadataImportOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ExportMetadata exports metadata from a service. -func (c *DataprocMetastoreClient) ExportMetadata(ctx context.Context, req *metastorepb.ExportMetadataRequest, opts ...gax.CallOption) (*ExportMetadataOperation, error) { +func (c *dataprocMetastoreGRPCClient) ExportMetadata(ctx context.Context, req *metastorepb.ExportMetadataRequest, opts ...gax.CallOption) (*ExportMetadataOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -488,7 +649,7 @@ func (c *DataprocMetastoreClient) ExportMetadata(ctx context.Context, req *metas } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service", url.QueryEscape(req.GetService()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportMetadata[0:len(c.CallOptions.ExportMetadata):len(c.CallOptions.ExportMetadata)], opts...) + opts = append((*c.CallOptions).ExportMetadata[0:len((*c.CallOptions).ExportMetadata):len((*c.CallOptions).ExportMetadata)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -499,7 +660,7 @@ func (c *DataprocMetastoreClient) ExportMetadata(ctx context.Context, req *metas return nil, err } return &ExportMetadataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -510,9 +671,9 @@ type CreateMetadataImportOperation struct { // CreateMetadataImportOperation returns a new CreateMetadataImportOperation from a given name. // The name must be that of a previously created CreateMetadataImportOperation, possibly from a different process. -func (c *DataprocMetastoreClient) CreateMetadataImportOperation(name string) *CreateMetadataImportOperation { +func (c *dataprocMetastoreGRPCClient) CreateMetadataImportOperation(name string) *CreateMetadataImportOperation { return &CreateMetadataImportOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -579,9 +740,9 @@ type CreateServiceOperation struct { // CreateServiceOperation returns a new CreateServiceOperation from a given name. // The name must be that of a previously created CreateServiceOperation, possibly from a different process. -func (c *DataprocMetastoreClient) CreateServiceOperation(name string) *CreateServiceOperation { +func (c *dataprocMetastoreGRPCClient) CreateServiceOperation(name string) *CreateServiceOperation { return &CreateServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -648,9 +809,9 @@ type DeleteServiceOperation struct { // DeleteServiceOperation returns a new DeleteServiceOperation from a given name. // The name must be that of a previously created DeleteServiceOperation, possibly from a different process. -func (c *DataprocMetastoreClient) DeleteServiceOperation(name string) *DeleteServiceOperation { +func (c *dataprocMetastoreGRPCClient) DeleteServiceOperation(name string) *DeleteServiceOperation { return &DeleteServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -706,9 +867,9 @@ type ExportMetadataOperation struct { // ExportMetadataOperation returns a new ExportMetadataOperation from a given name. // The name must be that of a previously created ExportMetadataOperation, possibly from a different process. -func (c *DataprocMetastoreClient) ExportMetadataOperation(name string) *ExportMetadataOperation { +func (c *dataprocMetastoreGRPCClient) ExportMetadataOperation(name string) *ExportMetadataOperation { return &ExportMetadataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -775,9 +936,9 @@ type UpdateMetadataImportOperation struct { // UpdateMetadataImportOperation returns a new UpdateMetadataImportOperation from a given name. // The name must be that of a previously created UpdateMetadataImportOperation, possibly from a different process. -func (c *DataprocMetastoreClient) UpdateMetadataImportOperation(name string) *UpdateMetadataImportOperation { +func (c *dataprocMetastoreGRPCClient) UpdateMetadataImportOperation(name string) *UpdateMetadataImportOperation { return &UpdateMetadataImportOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -844,9 +1005,9 @@ type UpdateServiceOperation struct { // UpdateServiceOperation returns a new UpdateServiceOperation from a given name. // The name must be that of a previously created UpdateServiceOperation, possibly from a different process. -func (c *DataprocMetastoreClient) UpdateServiceOperation(name string) *UpdateServiceOperation { +func (c *dataprocMetastoreGRPCClient) UpdateServiceOperation(name string) *UpdateServiceOperation { return &UpdateServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/metastore/apiv1/dataproc_metastore_client_example_test.go b/metastore/apiv1/dataproc_metastore_client_example_test.go index dd4f49f8ed35..eae26870050a 100644 --- a/metastore/apiv1/dataproc_metastore_client_example_test.go +++ b/metastore/apiv1/dataproc_metastore_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewDataprocMetastoreClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleDataprocMetastoreClient_ListServices() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ListServicesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleDataprocMetastoreClient_ListServices() { } func ExampleDataprocMetastoreClient_GetService() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.GetServiceRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleDataprocMetastoreClient_GetService() { } func ExampleDataprocMetastoreClient_CreateService() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.CreateServiceRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleDataprocMetastoreClient_CreateService() { } func ExampleDataprocMetastoreClient_UpdateService() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.UpdateServiceRequest{ // TODO: Fill request struct fields. @@ -132,13 +129,12 @@ func ExampleDataprocMetastoreClient_UpdateService() { } func ExampleDataprocMetastoreClient_DeleteService() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.DeleteServiceRequest{ // TODO: Fill request struct fields. @@ -155,14 +151,12 @@ func ExampleDataprocMetastoreClient_DeleteService() { } func ExampleDataprocMetastoreClient_ListMetadataImports() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ListMetadataImportsRequest{ // TODO: Fill request struct fields. @@ -182,13 +176,12 @@ func ExampleDataprocMetastoreClient_ListMetadataImports() { } func ExampleDataprocMetastoreClient_GetMetadataImport() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.GetMetadataImportRequest{ // TODO: Fill request struct fields. @@ -202,13 +195,12 @@ func ExampleDataprocMetastoreClient_GetMetadataImport() { } func ExampleDataprocMetastoreClient_CreateMetadataImport() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.CreateMetadataImportRequest{ // TODO: Fill request struct fields. @@ -227,13 +219,12 @@ func ExampleDataprocMetastoreClient_CreateMetadataImport() { } func ExampleDataprocMetastoreClient_UpdateMetadataImport() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.UpdateMetadataImportRequest{ // TODO: Fill request struct fields. @@ -252,13 +243,12 @@ func ExampleDataprocMetastoreClient_UpdateMetadataImport() { } func ExampleDataprocMetastoreClient_ExportMetadata() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ExportMetadataRequest{ // TODO: Fill request struct fields. diff --git a/metastore/apiv1/doc.go b/metastore/apiv1/doc.go index 2c294489cece..1d8d2ba42a7f 100644 --- a/metastore/apiv1/doc.go +++ b/metastore/apiv1/doc.go @@ -20,6 +20,8 @@ // The Dataproc Metastore API is used to manage the lifecycle and // configuration of metastore services. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package metastore // import "cloud.google.com/go/metastore/apiv1" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/metastore/apiv1alpha/dataproc_metastore_client.go b/metastore/apiv1alpha/dataproc_metastore_client.go index 7c27e3488e6d..55f3586dc4a7 100644 --- a/metastore/apiv1alpha/dataproc_metastore_client.go +++ b/metastore/apiv1alpha/dataproc_metastore_client.go @@ -59,7 +59,7 @@ type DataprocMetastoreCallOptions struct { DeleteBackup []gax.CallOption } -func defaultDataprocMetastoreClientOptions() []option.ClientOption { +func defaultDataprocMetastoreGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("metastore.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("metastore.mtls.googleapis.com:443"), @@ -151,32 +151,252 @@ func defaultDataprocMetastoreCallOptions() *DataprocMetastoreCallOptions { } } +// internalDataprocMetastoreClient is an interface that defines the methods availaible from Dataproc Metastore API. +type internalDataprocMetastoreClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListServices(context.Context, *metastorepb.ListServicesRequest, ...gax.CallOption) *ServiceIterator + GetService(context.Context, *metastorepb.GetServiceRequest, ...gax.CallOption) (*metastorepb.Service, error) + CreateService(context.Context, *metastorepb.CreateServiceRequest, ...gax.CallOption) (*CreateServiceOperation, error) + CreateServiceOperation(name string) *CreateServiceOperation + UpdateService(context.Context, *metastorepb.UpdateServiceRequest, ...gax.CallOption) (*UpdateServiceOperation, error) + UpdateServiceOperation(name string) *UpdateServiceOperation + DeleteService(context.Context, *metastorepb.DeleteServiceRequest, ...gax.CallOption) (*DeleteServiceOperation, error) + DeleteServiceOperation(name string) *DeleteServiceOperation + ListMetadataImports(context.Context, *metastorepb.ListMetadataImportsRequest, ...gax.CallOption) *MetadataImportIterator + GetMetadataImport(context.Context, *metastorepb.GetMetadataImportRequest, ...gax.CallOption) (*metastorepb.MetadataImport, error) + CreateMetadataImport(context.Context, *metastorepb.CreateMetadataImportRequest, ...gax.CallOption) (*CreateMetadataImportOperation, error) + CreateMetadataImportOperation(name string) *CreateMetadataImportOperation + UpdateMetadataImport(context.Context, *metastorepb.UpdateMetadataImportRequest, ...gax.CallOption) (*UpdateMetadataImportOperation, error) + UpdateMetadataImportOperation(name string) *UpdateMetadataImportOperation + ExportMetadata(context.Context, *metastorepb.ExportMetadataRequest, ...gax.CallOption) (*ExportMetadataOperation, error) + ExportMetadataOperation(name string) *ExportMetadataOperation + RestoreService(context.Context, *metastorepb.RestoreServiceRequest, ...gax.CallOption) (*RestoreServiceOperation, error) + RestoreServiceOperation(name string) *RestoreServiceOperation + ListBackups(context.Context, *metastorepb.ListBackupsRequest, ...gax.CallOption) *BackupIterator + GetBackup(context.Context, *metastorepb.GetBackupRequest, ...gax.CallOption) (*metastorepb.Backup, error) + CreateBackup(context.Context, *metastorepb.CreateBackupRequest, ...gax.CallOption) (*CreateBackupOperation, error) + CreateBackupOperation(name string) *CreateBackupOperation + DeleteBackup(context.Context, *metastorepb.DeleteBackupRequest, ...gax.CallOption) (*DeleteBackupOperation, error) + DeleteBackupOperation(name string) *DeleteBackupOperation +} + // DataprocMetastoreClient is a client for interacting with Dataproc Metastore API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Configures and manages metastore services. +// Metastore services are fully managed, highly available, auto-scaled, +// auto-healing, OSS-native deployments of technical metadata management +// software. Each metastore service exposes a network endpoint through which +// metadata queries are served. Metadata queries can originate from a variety +// of sources, including Apache Hive, Apache Presto, and Apache Spark. +// +// The Dataproc Metastore API defines the following resource model: +// +// The service works with a collection of Google Cloud projects, named: +// /projects/* +// +// Each project has a collection of available locations, named: /locations/* +// (a location must refer to a Google Cloud region) +// +// Each location has a collection of services, named: /services/* +// +// Dataproc Metastore services are resources with names of the form: +// +// /projects/{project_number}/locations/{location_id}/services/{service_id}. type DataprocMetastoreClient struct { + // The internal transport-dependent client. + internalClient internalDataprocMetastoreClient + + // The call options for this service. + CallOptions *DataprocMetastoreCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *DataprocMetastoreClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *DataprocMetastoreClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *DataprocMetastoreClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListServices lists services in a project and location. +func (c *DataprocMetastoreClient) ListServices(ctx context.Context, req *metastorepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { + return c.internalClient.ListServices(ctx, req, opts...) +} + +// GetService gets the details of a single service. +func (c *DataprocMetastoreClient) GetService(ctx context.Context, req *metastorepb.GetServiceRequest, opts ...gax.CallOption) (*metastorepb.Service, error) { + return c.internalClient.GetService(ctx, req, opts...) +} + +// CreateService creates a metastore service in a project and location. +func (c *DataprocMetastoreClient) CreateService(ctx context.Context, req *metastorepb.CreateServiceRequest, opts ...gax.CallOption) (*CreateServiceOperation, error) { + return c.internalClient.CreateService(ctx, req, opts...) +} + +// CreateServiceOperation returns a new CreateServiceOperation from a given name. +// The name must be that of a previously created CreateServiceOperation, possibly from a different process. +func (c *DataprocMetastoreClient) CreateServiceOperation(name string) *CreateServiceOperation { + return c.internalClient.CreateServiceOperation(name) +} + +// UpdateService updates the parameters of a single service. +func (c *DataprocMetastoreClient) UpdateService(ctx context.Context, req *metastorepb.UpdateServiceRequest, opts ...gax.CallOption) (*UpdateServiceOperation, error) { + return c.internalClient.UpdateService(ctx, req, opts...) +} + +// UpdateServiceOperation returns a new UpdateServiceOperation from a given name. +// The name must be that of a previously created UpdateServiceOperation, possibly from a different process. +func (c *DataprocMetastoreClient) UpdateServiceOperation(name string) *UpdateServiceOperation { + return c.internalClient.UpdateServiceOperation(name) +} + +// DeleteService deletes a single service. +func (c *DataprocMetastoreClient) DeleteService(ctx context.Context, req *metastorepb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { + return c.internalClient.DeleteService(ctx, req, opts...) +} + +// DeleteServiceOperation returns a new DeleteServiceOperation from a given name. +// The name must be that of a previously created DeleteServiceOperation, possibly from a different process. +func (c *DataprocMetastoreClient) DeleteServiceOperation(name string) *DeleteServiceOperation { + return c.internalClient.DeleteServiceOperation(name) +} + +// ListMetadataImports lists imports in a service. +func (c *DataprocMetastoreClient) ListMetadataImports(ctx context.Context, req *metastorepb.ListMetadataImportsRequest, opts ...gax.CallOption) *MetadataImportIterator { + return c.internalClient.ListMetadataImports(ctx, req, opts...) +} + +// GetMetadataImport gets details of a single import. +func (c *DataprocMetastoreClient) GetMetadataImport(ctx context.Context, req *metastorepb.GetMetadataImportRequest, opts ...gax.CallOption) (*metastorepb.MetadataImport, error) { + return c.internalClient.GetMetadataImport(ctx, req, opts...) +} + +// CreateMetadataImport creates a new MetadataImport in a given project and location. +func (c *DataprocMetastoreClient) CreateMetadataImport(ctx context.Context, req *metastorepb.CreateMetadataImportRequest, opts ...gax.CallOption) (*CreateMetadataImportOperation, error) { + return c.internalClient.CreateMetadataImport(ctx, req, opts...) +} + +// CreateMetadataImportOperation returns a new CreateMetadataImportOperation from a given name. +// The name must be that of a previously created CreateMetadataImportOperation, possibly from a different process. +func (c *DataprocMetastoreClient) CreateMetadataImportOperation(name string) *CreateMetadataImportOperation { + return c.internalClient.CreateMetadataImportOperation(name) +} + +// UpdateMetadataImport updates a single import. +// Only the description field of MetadataImport is supported to be updated. +func (c *DataprocMetastoreClient) UpdateMetadataImport(ctx context.Context, req *metastorepb.UpdateMetadataImportRequest, opts ...gax.CallOption) (*UpdateMetadataImportOperation, error) { + return c.internalClient.UpdateMetadataImport(ctx, req, opts...) +} + +// UpdateMetadataImportOperation returns a new UpdateMetadataImportOperation from a given name. +// The name must be that of a previously created UpdateMetadataImportOperation, possibly from a different process. +func (c *DataprocMetastoreClient) UpdateMetadataImportOperation(name string) *UpdateMetadataImportOperation { + return c.internalClient.UpdateMetadataImportOperation(name) +} + +// ExportMetadata exports metadata from a service. +func (c *DataprocMetastoreClient) ExportMetadata(ctx context.Context, req *metastorepb.ExportMetadataRequest, opts ...gax.CallOption) (*ExportMetadataOperation, error) { + return c.internalClient.ExportMetadata(ctx, req, opts...) +} + +// ExportMetadataOperation returns a new ExportMetadataOperation from a given name. +// The name must be that of a previously created ExportMetadataOperation, possibly from a different process. +func (c *DataprocMetastoreClient) ExportMetadataOperation(name string) *ExportMetadataOperation { + return c.internalClient.ExportMetadataOperation(name) +} + +// RestoreService restores a service from a backup. +func (c *DataprocMetastoreClient) RestoreService(ctx context.Context, req *metastorepb.RestoreServiceRequest, opts ...gax.CallOption) (*RestoreServiceOperation, error) { + return c.internalClient.RestoreService(ctx, req, opts...) +} + +// RestoreServiceOperation returns a new RestoreServiceOperation from a given name. +// The name must be that of a previously created RestoreServiceOperation, possibly from a different process. +func (c *DataprocMetastoreClient) RestoreServiceOperation(name string) *RestoreServiceOperation { + return c.internalClient.RestoreServiceOperation(name) +} + +// ListBackups lists backups in a service. +func (c *DataprocMetastoreClient) ListBackups(ctx context.Context, req *metastorepb.ListBackupsRequest, opts ...gax.CallOption) *BackupIterator { + return c.internalClient.ListBackups(ctx, req, opts...) +} + +// GetBackup gets details of a single backup. +func (c *DataprocMetastoreClient) GetBackup(ctx context.Context, req *metastorepb.GetBackupRequest, opts ...gax.CallOption) (*metastorepb.Backup, error) { + return c.internalClient.GetBackup(ctx, req, opts...) +} + +// CreateBackup creates a new Backup in a given project and location. +func (c *DataprocMetastoreClient) CreateBackup(ctx context.Context, req *metastorepb.CreateBackupRequest, opts ...gax.CallOption) (*CreateBackupOperation, error) { + return c.internalClient.CreateBackup(ctx, req, opts...) +} + +// CreateBackupOperation returns a new CreateBackupOperation from a given name. +// The name must be that of a previously created CreateBackupOperation, possibly from a different process. +func (c *DataprocMetastoreClient) CreateBackupOperation(name string) *CreateBackupOperation { + return c.internalClient.CreateBackupOperation(name) +} + +// DeleteBackup deletes a single backup. +func (c *DataprocMetastoreClient) DeleteBackup(ctx context.Context, req *metastorepb.DeleteBackupRequest, opts ...gax.CallOption) (*DeleteBackupOperation, error) { + return c.internalClient.DeleteBackup(ctx, req, opts...) +} + +// DeleteBackupOperation returns a new DeleteBackupOperation from a given name. +// The name must be that of a previously created DeleteBackupOperation, possibly from a different process. +func (c *DataprocMetastoreClient) DeleteBackupOperation(name string) *DeleteBackupOperation { + return c.internalClient.DeleteBackupOperation(name) +} + +// dataprocMetastoreGRPCClient is a client for interacting with Dataproc Metastore API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type dataprocMetastoreGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing DataprocMetastoreClient + CallOptions **DataprocMetastoreCallOptions + // The gRPC API client. dataprocMetastoreClient metastorepb.DataprocMetastoreClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *DataprocMetastoreCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewDataprocMetastoreClient creates a new dataproc metastore client. +// NewDataprocMetastoreClient creates a new dataproc metastore client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Configures and manages metastore services. // Metastore services are fully managed, highly available, auto-scaled, @@ -199,8 +419,7 @@ type DataprocMetastoreClient struct { // // /projects/{project_number}/locations/{location_id}/services/{service_id}. func NewDataprocMetastoreClient(ctx context.Context, opts ...option.ClientOption) (*DataprocMetastoreClient, error) { - clientOpts := defaultDataprocMetastoreClientOptions() - + clientOpts := defaultDataprocMetastoreGRPCClientOptions() if newDataprocMetastoreClientHook != nil { hookOpts, err := newDataprocMetastoreClientHook(ctx, clientHookParams{}) if err != nil { @@ -218,16 +437,19 @@ func NewDataprocMetastoreClient(ctx context.Context, opts ...option.ClientOption if err != nil { return nil, err } - c := &DataprocMetastoreClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultDataprocMetastoreCallOptions(), + client := DataprocMetastoreClient{CallOptions: defaultDataprocMetastoreCallOptions()} + c := &dataprocMetastoreGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, dataprocMetastoreClient: metastorepb.NewDataprocMetastoreClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -237,36 +459,36 @@ func NewDataprocMetastoreClient(ctx context.Context, opts ...option.ClientOption // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *DataprocMetastoreClient) Connection() *grpc.ClientConn { +func (c *dataprocMetastoreGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *DataprocMetastoreClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *DataprocMetastoreClient) setGoogleClientInfo(keyval ...string) { +func (c *dataprocMetastoreGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListServices lists services in a project and location. -func (c *DataprocMetastoreClient) ListServices(ctx context.Context, req *metastorepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *dataprocMetastoreGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *dataprocMetastoreGRPCClient) ListServices(ctx context.Context, req *metastorepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListServices[0:len(c.CallOptions.ListServices):len(c.CallOptions.ListServices)], opts...) + opts = append((*c.CallOptions).ListServices[0:len((*c.CallOptions).ListServices):len((*c.CallOptions).ListServices)], opts...) it := &ServiceIterator{} req = proto.Clone(req).(*metastorepb.ListServicesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*metastorepb.Service, string, error) { @@ -303,8 +525,7 @@ func (c *DataprocMetastoreClient) ListServices(ctx context.Context, req *metasto return it } -// GetService gets the details of a single service. -func (c *DataprocMetastoreClient) GetService(ctx context.Context, req *metastorepb.GetServiceRequest, opts ...gax.CallOption) (*metastorepb.Service, error) { +func (c *dataprocMetastoreGRPCClient) GetService(ctx context.Context, req *metastorepb.GetServiceRequest, opts ...gax.CallOption) (*metastorepb.Service, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -312,7 +533,7 @@ func (c *DataprocMetastoreClient) GetService(ctx context.Context, req *metastore } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetService[0:len(c.CallOptions.GetService):len(c.CallOptions.GetService)], opts...) + opts = append((*c.CallOptions).GetService[0:len((*c.CallOptions).GetService):len((*c.CallOptions).GetService)], opts...) var resp *metastorepb.Service err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -325,8 +546,7 @@ func (c *DataprocMetastoreClient) GetService(ctx context.Context, req *metastore return resp, nil } -// CreateService creates a metastore service in a project and location. -func (c *DataprocMetastoreClient) CreateService(ctx context.Context, req *metastorepb.CreateServiceRequest, opts ...gax.CallOption) (*CreateServiceOperation, error) { +func (c *dataprocMetastoreGRPCClient) CreateService(ctx context.Context, req *metastorepb.CreateServiceRequest, opts ...gax.CallOption) (*CreateServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -334,7 +554,7 @@ func (c *DataprocMetastoreClient) CreateService(ctx context.Context, req *metast } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateService[0:len(c.CallOptions.CreateService):len(c.CallOptions.CreateService)], opts...) + opts = append((*c.CallOptions).CreateService[0:len((*c.CallOptions).CreateService):len((*c.CallOptions).CreateService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -345,12 +565,11 @@ func (c *DataprocMetastoreClient) CreateService(ctx context.Context, req *metast return nil, err } return &CreateServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateService updates the parameters of a single service. -func (c *DataprocMetastoreClient) UpdateService(ctx context.Context, req *metastorepb.UpdateServiceRequest, opts ...gax.CallOption) (*UpdateServiceOperation, error) { +func (c *dataprocMetastoreGRPCClient) UpdateService(ctx context.Context, req *metastorepb.UpdateServiceRequest, opts ...gax.CallOption) (*UpdateServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -358,7 +577,7 @@ func (c *DataprocMetastoreClient) UpdateService(ctx context.Context, req *metast } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service.name", url.QueryEscape(req.GetService().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateService[0:len(c.CallOptions.UpdateService):len(c.CallOptions.UpdateService)], opts...) + opts = append((*c.CallOptions).UpdateService[0:len((*c.CallOptions).UpdateService):len((*c.CallOptions).UpdateService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -369,12 +588,11 @@ func (c *DataprocMetastoreClient) UpdateService(ctx context.Context, req *metast return nil, err } return &UpdateServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteService deletes a single service. -func (c *DataprocMetastoreClient) DeleteService(ctx context.Context, req *metastorepb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { +func (c *dataprocMetastoreGRPCClient) DeleteService(ctx context.Context, req *metastorepb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -382,7 +600,7 @@ func (c *DataprocMetastoreClient) DeleteService(ctx context.Context, req *metast } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteService[0:len(c.CallOptions.DeleteService):len(c.CallOptions.DeleteService)], opts...) + opts = append((*c.CallOptions).DeleteService[0:len((*c.CallOptions).DeleteService):len((*c.CallOptions).DeleteService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -393,15 +611,14 @@ func (c *DataprocMetastoreClient) DeleteService(ctx context.Context, req *metast return nil, err } return &DeleteServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListMetadataImports lists imports in a service. -func (c *DataprocMetastoreClient) ListMetadataImports(ctx context.Context, req *metastorepb.ListMetadataImportsRequest, opts ...gax.CallOption) *MetadataImportIterator { +func (c *dataprocMetastoreGRPCClient) ListMetadataImports(ctx context.Context, req *metastorepb.ListMetadataImportsRequest, opts ...gax.CallOption) *MetadataImportIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListMetadataImports[0:len(c.CallOptions.ListMetadataImports):len(c.CallOptions.ListMetadataImports)], opts...) + opts = append((*c.CallOptions).ListMetadataImports[0:len((*c.CallOptions).ListMetadataImports):len((*c.CallOptions).ListMetadataImports)], opts...) it := &MetadataImportIterator{} req = proto.Clone(req).(*metastorepb.ListMetadataImportsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*metastorepb.MetadataImport, string, error) { @@ -438,8 +655,7 @@ func (c *DataprocMetastoreClient) ListMetadataImports(ctx context.Context, req * return it } -// GetMetadataImport gets details of a single import. -func (c *DataprocMetastoreClient) GetMetadataImport(ctx context.Context, req *metastorepb.GetMetadataImportRequest, opts ...gax.CallOption) (*metastorepb.MetadataImport, error) { +func (c *dataprocMetastoreGRPCClient) GetMetadataImport(ctx context.Context, req *metastorepb.GetMetadataImportRequest, opts ...gax.CallOption) (*metastorepb.MetadataImport, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -447,7 +663,7 @@ func (c *DataprocMetastoreClient) GetMetadataImport(ctx context.Context, req *me } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetMetadataImport[0:len(c.CallOptions.GetMetadataImport):len(c.CallOptions.GetMetadataImport)], opts...) + opts = append((*c.CallOptions).GetMetadataImport[0:len((*c.CallOptions).GetMetadataImport):len((*c.CallOptions).GetMetadataImport)], opts...) var resp *metastorepb.MetadataImport err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -460,8 +676,7 @@ func (c *DataprocMetastoreClient) GetMetadataImport(ctx context.Context, req *me return resp, nil } -// CreateMetadataImport creates a new MetadataImport in a given project and location. -func (c *DataprocMetastoreClient) CreateMetadataImport(ctx context.Context, req *metastorepb.CreateMetadataImportRequest, opts ...gax.CallOption) (*CreateMetadataImportOperation, error) { +func (c *dataprocMetastoreGRPCClient) CreateMetadataImport(ctx context.Context, req *metastorepb.CreateMetadataImportRequest, opts ...gax.CallOption) (*CreateMetadataImportOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -469,7 +684,7 @@ func (c *DataprocMetastoreClient) CreateMetadataImport(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateMetadataImport[0:len(c.CallOptions.CreateMetadataImport):len(c.CallOptions.CreateMetadataImport)], opts...) + opts = append((*c.CallOptions).CreateMetadataImport[0:len((*c.CallOptions).CreateMetadataImport):len((*c.CallOptions).CreateMetadataImport)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -480,13 +695,11 @@ func (c *DataprocMetastoreClient) CreateMetadataImport(ctx context.Context, req return nil, err } return &CreateMetadataImportOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateMetadataImport updates a single import. -// Only the description field of MetadataImport is supported to be updated. -func (c *DataprocMetastoreClient) UpdateMetadataImport(ctx context.Context, req *metastorepb.UpdateMetadataImportRequest, opts ...gax.CallOption) (*UpdateMetadataImportOperation, error) { +func (c *dataprocMetastoreGRPCClient) UpdateMetadataImport(ctx context.Context, req *metastorepb.UpdateMetadataImportRequest, opts ...gax.CallOption) (*UpdateMetadataImportOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -494,7 +707,7 @@ func (c *DataprocMetastoreClient) UpdateMetadataImport(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "metadata_import.name", url.QueryEscape(req.GetMetadataImport().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateMetadataImport[0:len(c.CallOptions.UpdateMetadataImport):len(c.CallOptions.UpdateMetadataImport)], opts...) + opts = append((*c.CallOptions).UpdateMetadataImport[0:len((*c.CallOptions).UpdateMetadataImport):len((*c.CallOptions).UpdateMetadataImport)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -505,12 +718,11 @@ func (c *DataprocMetastoreClient) UpdateMetadataImport(ctx context.Context, req return nil, err } return &UpdateMetadataImportOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ExportMetadata exports metadata from a service. -func (c *DataprocMetastoreClient) ExportMetadata(ctx context.Context, req *metastorepb.ExportMetadataRequest, opts ...gax.CallOption) (*ExportMetadataOperation, error) { +func (c *dataprocMetastoreGRPCClient) ExportMetadata(ctx context.Context, req *metastorepb.ExportMetadataRequest, opts ...gax.CallOption) (*ExportMetadataOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -518,7 +730,7 @@ func (c *DataprocMetastoreClient) ExportMetadata(ctx context.Context, req *metas } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service", url.QueryEscape(req.GetService()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportMetadata[0:len(c.CallOptions.ExportMetadata):len(c.CallOptions.ExportMetadata)], opts...) + opts = append((*c.CallOptions).ExportMetadata[0:len((*c.CallOptions).ExportMetadata):len((*c.CallOptions).ExportMetadata)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -529,12 +741,11 @@ func (c *DataprocMetastoreClient) ExportMetadata(ctx context.Context, req *metas return nil, err } return &ExportMetadataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// RestoreService restores a service from a backup. -func (c *DataprocMetastoreClient) RestoreService(ctx context.Context, req *metastorepb.RestoreServiceRequest, opts ...gax.CallOption) (*RestoreServiceOperation, error) { +func (c *dataprocMetastoreGRPCClient) RestoreService(ctx context.Context, req *metastorepb.RestoreServiceRequest, opts ...gax.CallOption) (*RestoreServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -542,7 +753,7 @@ func (c *DataprocMetastoreClient) RestoreService(ctx context.Context, req *metas } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service", url.QueryEscape(req.GetService()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RestoreService[0:len(c.CallOptions.RestoreService):len(c.CallOptions.RestoreService)], opts...) + opts = append((*c.CallOptions).RestoreService[0:len((*c.CallOptions).RestoreService):len((*c.CallOptions).RestoreService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -553,15 +764,14 @@ func (c *DataprocMetastoreClient) RestoreService(ctx context.Context, req *metas return nil, err } return &RestoreServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListBackups lists backups in a service. -func (c *DataprocMetastoreClient) ListBackups(ctx context.Context, req *metastorepb.ListBackupsRequest, opts ...gax.CallOption) *BackupIterator { +func (c *dataprocMetastoreGRPCClient) ListBackups(ctx context.Context, req *metastorepb.ListBackupsRequest, opts ...gax.CallOption) *BackupIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListBackups[0:len(c.CallOptions.ListBackups):len(c.CallOptions.ListBackups)], opts...) + opts = append((*c.CallOptions).ListBackups[0:len((*c.CallOptions).ListBackups):len((*c.CallOptions).ListBackups)], opts...) it := &BackupIterator{} req = proto.Clone(req).(*metastorepb.ListBackupsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*metastorepb.Backup, string, error) { @@ -598,8 +808,7 @@ func (c *DataprocMetastoreClient) ListBackups(ctx context.Context, req *metastor return it } -// GetBackup gets details of a single backup. -func (c *DataprocMetastoreClient) GetBackup(ctx context.Context, req *metastorepb.GetBackupRequest, opts ...gax.CallOption) (*metastorepb.Backup, error) { +func (c *dataprocMetastoreGRPCClient) GetBackup(ctx context.Context, req *metastorepb.GetBackupRequest, opts ...gax.CallOption) (*metastorepb.Backup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -607,7 +816,7 @@ func (c *DataprocMetastoreClient) GetBackup(ctx context.Context, req *metastorep } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetBackup[0:len(c.CallOptions.GetBackup):len(c.CallOptions.GetBackup)], opts...) + opts = append((*c.CallOptions).GetBackup[0:len((*c.CallOptions).GetBackup):len((*c.CallOptions).GetBackup)], opts...) var resp *metastorepb.Backup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -620,8 +829,7 @@ func (c *DataprocMetastoreClient) GetBackup(ctx context.Context, req *metastorep return resp, nil } -// CreateBackup creates a new Backup in a given project and location. -func (c *DataprocMetastoreClient) CreateBackup(ctx context.Context, req *metastorepb.CreateBackupRequest, opts ...gax.CallOption) (*CreateBackupOperation, error) { +func (c *dataprocMetastoreGRPCClient) CreateBackup(ctx context.Context, req *metastorepb.CreateBackupRequest, opts ...gax.CallOption) (*CreateBackupOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -629,7 +837,7 @@ func (c *DataprocMetastoreClient) CreateBackup(ctx context.Context, req *metasto } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateBackup[0:len(c.CallOptions.CreateBackup):len(c.CallOptions.CreateBackup)], opts...) + opts = append((*c.CallOptions).CreateBackup[0:len((*c.CallOptions).CreateBackup):len((*c.CallOptions).CreateBackup)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -640,12 +848,11 @@ func (c *DataprocMetastoreClient) CreateBackup(ctx context.Context, req *metasto return nil, err } return &CreateBackupOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteBackup deletes a single backup. -func (c *DataprocMetastoreClient) DeleteBackup(ctx context.Context, req *metastorepb.DeleteBackupRequest, opts ...gax.CallOption) (*DeleteBackupOperation, error) { +func (c *dataprocMetastoreGRPCClient) DeleteBackup(ctx context.Context, req *metastorepb.DeleteBackupRequest, opts ...gax.CallOption) (*DeleteBackupOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -653,7 +860,7 @@ func (c *DataprocMetastoreClient) DeleteBackup(ctx context.Context, req *metasto } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteBackup[0:len(c.CallOptions.DeleteBackup):len(c.CallOptions.DeleteBackup)], opts...) + opts = append((*c.CallOptions).DeleteBackup[0:len((*c.CallOptions).DeleteBackup):len((*c.CallOptions).DeleteBackup)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -664,7 +871,7 @@ func (c *DataprocMetastoreClient) DeleteBackup(ctx context.Context, req *metasto return nil, err } return &DeleteBackupOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -675,9 +882,9 @@ type CreateBackupOperation struct { // CreateBackupOperation returns a new CreateBackupOperation from a given name. // The name must be that of a previously created CreateBackupOperation, possibly from a different process. -func (c *DataprocMetastoreClient) CreateBackupOperation(name string) *CreateBackupOperation { +func (c *dataprocMetastoreGRPCClient) CreateBackupOperation(name string) *CreateBackupOperation { return &CreateBackupOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -744,9 +951,9 @@ type CreateMetadataImportOperation struct { // CreateMetadataImportOperation returns a new CreateMetadataImportOperation from a given name. // The name must be that of a previously created CreateMetadataImportOperation, possibly from a different process. -func (c *DataprocMetastoreClient) CreateMetadataImportOperation(name string) *CreateMetadataImportOperation { +func (c *dataprocMetastoreGRPCClient) CreateMetadataImportOperation(name string) *CreateMetadataImportOperation { return &CreateMetadataImportOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -813,9 +1020,9 @@ type CreateServiceOperation struct { // CreateServiceOperation returns a new CreateServiceOperation from a given name. // The name must be that of a previously created CreateServiceOperation, possibly from a different process. -func (c *DataprocMetastoreClient) CreateServiceOperation(name string) *CreateServiceOperation { +func (c *dataprocMetastoreGRPCClient) CreateServiceOperation(name string) *CreateServiceOperation { return &CreateServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -882,9 +1089,9 @@ type DeleteBackupOperation struct { // DeleteBackupOperation returns a new DeleteBackupOperation from a given name. // The name must be that of a previously created DeleteBackupOperation, possibly from a different process. -func (c *DataprocMetastoreClient) DeleteBackupOperation(name string) *DeleteBackupOperation { +func (c *dataprocMetastoreGRPCClient) DeleteBackupOperation(name string) *DeleteBackupOperation { return &DeleteBackupOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -940,9 +1147,9 @@ type DeleteServiceOperation struct { // DeleteServiceOperation returns a new DeleteServiceOperation from a given name. // The name must be that of a previously created DeleteServiceOperation, possibly from a different process. -func (c *DataprocMetastoreClient) DeleteServiceOperation(name string) *DeleteServiceOperation { +func (c *dataprocMetastoreGRPCClient) DeleteServiceOperation(name string) *DeleteServiceOperation { return &DeleteServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -998,9 +1205,9 @@ type ExportMetadataOperation struct { // ExportMetadataOperation returns a new ExportMetadataOperation from a given name. // The name must be that of a previously created ExportMetadataOperation, possibly from a different process. -func (c *DataprocMetastoreClient) ExportMetadataOperation(name string) *ExportMetadataOperation { +func (c *dataprocMetastoreGRPCClient) ExportMetadataOperation(name string) *ExportMetadataOperation { return &ExportMetadataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1067,9 +1274,9 @@ type RestoreServiceOperation struct { // RestoreServiceOperation returns a new RestoreServiceOperation from a given name. // The name must be that of a previously created RestoreServiceOperation, possibly from a different process. -func (c *DataprocMetastoreClient) RestoreServiceOperation(name string) *RestoreServiceOperation { +func (c *dataprocMetastoreGRPCClient) RestoreServiceOperation(name string) *RestoreServiceOperation { return &RestoreServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1136,9 +1343,9 @@ type UpdateMetadataImportOperation struct { // UpdateMetadataImportOperation returns a new UpdateMetadataImportOperation from a given name. // The name must be that of a previously created UpdateMetadataImportOperation, possibly from a different process. -func (c *DataprocMetastoreClient) UpdateMetadataImportOperation(name string) *UpdateMetadataImportOperation { +func (c *dataprocMetastoreGRPCClient) UpdateMetadataImportOperation(name string) *UpdateMetadataImportOperation { return &UpdateMetadataImportOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1205,9 +1412,9 @@ type UpdateServiceOperation struct { // UpdateServiceOperation returns a new UpdateServiceOperation from a given name. // The name must be that of a previously created UpdateServiceOperation, possibly from a different process. -func (c *DataprocMetastoreClient) UpdateServiceOperation(name string) *UpdateServiceOperation { +func (c *dataprocMetastoreGRPCClient) UpdateServiceOperation(name string) *UpdateServiceOperation { return &UpdateServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/metastore/apiv1alpha/dataproc_metastore_client_example_test.go b/metastore/apiv1alpha/dataproc_metastore_client_example_test.go index c29a1be9df43..89e7fa12d864 100644 --- a/metastore/apiv1alpha/dataproc_metastore_client_example_test.go +++ b/metastore/apiv1alpha/dataproc_metastore_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewDataprocMetastoreClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleDataprocMetastoreClient_ListServices() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ListServicesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleDataprocMetastoreClient_ListServices() { } func ExampleDataprocMetastoreClient_GetService() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.GetServiceRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleDataprocMetastoreClient_GetService() { } func ExampleDataprocMetastoreClient_CreateService() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.CreateServiceRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleDataprocMetastoreClient_CreateService() { } func ExampleDataprocMetastoreClient_UpdateService() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.UpdateServiceRequest{ // TODO: Fill request struct fields. @@ -132,13 +129,12 @@ func ExampleDataprocMetastoreClient_UpdateService() { } func ExampleDataprocMetastoreClient_DeleteService() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.DeleteServiceRequest{ // TODO: Fill request struct fields. @@ -155,14 +151,12 @@ func ExampleDataprocMetastoreClient_DeleteService() { } func ExampleDataprocMetastoreClient_ListMetadataImports() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ListMetadataImportsRequest{ // TODO: Fill request struct fields. @@ -182,13 +176,12 @@ func ExampleDataprocMetastoreClient_ListMetadataImports() { } func ExampleDataprocMetastoreClient_GetMetadataImport() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.GetMetadataImportRequest{ // TODO: Fill request struct fields. @@ -202,13 +195,12 @@ func ExampleDataprocMetastoreClient_GetMetadataImport() { } func ExampleDataprocMetastoreClient_CreateMetadataImport() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.CreateMetadataImportRequest{ // TODO: Fill request struct fields. @@ -227,13 +219,12 @@ func ExampleDataprocMetastoreClient_CreateMetadataImport() { } func ExampleDataprocMetastoreClient_UpdateMetadataImport() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.UpdateMetadataImportRequest{ // TODO: Fill request struct fields. @@ -252,13 +243,12 @@ func ExampleDataprocMetastoreClient_UpdateMetadataImport() { } func ExampleDataprocMetastoreClient_ExportMetadata() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ExportMetadataRequest{ // TODO: Fill request struct fields. @@ -277,13 +267,12 @@ func ExampleDataprocMetastoreClient_ExportMetadata() { } func ExampleDataprocMetastoreClient_RestoreService() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.RestoreServiceRequest{ // TODO: Fill request struct fields. @@ -302,14 +291,12 @@ func ExampleDataprocMetastoreClient_RestoreService() { } func ExampleDataprocMetastoreClient_ListBackups() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ListBackupsRequest{ // TODO: Fill request struct fields. @@ -329,13 +316,12 @@ func ExampleDataprocMetastoreClient_ListBackups() { } func ExampleDataprocMetastoreClient_GetBackup() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.GetBackupRequest{ // TODO: Fill request struct fields. @@ -349,13 +335,12 @@ func ExampleDataprocMetastoreClient_GetBackup() { } func ExampleDataprocMetastoreClient_CreateBackup() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.CreateBackupRequest{ // TODO: Fill request struct fields. @@ -374,13 +359,12 @@ func ExampleDataprocMetastoreClient_CreateBackup() { } func ExampleDataprocMetastoreClient_DeleteBackup() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1alpha" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.DeleteBackupRequest{ // TODO: Fill request struct fields. diff --git a/metastore/apiv1alpha/doc.go b/metastore/apiv1alpha/doc.go index bb6c648e2f27..10aab94b11fe 100644 --- a/metastore/apiv1alpha/doc.go +++ b/metastore/apiv1alpha/doc.go @@ -20,6 +20,8 @@ // The Dataproc Metastore API is used to manage the lifecycle and // configuration of metastore services. // +// NOTE: This package is in alpha. It is not stable, and is likely to change. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package metastore // import "cloud.google.com/go/metastore/apiv1alpha" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/metastore/apiv1beta/dataproc_metastore_client.go b/metastore/apiv1beta/dataproc_metastore_client.go index 26ee90b87f86..5b6e91633e7b 100644 --- a/metastore/apiv1beta/dataproc_metastore_client.go +++ b/metastore/apiv1beta/dataproc_metastore_client.go @@ -59,7 +59,7 @@ type DataprocMetastoreCallOptions struct { DeleteBackup []gax.CallOption } -func defaultDataprocMetastoreClientOptions() []option.ClientOption { +func defaultDataprocMetastoreGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("metastore.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("metastore.mtls.googleapis.com:443"), @@ -151,32 +151,252 @@ func defaultDataprocMetastoreCallOptions() *DataprocMetastoreCallOptions { } } +// internalDataprocMetastoreClient is an interface that defines the methods availaible from Dataproc Metastore API. +type internalDataprocMetastoreClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListServices(context.Context, *metastorepb.ListServicesRequest, ...gax.CallOption) *ServiceIterator + GetService(context.Context, *metastorepb.GetServiceRequest, ...gax.CallOption) (*metastorepb.Service, error) + CreateService(context.Context, *metastorepb.CreateServiceRequest, ...gax.CallOption) (*CreateServiceOperation, error) + CreateServiceOperation(name string) *CreateServiceOperation + UpdateService(context.Context, *metastorepb.UpdateServiceRequest, ...gax.CallOption) (*UpdateServiceOperation, error) + UpdateServiceOperation(name string) *UpdateServiceOperation + DeleteService(context.Context, *metastorepb.DeleteServiceRequest, ...gax.CallOption) (*DeleteServiceOperation, error) + DeleteServiceOperation(name string) *DeleteServiceOperation + ListMetadataImports(context.Context, *metastorepb.ListMetadataImportsRequest, ...gax.CallOption) *MetadataImportIterator + GetMetadataImport(context.Context, *metastorepb.GetMetadataImportRequest, ...gax.CallOption) (*metastorepb.MetadataImport, error) + CreateMetadataImport(context.Context, *metastorepb.CreateMetadataImportRequest, ...gax.CallOption) (*CreateMetadataImportOperation, error) + CreateMetadataImportOperation(name string) *CreateMetadataImportOperation + UpdateMetadataImport(context.Context, *metastorepb.UpdateMetadataImportRequest, ...gax.CallOption) (*UpdateMetadataImportOperation, error) + UpdateMetadataImportOperation(name string) *UpdateMetadataImportOperation + ExportMetadata(context.Context, *metastorepb.ExportMetadataRequest, ...gax.CallOption) (*ExportMetadataOperation, error) + ExportMetadataOperation(name string) *ExportMetadataOperation + RestoreService(context.Context, *metastorepb.RestoreServiceRequest, ...gax.CallOption) (*RestoreServiceOperation, error) + RestoreServiceOperation(name string) *RestoreServiceOperation + ListBackups(context.Context, *metastorepb.ListBackupsRequest, ...gax.CallOption) *BackupIterator + GetBackup(context.Context, *metastorepb.GetBackupRequest, ...gax.CallOption) (*metastorepb.Backup, error) + CreateBackup(context.Context, *metastorepb.CreateBackupRequest, ...gax.CallOption) (*CreateBackupOperation, error) + CreateBackupOperation(name string) *CreateBackupOperation + DeleteBackup(context.Context, *metastorepb.DeleteBackupRequest, ...gax.CallOption) (*DeleteBackupOperation, error) + DeleteBackupOperation(name string) *DeleteBackupOperation +} + // DataprocMetastoreClient is a client for interacting with Dataproc Metastore API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Configures and manages metastore services. +// Metastore services are fully managed, highly available, auto-scaled, +// auto-healing, OSS-native deployments of technical metadata management +// software. Each metastore service exposes a network endpoint through which +// metadata queries are served. Metadata queries can originate from a variety +// of sources, including Apache Hive, Apache Presto, and Apache Spark. +// +// The Dataproc Metastore API defines the following resource model: +// +// The service works with a collection of Google Cloud projects, named: +// /projects/* +// +// Each project has a collection of available locations, named: /locations/* +// (a location must refer to a Google Cloud region) +// +// Each location has a collection of services, named: /services/* +// +// Dataproc Metastore services are resources with names of the form: +// +// /projects/{project_number}/locations/{location_id}/services/{service_id}. type DataprocMetastoreClient struct { + // The internal transport-dependent client. + internalClient internalDataprocMetastoreClient + + // The call options for this service. + CallOptions *DataprocMetastoreCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *DataprocMetastoreClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *DataprocMetastoreClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *DataprocMetastoreClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListServices lists services in a project and location. +func (c *DataprocMetastoreClient) ListServices(ctx context.Context, req *metastorepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { + return c.internalClient.ListServices(ctx, req, opts...) +} + +// GetService gets the details of a single service. +func (c *DataprocMetastoreClient) GetService(ctx context.Context, req *metastorepb.GetServiceRequest, opts ...gax.CallOption) (*metastorepb.Service, error) { + return c.internalClient.GetService(ctx, req, opts...) +} + +// CreateService creates a metastore service in a project and location. +func (c *DataprocMetastoreClient) CreateService(ctx context.Context, req *metastorepb.CreateServiceRequest, opts ...gax.CallOption) (*CreateServiceOperation, error) { + return c.internalClient.CreateService(ctx, req, opts...) +} + +// CreateServiceOperation returns a new CreateServiceOperation from a given name. +// The name must be that of a previously created CreateServiceOperation, possibly from a different process. +func (c *DataprocMetastoreClient) CreateServiceOperation(name string) *CreateServiceOperation { + return c.internalClient.CreateServiceOperation(name) +} + +// UpdateService updates the parameters of a single service. +func (c *DataprocMetastoreClient) UpdateService(ctx context.Context, req *metastorepb.UpdateServiceRequest, opts ...gax.CallOption) (*UpdateServiceOperation, error) { + return c.internalClient.UpdateService(ctx, req, opts...) +} + +// UpdateServiceOperation returns a new UpdateServiceOperation from a given name. +// The name must be that of a previously created UpdateServiceOperation, possibly from a different process. +func (c *DataprocMetastoreClient) UpdateServiceOperation(name string) *UpdateServiceOperation { + return c.internalClient.UpdateServiceOperation(name) +} + +// DeleteService deletes a single service. +func (c *DataprocMetastoreClient) DeleteService(ctx context.Context, req *metastorepb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { + return c.internalClient.DeleteService(ctx, req, opts...) +} + +// DeleteServiceOperation returns a new DeleteServiceOperation from a given name. +// The name must be that of a previously created DeleteServiceOperation, possibly from a different process. +func (c *DataprocMetastoreClient) DeleteServiceOperation(name string) *DeleteServiceOperation { + return c.internalClient.DeleteServiceOperation(name) +} + +// ListMetadataImports lists imports in a service. +func (c *DataprocMetastoreClient) ListMetadataImports(ctx context.Context, req *metastorepb.ListMetadataImportsRequest, opts ...gax.CallOption) *MetadataImportIterator { + return c.internalClient.ListMetadataImports(ctx, req, opts...) +} + +// GetMetadataImport gets details of a single import. +func (c *DataprocMetastoreClient) GetMetadataImport(ctx context.Context, req *metastorepb.GetMetadataImportRequest, opts ...gax.CallOption) (*metastorepb.MetadataImport, error) { + return c.internalClient.GetMetadataImport(ctx, req, opts...) +} + +// CreateMetadataImport creates a new MetadataImport in a given project and location. +func (c *DataprocMetastoreClient) CreateMetadataImport(ctx context.Context, req *metastorepb.CreateMetadataImportRequest, opts ...gax.CallOption) (*CreateMetadataImportOperation, error) { + return c.internalClient.CreateMetadataImport(ctx, req, opts...) +} + +// CreateMetadataImportOperation returns a new CreateMetadataImportOperation from a given name. +// The name must be that of a previously created CreateMetadataImportOperation, possibly from a different process. +func (c *DataprocMetastoreClient) CreateMetadataImportOperation(name string) *CreateMetadataImportOperation { + return c.internalClient.CreateMetadataImportOperation(name) +} + +// UpdateMetadataImport updates a single import. +// Only the description field of MetadataImport is supported to be updated. +func (c *DataprocMetastoreClient) UpdateMetadataImport(ctx context.Context, req *metastorepb.UpdateMetadataImportRequest, opts ...gax.CallOption) (*UpdateMetadataImportOperation, error) { + return c.internalClient.UpdateMetadataImport(ctx, req, opts...) +} + +// UpdateMetadataImportOperation returns a new UpdateMetadataImportOperation from a given name. +// The name must be that of a previously created UpdateMetadataImportOperation, possibly from a different process. +func (c *DataprocMetastoreClient) UpdateMetadataImportOperation(name string) *UpdateMetadataImportOperation { + return c.internalClient.UpdateMetadataImportOperation(name) +} + +// ExportMetadata exports metadata from a service. +func (c *DataprocMetastoreClient) ExportMetadata(ctx context.Context, req *metastorepb.ExportMetadataRequest, opts ...gax.CallOption) (*ExportMetadataOperation, error) { + return c.internalClient.ExportMetadata(ctx, req, opts...) +} + +// ExportMetadataOperation returns a new ExportMetadataOperation from a given name. +// The name must be that of a previously created ExportMetadataOperation, possibly from a different process. +func (c *DataprocMetastoreClient) ExportMetadataOperation(name string) *ExportMetadataOperation { + return c.internalClient.ExportMetadataOperation(name) +} + +// RestoreService restores a service from a backup. +func (c *DataprocMetastoreClient) RestoreService(ctx context.Context, req *metastorepb.RestoreServiceRequest, opts ...gax.CallOption) (*RestoreServiceOperation, error) { + return c.internalClient.RestoreService(ctx, req, opts...) +} + +// RestoreServiceOperation returns a new RestoreServiceOperation from a given name. +// The name must be that of a previously created RestoreServiceOperation, possibly from a different process. +func (c *DataprocMetastoreClient) RestoreServiceOperation(name string) *RestoreServiceOperation { + return c.internalClient.RestoreServiceOperation(name) +} + +// ListBackups lists backups in a service. +func (c *DataprocMetastoreClient) ListBackups(ctx context.Context, req *metastorepb.ListBackupsRequest, opts ...gax.CallOption) *BackupIterator { + return c.internalClient.ListBackups(ctx, req, opts...) +} + +// GetBackup gets details of a single backup. +func (c *DataprocMetastoreClient) GetBackup(ctx context.Context, req *metastorepb.GetBackupRequest, opts ...gax.CallOption) (*metastorepb.Backup, error) { + return c.internalClient.GetBackup(ctx, req, opts...) +} + +// CreateBackup creates a new Backup in a given project and location. +func (c *DataprocMetastoreClient) CreateBackup(ctx context.Context, req *metastorepb.CreateBackupRequest, opts ...gax.CallOption) (*CreateBackupOperation, error) { + return c.internalClient.CreateBackup(ctx, req, opts...) +} + +// CreateBackupOperation returns a new CreateBackupOperation from a given name. +// The name must be that of a previously created CreateBackupOperation, possibly from a different process. +func (c *DataprocMetastoreClient) CreateBackupOperation(name string) *CreateBackupOperation { + return c.internalClient.CreateBackupOperation(name) +} + +// DeleteBackup deletes a single backup. +func (c *DataprocMetastoreClient) DeleteBackup(ctx context.Context, req *metastorepb.DeleteBackupRequest, opts ...gax.CallOption) (*DeleteBackupOperation, error) { + return c.internalClient.DeleteBackup(ctx, req, opts...) +} + +// DeleteBackupOperation returns a new DeleteBackupOperation from a given name. +// The name must be that of a previously created DeleteBackupOperation, possibly from a different process. +func (c *DataprocMetastoreClient) DeleteBackupOperation(name string) *DeleteBackupOperation { + return c.internalClient.DeleteBackupOperation(name) +} + +// dataprocMetastoreGRPCClient is a client for interacting with Dataproc Metastore API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type dataprocMetastoreGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing DataprocMetastoreClient + CallOptions **DataprocMetastoreCallOptions + // The gRPC API client. dataprocMetastoreClient metastorepb.DataprocMetastoreClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *DataprocMetastoreCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewDataprocMetastoreClient creates a new dataproc metastore client. +// NewDataprocMetastoreClient creates a new dataproc metastore client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Configures and manages metastore services. // Metastore services are fully managed, highly available, auto-scaled, @@ -199,8 +419,7 @@ type DataprocMetastoreClient struct { // // /projects/{project_number}/locations/{location_id}/services/{service_id}. func NewDataprocMetastoreClient(ctx context.Context, opts ...option.ClientOption) (*DataprocMetastoreClient, error) { - clientOpts := defaultDataprocMetastoreClientOptions() - + clientOpts := defaultDataprocMetastoreGRPCClientOptions() if newDataprocMetastoreClientHook != nil { hookOpts, err := newDataprocMetastoreClientHook(ctx, clientHookParams{}) if err != nil { @@ -218,16 +437,19 @@ func NewDataprocMetastoreClient(ctx context.Context, opts ...option.ClientOption if err != nil { return nil, err } - c := &DataprocMetastoreClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultDataprocMetastoreCallOptions(), + client := DataprocMetastoreClient{CallOptions: defaultDataprocMetastoreCallOptions()} + c := &dataprocMetastoreGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, dataprocMetastoreClient: metastorepb.NewDataprocMetastoreClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -237,36 +459,36 @@ func NewDataprocMetastoreClient(ctx context.Context, opts ...option.ClientOption // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *DataprocMetastoreClient) Connection() *grpc.ClientConn { +func (c *dataprocMetastoreGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *DataprocMetastoreClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *DataprocMetastoreClient) setGoogleClientInfo(keyval ...string) { +func (c *dataprocMetastoreGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListServices lists services in a project and location. -func (c *DataprocMetastoreClient) ListServices(ctx context.Context, req *metastorepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *dataprocMetastoreGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *dataprocMetastoreGRPCClient) ListServices(ctx context.Context, req *metastorepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListServices[0:len(c.CallOptions.ListServices):len(c.CallOptions.ListServices)], opts...) + opts = append((*c.CallOptions).ListServices[0:len((*c.CallOptions).ListServices):len((*c.CallOptions).ListServices)], opts...) it := &ServiceIterator{} req = proto.Clone(req).(*metastorepb.ListServicesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*metastorepb.Service, string, error) { @@ -303,8 +525,7 @@ func (c *DataprocMetastoreClient) ListServices(ctx context.Context, req *metasto return it } -// GetService gets the details of a single service. -func (c *DataprocMetastoreClient) GetService(ctx context.Context, req *metastorepb.GetServiceRequest, opts ...gax.CallOption) (*metastorepb.Service, error) { +func (c *dataprocMetastoreGRPCClient) GetService(ctx context.Context, req *metastorepb.GetServiceRequest, opts ...gax.CallOption) (*metastorepb.Service, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -312,7 +533,7 @@ func (c *DataprocMetastoreClient) GetService(ctx context.Context, req *metastore } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetService[0:len(c.CallOptions.GetService):len(c.CallOptions.GetService)], opts...) + opts = append((*c.CallOptions).GetService[0:len((*c.CallOptions).GetService):len((*c.CallOptions).GetService)], opts...) var resp *metastorepb.Service err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -325,8 +546,7 @@ func (c *DataprocMetastoreClient) GetService(ctx context.Context, req *metastore return resp, nil } -// CreateService creates a metastore service in a project and location. -func (c *DataprocMetastoreClient) CreateService(ctx context.Context, req *metastorepb.CreateServiceRequest, opts ...gax.CallOption) (*CreateServiceOperation, error) { +func (c *dataprocMetastoreGRPCClient) CreateService(ctx context.Context, req *metastorepb.CreateServiceRequest, opts ...gax.CallOption) (*CreateServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -334,7 +554,7 @@ func (c *DataprocMetastoreClient) CreateService(ctx context.Context, req *metast } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateService[0:len(c.CallOptions.CreateService):len(c.CallOptions.CreateService)], opts...) + opts = append((*c.CallOptions).CreateService[0:len((*c.CallOptions).CreateService):len((*c.CallOptions).CreateService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -345,12 +565,11 @@ func (c *DataprocMetastoreClient) CreateService(ctx context.Context, req *metast return nil, err } return &CreateServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateService updates the parameters of a single service. -func (c *DataprocMetastoreClient) UpdateService(ctx context.Context, req *metastorepb.UpdateServiceRequest, opts ...gax.CallOption) (*UpdateServiceOperation, error) { +func (c *dataprocMetastoreGRPCClient) UpdateService(ctx context.Context, req *metastorepb.UpdateServiceRequest, opts ...gax.CallOption) (*UpdateServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -358,7 +577,7 @@ func (c *DataprocMetastoreClient) UpdateService(ctx context.Context, req *metast } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service.name", url.QueryEscape(req.GetService().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateService[0:len(c.CallOptions.UpdateService):len(c.CallOptions.UpdateService)], opts...) + opts = append((*c.CallOptions).UpdateService[0:len((*c.CallOptions).UpdateService):len((*c.CallOptions).UpdateService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -369,12 +588,11 @@ func (c *DataprocMetastoreClient) UpdateService(ctx context.Context, req *metast return nil, err } return &UpdateServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteService deletes a single service. -func (c *DataprocMetastoreClient) DeleteService(ctx context.Context, req *metastorepb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { +func (c *dataprocMetastoreGRPCClient) DeleteService(ctx context.Context, req *metastorepb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -382,7 +600,7 @@ func (c *DataprocMetastoreClient) DeleteService(ctx context.Context, req *metast } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteService[0:len(c.CallOptions.DeleteService):len(c.CallOptions.DeleteService)], opts...) + opts = append((*c.CallOptions).DeleteService[0:len((*c.CallOptions).DeleteService):len((*c.CallOptions).DeleteService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -393,15 +611,14 @@ func (c *DataprocMetastoreClient) DeleteService(ctx context.Context, req *metast return nil, err } return &DeleteServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListMetadataImports lists imports in a service. -func (c *DataprocMetastoreClient) ListMetadataImports(ctx context.Context, req *metastorepb.ListMetadataImportsRequest, opts ...gax.CallOption) *MetadataImportIterator { +func (c *dataprocMetastoreGRPCClient) ListMetadataImports(ctx context.Context, req *metastorepb.ListMetadataImportsRequest, opts ...gax.CallOption) *MetadataImportIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListMetadataImports[0:len(c.CallOptions.ListMetadataImports):len(c.CallOptions.ListMetadataImports)], opts...) + opts = append((*c.CallOptions).ListMetadataImports[0:len((*c.CallOptions).ListMetadataImports):len((*c.CallOptions).ListMetadataImports)], opts...) it := &MetadataImportIterator{} req = proto.Clone(req).(*metastorepb.ListMetadataImportsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*metastorepb.MetadataImport, string, error) { @@ -438,8 +655,7 @@ func (c *DataprocMetastoreClient) ListMetadataImports(ctx context.Context, req * return it } -// GetMetadataImport gets details of a single import. -func (c *DataprocMetastoreClient) GetMetadataImport(ctx context.Context, req *metastorepb.GetMetadataImportRequest, opts ...gax.CallOption) (*metastorepb.MetadataImport, error) { +func (c *dataprocMetastoreGRPCClient) GetMetadataImport(ctx context.Context, req *metastorepb.GetMetadataImportRequest, opts ...gax.CallOption) (*metastorepb.MetadataImport, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -447,7 +663,7 @@ func (c *DataprocMetastoreClient) GetMetadataImport(ctx context.Context, req *me } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetMetadataImport[0:len(c.CallOptions.GetMetadataImport):len(c.CallOptions.GetMetadataImport)], opts...) + opts = append((*c.CallOptions).GetMetadataImport[0:len((*c.CallOptions).GetMetadataImport):len((*c.CallOptions).GetMetadataImport)], opts...) var resp *metastorepb.MetadataImport err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -460,8 +676,7 @@ func (c *DataprocMetastoreClient) GetMetadataImport(ctx context.Context, req *me return resp, nil } -// CreateMetadataImport creates a new MetadataImport in a given project and location. -func (c *DataprocMetastoreClient) CreateMetadataImport(ctx context.Context, req *metastorepb.CreateMetadataImportRequest, opts ...gax.CallOption) (*CreateMetadataImportOperation, error) { +func (c *dataprocMetastoreGRPCClient) CreateMetadataImport(ctx context.Context, req *metastorepb.CreateMetadataImportRequest, opts ...gax.CallOption) (*CreateMetadataImportOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -469,7 +684,7 @@ func (c *DataprocMetastoreClient) CreateMetadataImport(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateMetadataImport[0:len(c.CallOptions.CreateMetadataImport):len(c.CallOptions.CreateMetadataImport)], opts...) + opts = append((*c.CallOptions).CreateMetadataImport[0:len((*c.CallOptions).CreateMetadataImport):len((*c.CallOptions).CreateMetadataImport)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -480,13 +695,11 @@ func (c *DataprocMetastoreClient) CreateMetadataImport(ctx context.Context, req return nil, err } return &CreateMetadataImportOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateMetadataImport updates a single import. -// Only the description field of MetadataImport is supported to be updated. -func (c *DataprocMetastoreClient) UpdateMetadataImport(ctx context.Context, req *metastorepb.UpdateMetadataImportRequest, opts ...gax.CallOption) (*UpdateMetadataImportOperation, error) { +func (c *dataprocMetastoreGRPCClient) UpdateMetadataImport(ctx context.Context, req *metastorepb.UpdateMetadataImportRequest, opts ...gax.CallOption) (*UpdateMetadataImportOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -494,7 +707,7 @@ func (c *DataprocMetastoreClient) UpdateMetadataImport(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "metadata_import.name", url.QueryEscape(req.GetMetadataImport().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateMetadataImport[0:len(c.CallOptions.UpdateMetadataImport):len(c.CallOptions.UpdateMetadataImport)], opts...) + opts = append((*c.CallOptions).UpdateMetadataImport[0:len((*c.CallOptions).UpdateMetadataImport):len((*c.CallOptions).UpdateMetadataImport)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -505,12 +718,11 @@ func (c *DataprocMetastoreClient) UpdateMetadataImport(ctx context.Context, req return nil, err } return &UpdateMetadataImportOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ExportMetadata exports metadata from a service. -func (c *DataprocMetastoreClient) ExportMetadata(ctx context.Context, req *metastorepb.ExportMetadataRequest, opts ...gax.CallOption) (*ExportMetadataOperation, error) { +func (c *dataprocMetastoreGRPCClient) ExportMetadata(ctx context.Context, req *metastorepb.ExportMetadataRequest, opts ...gax.CallOption) (*ExportMetadataOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -518,7 +730,7 @@ func (c *DataprocMetastoreClient) ExportMetadata(ctx context.Context, req *metas } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service", url.QueryEscape(req.GetService()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportMetadata[0:len(c.CallOptions.ExportMetadata):len(c.CallOptions.ExportMetadata)], opts...) + opts = append((*c.CallOptions).ExportMetadata[0:len((*c.CallOptions).ExportMetadata):len((*c.CallOptions).ExportMetadata)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -529,12 +741,11 @@ func (c *DataprocMetastoreClient) ExportMetadata(ctx context.Context, req *metas return nil, err } return &ExportMetadataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// RestoreService restores a service from a backup. -func (c *DataprocMetastoreClient) RestoreService(ctx context.Context, req *metastorepb.RestoreServiceRequest, opts ...gax.CallOption) (*RestoreServiceOperation, error) { +func (c *dataprocMetastoreGRPCClient) RestoreService(ctx context.Context, req *metastorepb.RestoreServiceRequest, opts ...gax.CallOption) (*RestoreServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -542,7 +753,7 @@ func (c *DataprocMetastoreClient) RestoreService(ctx context.Context, req *metas } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service", url.QueryEscape(req.GetService()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RestoreService[0:len(c.CallOptions.RestoreService):len(c.CallOptions.RestoreService)], opts...) + opts = append((*c.CallOptions).RestoreService[0:len((*c.CallOptions).RestoreService):len((*c.CallOptions).RestoreService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -553,15 +764,14 @@ func (c *DataprocMetastoreClient) RestoreService(ctx context.Context, req *metas return nil, err } return &RestoreServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListBackups lists backups in a service. -func (c *DataprocMetastoreClient) ListBackups(ctx context.Context, req *metastorepb.ListBackupsRequest, opts ...gax.CallOption) *BackupIterator { +func (c *dataprocMetastoreGRPCClient) ListBackups(ctx context.Context, req *metastorepb.ListBackupsRequest, opts ...gax.CallOption) *BackupIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListBackups[0:len(c.CallOptions.ListBackups):len(c.CallOptions.ListBackups)], opts...) + opts = append((*c.CallOptions).ListBackups[0:len((*c.CallOptions).ListBackups):len((*c.CallOptions).ListBackups)], opts...) it := &BackupIterator{} req = proto.Clone(req).(*metastorepb.ListBackupsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*metastorepb.Backup, string, error) { @@ -598,8 +808,7 @@ func (c *DataprocMetastoreClient) ListBackups(ctx context.Context, req *metastor return it } -// GetBackup gets details of a single backup. -func (c *DataprocMetastoreClient) GetBackup(ctx context.Context, req *metastorepb.GetBackupRequest, opts ...gax.CallOption) (*metastorepb.Backup, error) { +func (c *dataprocMetastoreGRPCClient) GetBackup(ctx context.Context, req *metastorepb.GetBackupRequest, opts ...gax.CallOption) (*metastorepb.Backup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -607,7 +816,7 @@ func (c *DataprocMetastoreClient) GetBackup(ctx context.Context, req *metastorep } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetBackup[0:len(c.CallOptions.GetBackup):len(c.CallOptions.GetBackup)], opts...) + opts = append((*c.CallOptions).GetBackup[0:len((*c.CallOptions).GetBackup):len((*c.CallOptions).GetBackup)], opts...) var resp *metastorepb.Backup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -620,8 +829,7 @@ func (c *DataprocMetastoreClient) GetBackup(ctx context.Context, req *metastorep return resp, nil } -// CreateBackup creates a new Backup in a given project and location. -func (c *DataprocMetastoreClient) CreateBackup(ctx context.Context, req *metastorepb.CreateBackupRequest, opts ...gax.CallOption) (*CreateBackupOperation, error) { +func (c *dataprocMetastoreGRPCClient) CreateBackup(ctx context.Context, req *metastorepb.CreateBackupRequest, opts ...gax.CallOption) (*CreateBackupOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -629,7 +837,7 @@ func (c *DataprocMetastoreClient) CreateBackup(ctx context.Context, req *metasto } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateBackup[0:len(c.CallOptions.CreateBackup):len(c.CallOptions.CreateBackup)], opts...) + opts = append((*c.CallOptions).CreateBackup[0:len((*c.CallOptions).CreateBackup):len((*c.CallOptions).CreateBackup)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -640,12 +848,11 @@ func (c *DataprocMetastoreClient) CreateBackup(ctx context.Context, req *metasto return nil, err } return &CreateBackupOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteBackup deletes a single backup. -func (c *DataprocMetastoreClient) DeleteBackup(ctx context.Context, req *metastorepb.DeleteBackupRequest, opts ...gax.CallOption) (*DeleteBackupOperation, error) { +func (c *dataprocMetastoreGRPCClient) DeleteBackup(ctx context.Context, req *metastorepb.DeleteBackupRequest, opts ...gax.CallOption) (*DeleteBackupOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -653,7 +860,7 @@ func (c *DataprocMetastoreClient) DeleteBackup(ctx context.Context, req *metasto } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteBackup[0:len(c.CallOptions.DeleteBackup):len(c.CallOptions.DeleteBackup)], opts...) + opts = append((*c.CallOptions).DeleteBackup[0:len((*c.CallOptions).DeleteBackup):len((*c.CallOptions).DeleteBackup)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -664,7 +871,7 @@ func (c *DataprocMetastoreClient) DeleteBackup(ctx context.Context, req *metasto return nil, err } return &DeleteBackupOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -675,9 +882,9 @@ type CreateBackupOperation struct { // CreateBackupOperation returns a new CreateBackupOperation from a given name. // The name must be that of a previously created CreateBackupOperation, possibly from a different process. -func (c *DataprocMetastoreClient) CreateBackupOperation(name string) *CreateBackupOperation { +func (c *dataprocMetastoreGRPCClient) CreateBackupOperation(name string) *CreateBackupOperation { return &CreateBackupOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -744,9 +951,9 @@ type CreateMetadataImportOperation struct { // CreateMetadataImportOperation returns a new CreateMetadataImportOperation from a given name. // The name must be that of a previously created CreateMetadataImportOperation, possibly from a different process. -func (c *DataprocMetastoreClient) CreateMetadataImportOperation(name string) *CreateMetadataImportOperation { +func (c *dataprocMetastoreGRPCClient) CreateMetadataImportOperation(name string) *CreateMetadataImportOperation { return &CreateMetadataImportOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -813,9 +1020,9 @@ type CreateServiceOperation struct { // CreateServiceOperation returns a new CreateServiceOperation from a given name. // The name must be that of a previously created CreateServiceOperation, possibly from a different process. -func (c *DataprocMetastoreClient) CreateServiceOperation(name string) *CreateServiceOperation { +func (c *dataprocMetastoreGRPCClient) CreateServiceOperation(name string) *CreateServiceOperation { return &CreateServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -882,9 +1089,9 @@ type DeleteBackupOperation struct { // DeleteBackupOperation returns a new DeleteBackupOperation from a given name. // The name must be that of a previously created DeleteBackupOperation, possibly from a different process. -func (c *DataprocMetastoreClient) DeleteBackupOperation(name string) *DeleteBackupOperation { +func (c *dataprocMetastoreGRPCClient) DeleteBackupOperation(name string) *DeleteBackupOperation { return &DeleteBackupOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -940,9 +1147,9 @@ type DeleteServiceOperation struct { // DeleteServiceOperation returns a new DeleteServiceOperation from a given name. // The name must be that of a previously created DeleteServiceOperation, possibly from a different process. -func (c *DataprocMetastoreClient) DeleteServiceOperation(name string) *DeleteServiceOperation { +func (c *dataprocMetastoreGRPCClient) DeleteServiceOperation(name string) *DeleteServiceOperation { return &DeleteServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -998,9 +1205,9 @@ type ExportMetadataOperation struct { // ExportMetadataOperation returns a new ExportMetadataOperation from a given name. // The name must be that of a previously created ExportMetadataOperation, possibly from a different process. -func (c *DataprocMetastoreClient) ExportMetadataOperation(name string) *ExportMetadataOperation { +func (c *dataprocMetastoreGRPCClient) ExportMetadataOperation(name string) *ExportMetadataOperation { return &ExportMetadataOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1067,9 +1274,9 @@ type RestoreServiceOperation struct { // RestoreServiceOperation returns a new RestoreServiceOperation from a given name. // The name must be that of a previously created RestoreServiceOperation, possibly from a different process. -func (c *DataprocMetastoreClient) RestoreServiceOperation(name string) *RestoreServiceOperation { +func (c *dataprocMetastoreGRPCClient) RestoreServiceOperation(name string) *RestoreServiceOperation { return &RestoreServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1136,9 +1343,9 @@ type UpdateMetadataImportOperation struct { // UpdateMetadataImportOperation returns a new UpdateMetadataImportOperation from a given name. // The name must be that of a previously created UpdateMetadataImportOperation, possibly from a different process. -func (c *DataprocMetastoreClient) UpdateMetadataImportOperation(name string) *UpdateMetadataImportOperation { +func (c *dataprocMetastoreGRPCClient) UpdateMetadataImportOperation(name string) *UpdateMetadataImportOperation { return &UpdateMetadataImportOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1205,9 +1412,9 @@ type UpdateServiceOperation struct { // UpdateServiceOperation returns a new UpdateServiceOperation from a given name. // The name must be that of a previously created UpdateServiceOperation, possibly from a different process. -func (c *DataprocMetastoreClient) UpdateServiceOperation(name string) *UpdateServiceOperation { +func (c *dataprocMetastoreGRPCClient) UpdateServiceOperation(name string) *UpdateServiceOperation { return &UpdateServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/metastore/apiv1beta/dataproc_metastore_client_example_test.go b/metastore/apiv1beta/dataproc_metastore_client_example_test.go index 10f2799a5fe3..41909d092e33 100644 --- a/metastore/apiv1beta/dataproc_metastore_client_example_test.go +++ b/metastore/apiv1beta/dataproc_metastore_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewDataprocMetastoreClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleDataprocMetastoreClient_ListServices() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ListServicesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleDataprocMetastoreClient_ListServices() { } func ExampleDataprocMetastoreClient_GetService() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.GetServiceRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleDataprocMetastoreClient_GetService() { } func ExampleDataprocMetastoreClient_CreateService() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.CreateServiceRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleDataprocMetastoreClient_CreateService() { } func ExampleDataprocMetastoreClient_UpdateService() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.UpdateServiceRequest{ // TODO: Fill request struct fields. @@ -132,13 +129,12 @@ func ExampleDataprocMetastoreClient_UpdateService() { } func ExampleDataprocMetastoreClient_DeleteService() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.DeleteServiceRequest{ // TODO: Fill request struct fields. @@ -155,14 +151,12 @@ func ExampleDataprocMetastoreClient_DeleteService() { } func ExampleDataprocMetastoreClient_ListMetadataImports() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ListMetadataImportsRequest{ // TODO: Fill request struct fields. @@ -182,13 +176,12 @@ func ExampleDataprocMetastoreClient_ListMetadataImports() { } func ExampleDataprocMetastoreClient_GetMetadataImport() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.GetMetadataImportRequest{ // TODO: Fill request struct fields. @@ -202,13 +195,12 @@ func ExampleDataprocMetastoreClient_GetMetadataImport() { } func ExampleDataprocMetastoreClient_CreateMetadataImport() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.CreateMetadataImportRequest{ // TODO: Fill request struct fields. @@ -227,13 +219,12 @@ func ExampleDataprocMetastoreClient_CreateMetadataImport() { } func ExampleDataprocMetastoreClient_UpdateMetadataImport() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.UpdateMetadataImportRequest{ // TODO: Fill request struct fields. @@ -252,13 +243,12 @@ func ExampleDataprocMetastoreClient_UpdateMetadataImport() { } func ExampleDataprocMetastoreClient_ExportMetadata() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ExportMetadataRequest{ // TODO: Fill request struct fields. @@ -277,13 +267,12 @@ func ExampleDataprocMetastoreClient_ExportMetadata() { } func ExampleDataprocMetastoreClient_RestoreService() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.RestoreServiceRequest{ // TODO: Fill request struct fields. @@ -302,14 +291,12 @@ func ExampleDataprocMetastoreClient_RestoreService() { } func ExampleDataprocMetastoreClient_ListBackups() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.ListBackupsRequest{ // TODO: Fill request struct fields. @@ -329,13 +316,12 @@ func ExampleDataprocMetastoreClient_ListBackups() { } func ExampleDataprocMetastoreClient_GetBackup() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.GetBackupRequest{ // TODO: Fill request struct fields. @@ -349,13 +335,12 @@ func ExampleDataprocMetastoreClient_GetBackup() { } func ExampleDataprocMetastoreClient_CreateBackup() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.CreateBackupRequest{ // TODO: Fill request struct fields. @@ -374,13 +359,12 @@ func ExampleDataprocMetastoreClient_CreateBackup() { } func ExampleDataprocMetastoreClient_DeleteBackup() { - // import metastorepb "google.golang.org/genproto/googleapis/cloud/metastore/v1beta" - ctx := context.Background() c, err := metastore.NewDataprocMetastoreClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &metastorepb.DeleteBackupRequest{ // TODO: Fill request struct fields. diff --git a/metastore/apiv1beta/doc.go b/metastore/apiv1beta/doc.go index 047793d4512c..6c1d7a1e24a3 100644 --- a/metastore/apiv1beta/doc.go +++ b/metastore/apiv1beta/doc.go @@ -20,6 +20,8 @@ // The Dataproc Metastore API is used to manage the lifecycle and // configuration of metastore services. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package metastore // import "cloud.google.com/go/metastore/apiv1beta" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/monitoring/apiv3/v2/alert_policy_client.go b/monitoring/apiv3/v2/alert_policy_client.go index f274dd314f13..27f1a72080e0 100644 --- a/monitoring/apiv3/v2/alert_policy_client.go +++ b/monitoring/apiv3/v2/alert_policy_client.go @@ -46,7 +46,7 @@ type AlertPolicyCallOptions struct { UpdateAlertPolicy []gax.CallOption } -func defaultAlertPolicyClientOptions() []option.ClientOption { +func defaultAlertPolicyGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("monitoring.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("monitoring.mtls.googleapis.com:443"), @@ -101,27 +101,110 @@ func defaultAlertPolicyCallOptions() *AlertPolicyCallOptions { } } +// internalAlertPolicyClient is an interface that defines the methods availaible from Cloud Monitoring API. +type internalAlertPolicyClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListAlertPolicies(context.Context, *monitoringpb.ListAlertPoliciesRequest, ...gax.CallOption) *AlertPolicyIterator + GetAlertPolicy(context.Context, *monitoringpb.GetAlertPolicyRequest, ...gax.CallOption) (*monitoringpb.AlertPolicy, error) + CreateAlertPolicy(context.Context, *monitoringpb.CreateAlertPolicyRequest, ...gax.CallOption) (*monitoringpb.AlertPolicy, error) + DeleteAlertPolicy(context.Context, *monitoringpb.DeleteAlertPolicyRequest, ...gax.CallOption) error + UpdateAlertPolicy(context.Context, *monitoringpb.UpdateAlertPolicyRequest, ...gax.CallOption) (*monitoringpb.AlertPolicy, error) +} + // AlertPolicyClient is a client for interacting with Cloud Monitoring API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The AlertPolicyService API is used to manage (list, create, delete, +// edit) alert policies in Stackdriver Monitoring. An alerting policy is +// a description of the conditions under which some aspect of your +// system is considered to be “unhealthy” and the ways to notify +// people or services about this state. In addition to using this API, alert +// policies can also be managed through +// Stackdriver Monitoring (at https://cloud.google.com/monitoring/docs/), +// which can be reached by clicking the “Monitoring” tab in +// Cloud Console (at https://console.cloud.google.com/). type AlertPolicyClient struct { + // The internal transport-dependent client. + internalClient internalAlertPolicyClient + + // The call options for this service. + CallOptions *AlertPolicyCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *AlertPolicyClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *AlertPolicyClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *AlertPolicyClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListAlertPolicies lists the existing alerting policies for the workspace. +func (c *AlertPolicyClient) ListAlertPolicies(ctx context.Context, req *monitoringpb.ListAlertPoliciesRequest, opts ...gax.CallOption) *AlertPolicyIterator { + return c.internalClient.ListAlertPolicies(ctx, req, opts...) +} + +// GetAlertPolicy gets a single alerting policy. +func (c *AlertPolicyClient) GetAlertPolicy(ctx context.Context, req *monitoringpb.GetAlertPolicyRequest, opts ...gax.CallOption) (*monitoringpb.AlertPolicy, error) { + return c.internalClient.GetAlertPolicy(ctx, req, opts...) +} + +// CreateAlertPolicy creates a new alerting policy. +func (c *AlertPolicyClient) CreateAlertPolicy(ctx context.Context, req *monitoringpb.CreateAlertPolicyRequest, opts ...gax.CallOption) (*monitoringpb.AlertPolicy, error) { + return c.internalClient.CreateAlertPolicy(ctx, req, opts...) +} + +// DeleteAlertPolicy deletes an alerting policy. +func (c *AlertPolicyClient) DeleteAlertPolicy(ctx context.Context, req *monitoringpb.DeleteAlertPolicyRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteAlertPolicy(ctx, req, opts...) +} + +// UpdateAlertPolicy updates an alerting policy. You can either replace the entire policy with +// a new one or replace only certain fields in the current alerting policy by +// specifying the fields to be updated via updateMask. Returns the +// updated alerting policy. +func (c *AlertPolicyClient) UpdateAlertPolicy(ctx context.Context, req *monitoringpb.UpdateAlertPolicyRequest, opts ...gax.CallOption) (*monitoringpb.AlertPolicy, error) { + return c.internalClient.UpdateAlertPolicy(ctx, req, opts...) +} + +// alertPolicyGRPCClient is a client for interacting with Cloud Monitoring API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type alertPolicyGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing AlertPolicyClient + CallOptions **AlertPolicyCallOptions + // The gRPC API client. alertPolicyClient monitoringpb.AlertPolicyServiceClient - // The call options for this service. - CallOptions *AlertPolicyCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewAlertPolicyClient creates a new alert policy service client. +// NewAlertPolicyClient creates a new alert policy service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The AlertPolicyService API is used to manage (list, create, delete, // edit) alert policies in Stackdriver Monitoring. An alerting policy is @@ -133,8 +216,7 @@ type AlertPolicyClient struct { // which can be reached by clicking the “Monitoring” tab in // Cloud Console (at https://console.cloud.google.com/). func NewAlertPolicyClient(ctx context.Context, opts ...option.ClientOption) (*AlertPolicyClient, error) { - clientOpts := defaultAlertPolicyClientOptions() - + clientOpts := defaultAlertPolicyGRPCClientOptions() if newAlertPolicyClientHook != nil { hookOpts, err := newAlertPolicyClientHook(ctx, clientHookParams{}) if err != nil { @@ -152,45 +234,47 @@ func NewAlertPolicyClient(ctx context.Context, opts ...option.ClientOption) (*Al if err != nil { return nil, err } - c := &AlertPolicyClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultAlertPolicyCallOptions(), + client := AlertPolicyClient{CallOptions: defaultAlertPolicyCallOptions()} + c := &alertPolicyGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, alertPolicyClient: monitoringpb.NewAlertPolicyServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *AlertPolicyClient) Connection() *grpc.ClientConn { +func (c *alertPolicyGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *AlertPolicyClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *AlertPolicyClient) setGoogleClientInfo(keyval ...string) { +func (c *alertPolicyGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListAlertPolicies lists the existing alerting policies for the workspace. -func (c *AlertPolicyClient) ListAlertPolicies(ctx context.Context, req *monitoringpb.ListAlertPoliciesRequest, opts ...gax.CallOption) *AlertPolicyIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *alertPolicyGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *alertPolicyGRPCClient) ListAlertPolicies(ctx context.Context, req *monitoringpb.ListAlertPoliciesRequest, opts ...gax.CallOption) *AlertPolicyIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAlertPolicies[0:len(c.CallOptions.ListAlertPolicies):len(c.CallOptions.ListAlertPolicies)], opts...) + opts = append((*c.CallOptions).ListAlertPolicies[0:len((*c.CallOptions).ListAlertPolicies):len((*c.CallOptions).ListAlertPolicies)], opts...) it := &AlertPolicyIterator{} req = proto.Clone(req).(*monitoringpb.ListAlertPoliciesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.AlertPolicy, string, error) { @@ -227,8 +311,7 @@ func (c *AlertPolicyClient) ListAlertPolicies(ctx context.Context, req *monitori return it } -// GetAlertPolicy gets a single alerting policy. -func (c *AlertPolicyClient) GetAlertPolicy(ctx context.Context, req *monitoringpb.GetAlertPolicyRequest, opts ...gax.CallOption) (*monitoringpb.AlertPolicy, error) { +func (c *alertPolicyGRPCClient) GetAlertPolicy(ctx context.Context, req *monitoringpb.GetAlertPolicyRequest, opts ...gax.CallOption) (*monitoringpb.AlertPolicy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -236,7 +319,7 @@ func (c *AlertPolicyClient) GetAlertPolicy(ctx context.Context, req *monitoringp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetAlertPolicy[0:len(c.CallOptions.GetAlertPolicy):len(c.CallOptions.GetAlertPolicy)], opts...) + opts = append((*c.CallOptions).GetAlertPolicy[0:len((*c.CallOptions).GetAlertPolicy):len((*c.CallOptions).GetAlertPolicy)], opts...) var resp *monitoringpb.AlertPolicy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -249,8 +332,7 @@ func (c *AlertPolicyClient) GetAlertPolicy(ctx context.Context, req *monitoringp return resp, nil } -// CreateAlertPolicy creates a new alerting policy. -func (c *AlertPolicyClient) CreateAlertPolicy(ctx context.Context, req *monitoringpb.CreateAlertPolicyRequest, opts ...gax.CallOption) (*monitoringpb.AlertPolicy, error) { +func (c *alertPolicyGRPCClient) CreateAlertPolicy(ctx context.Context, req *monitoringpb.CreateAlertPolicyRequest, opts ...gax.CallOption) (*monitoringpb.AlertPolicy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -258,7 +340,7 @@ func (c *AlertPolicyClient) CreateAlertPolicy(ctx context.Context, req *monitori } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateAlertPolicy[0:len(c.CallOptions.CreateAlertPolicy):len(c.CallOptions.CreateAlertPolicy)], opts...) + opts = append((*c.CallOptions).CreateAlertPolicy[0:len((*c.CallOptions).CreateAlertPolicy):len((*c.CallOptions).CreateAlertPolicy)], opts...) var resp *monitoringpb.AlertPolicy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -271,8 +353,7 @@ func (c *AlertPolicyClient) CreateAlertPolicy(ctx context.Context, req *monitori return resp, nil } -// DeleteAlertPolicy deletes an alerting policy. -func (c *AlertPolicyClient) DeleteAlertPolicy(ctx context.Context, req *monitoringpb.DeleteAlertPolicyRequest, opts ...gax.CallOption) error { +func (c *alertPolicyGRPCClient) DeleteAlertPolicy(ctx context.Context, req *monitoringpb.DeleteAlertPolicyRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -280,7 +361,7 @@ func (c *AlertPolicyClient) DeleteAlertPolicy(ctx context.Context, req *monitori } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteAlertPolicy[0:len(c.CallOptions.DeleteAlertPolicy):len(c.CallOptions.DeleteAlertPolicy)], opts...) + opts = append((*c.CallOptions).DeleteAlertPolicy[0:len((*c.CallOptions).DeleteAlertPolicy):len((*c.CallOptions).DeleteAlertPolicy)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.alertPolicyClient.DeleteAlertPolicy(ctx, req, settings.GRPC...) @@ -289,11 +370,7 @@ func (c *AlertPolicyClient) DeleteAlertPolicy(ctx context.Context, req *monitori return err } -// UpdateAlertPolicy updates an alerting policy. You can either replace the entire policy with -// a new one or replace only certain fields in the current alerting policy by -// specifying the fields to be updated via updateMask. Returns the -// updated alerting policy. -func (c *AlertPolicyClient) UpdateAlertPolicy(ctx context.Context, req *monitoringpb.UpdateAlertPolicyRequest, opts ...gax.CallOption) (*monitoringpb.AlertPolicy, error) { +func (c *alertPolicyGRPCClient) UpdateAlertPolicy(ctx context.Context, req *monitoringpb.UpdateAlertPolicyRequest, opts ...gax.CallOption) (*monitoringpb.AlertPolicy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -301,7 +378,7 @@ func (c *AlertPolicyClient) UpdateAlertPolicy(ctx context.Context, req *monitori } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "alert_policy.name", url.QueryEscape(req.GetAlertPolicy().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateAlertPolicy[0:len(c.CallOptions.UpdateAlertPolicy):len(c.CallOptions.UpdateAlertPolicy)], opts...) + opts = append((*c.CallOptions).UpdateAlertPolicy[0:len((*c.CallOptions).UpdateAlertPolicy):len((*c.CallOptions).UpdateAlertPolicy)], opts...) var resp *monitoringpb.AlertPolicy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/monitoring/apiv3/v2/alert_policy_client_example_test.go b/monitoring/apiv3/v2/alert_policy_client_example_test.go index c847723acc35..2472ae6e6719 100644 --- a/monitoring/apiv3/v2/alert_policy_client_example_test.go +++ b/monitoring/apiv3/v2/alert_policy_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewAlertPolicyClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleAlertPolicyClient_ListAlertPolicies() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewAlertPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListAlertPoliciesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleAlertPolicyClient_ListAlertPolicies() { } func ExampleAlertPolicyClient_GetAlertPolicy() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewAlertPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetAlertPolicyRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleAlertPolicyClient_GetAlertPolicy() { } func ExampleAlertPolicyClient_CreateAlertPolicy() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewAlertPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.CreateAlertPolicyRequest{ // TODO: Fill request struct fields. @@ -107,6 +105,7 @@ func ExampleAlertPolicyClient_DeleteAlertPolicy() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.DeleteAlertPolicyRequest{ // TODO: Fill request struct fields. @@ -118,13 +117,12 @@ func ExampleAlertPolicyClient_DeleteAlertPolicy() { } func ExampleAlertPolicyClient_UpdateAlertPolicy() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewAlertPolicyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.UpdateAlertPolicyRequest{ // TODO: Fill request struct fields. diff --git a/monitoring/apiv3/v2/doc.go b/monitoring/apiv3/v2/doc.go index 8de974d1daf0..584f6afc513c 100644 --- a/monitoring/apiv3/v2/doc.go +++ b/monitoring/apiv3/v2/doc.go @@ -21,8 +21,8 @@ // be associated with a Workspace, with a few exceptions as noted on the // individual method pages. The table entries below are presented in // alphabetical order, not in order of common use. For explanations of the -// concepts found in the table entries, read the [Cloud Monitoring -// documentation](/monitoring/docs). +// concepts found in the table entries, read the Cloud Monitoring +// documentation (at /monitoring/docs). // // Use of Context // @@ -33,7 +33,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package monitoring // import "cloud.google.com/go/monitoring/apiv3/v2" import ( @@ -53,7 +53,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/monitoring/apiv3/v2/group_client.go b/monitoring/apiv3/v2/group_client.go index b3066b4186fa..15761d4cf8f7 100644 --- a/monitoring/apiv3/v2/group_client.go +++ b/monitoring/apiv3/v2/group_client.go @@ -48,7 +48,7 @@ type GroupCallOptions struct { ListGroupMembers []gax.CallOption } -func defaultGroupClientOptions() []option.ClientOption { +func defaultGroupGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("monitoring.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("monitoring.mtls.googleapis.com:443"), @@ -126,27 +126,117 @@ func defaultGroupCallOptions() *GroupCallOptions { } } +// internalGroupClient is an interface that defines the methods availaible from Cloud Monitoring API. +type internalGroupClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListGroups(context.Context, *monitoringpb.ListGroupsRequest, ...gax.CallOption) *GroupIterator + GetGroup(context.Context, *monitoringpb.GetGroupRequest, ...gax.CallOption) (*monitoringpb.Group, error) + CreateGroup(context.Context, *monitoringpb.CreateGroupRequest, ...gax.CallOption) (*monitoringpb.Group, error) + UpdateGroup(context.Context, *monitoringpb.UpdateGroupRequest, ...gax.CallOption) (*monitoringpb.Group, error) + DeleteGroup(context.Context, *monitoringpb.DeleteGroupRequest, ...gax.CallOption) error + ListGroupMembers(context.Context, *monitoringpb.ListGroupMembersRequest, ...gax.CallOption) *MonitoredResourceIterator +} + // GroupClient is a client for interacting with Cloud Monitoring API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The Group API lets you inspect and manage your +// groups (at #google.monitoring.v3.Group). +// +// A group is a named filter that is used to identify +// a collection of monitored resources. Groups are typically used to +// mirror the physical and/or logical topology of the environment. +// Because group membership is computed dynamically, monitored +// resources that are started in the future are automatically placed +// in matching groups. By using a group to name monitored resources in, +// for example, an alert policy, the target of that alert policy is +// updated automatically as monitored resources are added and removed +// from the infrastructure. type GroupClient struct { + // The internal transport-dependent client. + internalClient internalGroupClient + + // The call options for this service. + CallOptions *GroupCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *GroupClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *GroupClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *GroupClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListGroups lists the existing groups. +func (c *GroupClient) ListGroups(ctx context.Context, req *monitoringpb.ListGroupsRequest, opts ...gax.CallOption) *GroupIterator { + return c.internalClient.ListGroups(ctx, req, opts...) +} + +// GetGroup gets a single group. +func (c *GroupClient) GetGroup(ctx context.Context, req *monitoringpb.GetGroupRequest, opts ...gax.CallOption) (*monitoringpb.Group, error) { + return c.internalClient.GetGroup(ctx, req, opts...) +} + +// CreateGroup creates a new group. +func (c *GroupClient) CreateGroup(ctx context.Context, req *monitoringpb.CreateGroupRequest, opts ...gax.CallOption) (*monitoringpb.Group, error) { + return c.internalClient.CreateGroup(ctx, req, opts...) +} + +// UpdateGroup updates an existing group. +// You can change any group attributes except name. +func (c *GroupClient) UpdateGroup(ctx context.Context, req *monitoringpb.UpdateGroupRequest, opts ...gax.CallOption) (*monitoringpb.Group, error) { + return c.internalClient.UpdateGroup(ctx, req, opts...) +} + +// DeleteGroup deletes an existing group. +func (c *GroupClient) DeleteGroup(ctx context.Context, req *monitoringpb.DeleteGroupRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteGroup(ctx, req, opts...) +} + +// ListGroupMembers lists the monitored resources that are members of a group. +func (c *GroupClient) ListGroupMembers(ctx context.Context, req *monitoringpb.ListGroupMembersRequest, opts ...gax.CallOption) *MonitoredResourceIterator { + return c.internalClient.ListGroupMembers(ctx, req, opts...) +} + +// groupGRPCClient is a client for interacting with Cloud Monitoring API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type groupGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing GroupClient + CallOptions **GroupCallOptions + // The gRPC API client. groupClient monitoringpb.GroupServiceClient - // The call options for this service. - CallOptions *GroupCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewGroupClient creates a new group service client. +// NewGroupClient creates a new group service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The Group API lets you inspect and manage your // groups (at #google.monitoring.v3.Group). @@ -161,8 +251,7 @@ type GroupClient struct { // updated automatically as monitored resources are added and removed // from the infrastructure. func NewGroupClient(ctx context.Context, opts ...option.ClientOption) (*GroupClient, error) { - clientOpts := defaultGroupClientOptions() - + clientOpts := defaultGroupGRPCClientOptions() if newGroupClientHook != nil { hookOpts, err := newGroupClientHook(ctx, clientHookParams{}) if err != nil { @@ -180,45 +269,47 @@ func NewGroupClient(ctx context.Context, opts ...option.ClientOption) (*GroupCli if err != nil { return nil, err } - c := &GroupClient{ + client := GroupClient{CallOptions: defaultGroupCallOptions()} + + c := &groupGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultGroupCallOptions(), - - groupClient: monitoringpb.NewGroupServiceClient(connPool), + groupClient: monitoringpb.NewGroupServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *GroupClient) Connection() *grpc.ClientConn { +func (c *groupGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *GroupClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *GroupClient) setGoogleClientInfo(keyval ...string) { +func (c *groupGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListGroups lists the existing groups. -func (c *GroupClient) ListGroups(ctx context.Context, req *monitoringpb.ListGroupsRequest, opts ...gax.CallOption) *GroupIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *groupGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *groupGRPCClient) ListGroups(ctx context.Context, req *monitoringpb.ListGroupsRequest, opts ...gax.CallOption) *GroupIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListGroups[0:len(c.CallOptions.ListGroups):len(c.CallOptions.ListGroups)], opts...) + opts = append((*c.CallOptions).ListGroups[0:len((*c.CallOptions).ListGroups):len((*c.CallOptions).ListGroups)], opts...) it := &GroupIterator{} req = proto.Clone(req).(*monitoringpb.ListGroupsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.Group, string, error) { @@ -255,8 +346,7 @@ func (c *GroupClient) ListGroups(ctx context.Context, req *monitoringpb.ListGrou return it } -// GetGroup gets a single group. -func (c *GroupClient) GetGroup(ctx context.Context, req *monitoringpb.GetGroupRequest, opts ...gax.CallOption) (*monitoringpb.Group, error) { +func (c *groupGRPCClient) GetGroup(ctx context.Context, req *monitoringpb.GetGroupRequest, opts ...gax.CallOption) (*monitoringpb.Group, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -264,7 +354,7 @@ func (c *GroupClient) GetGroup(ctx context.Context, req *monitoringpb.GetGroupRe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetGroup[0:len(c.CallOptions.GetGroup):len(c.CallOptions.GetGroup)], opts...) + opts = append((*c.CallOptions).GetGroup[0:len((*c.CallOptions).GetGroup):len((*c.CallOptions).GetGroup)], opts...) var resp *monitoringpb.Group err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -277,8 +367,7 @@ func (c *GroupClient) GetGroup(ctx context.Context, req *monitoringpb.GetGroupRe return resp, nil } -// CreateGroup creates a new group. -func (c *GroupClient) CreateGroup(ctx context.Context, req *monitoringpb.CreateGroupRequest, opts ...gax.CallOption) (*monitoringpb.Group, error) { +func (c *groupGRPCClient) CreateGroup(ctx context.Context, req *monitoringpb.CreateGroupRequest, opts ...gax.CallOption) (*monitoringpb.Group, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -286,7 +375,7 @@ func (c *GroupClient) CreateGroup(ctx context.Context, req *monitoringpb.CreateG } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateGroup[0:len(c.CallOptions.CreateGroup):len(c.CallOptions.CreateGroup)], opts...) + opts = append((*c.CallOptions).CreateGroup[0:len((*c.CallOptions).CreateGroup):len((*c.CallOptions).CreateGroup)], opts...) var resp *monitoringpb.Group err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -299,9 +388,7 @@ func (c *GroupClient) CreateGroup(ctx context.Context, req *monitoringpb.CreateG return resp, nil } -// UpdateGroup updates an existing group. -// You can change any group attributes except name. -func (c *GroupClient) UpdateGroup(ctx context.Context, req *monitoringpb.UpdateGroupRequest, opts ...gax.CallOption) (*monitoringpb.Group, error) { +func (c *groupGRPCClient) UpdateGroup(ctx context.Context, req *monitoringpb.UpdateGroupRequest, opts ...gax.CallOption) (*monitoringpb.Group, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -309,7 +396,7 @@ func (c *GroupClient) UpdateGroup(ctx context.Context, req *monitoringpb.UpdateG } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "group.name", url.QueryEscape(req.GetGroup().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateGroup[0:len(c.CallOptions.UpdateGroup):len(c.CallOptions.UpdateGroup)], opts...) + opts = append((*c.CallOptions).UpdateGroup[0:len((*c.CallOptions).UpdateGroup):len((*c.CallOptions).UpdateGroup)], opts...) var resp *monitoringpb.Group err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -322,8 +409,7 @@ func (c *GroupClient) UpdateGroup(ctx context.Context, req *monitoringpb.UpdateG return resp, nil } -// DeleteGroup deletes an existing group. -func (c *GroupClient) DeleteGroup(ctx context.Context, req *monitoringpb.DeleteGroupRequest, opts ...gax.CallOption) error { +func (c *groupGRPCClient) DeleteGroup(ctx context.Context, req *monitoringpb.DeleteGroupRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -331,7 +417,7 @@ func (c *GroupClient) DeleteGroup(ctx context.Context, req *monitoringpb.DeleteG } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteGroup[0:len(c.CallOptions.DeleteGroup):len(c.CallOptions.DeleteGroup)], opts...) + opts = append((*c.CallOptions).DeleteGroup[0:len((*c.CallOptions).DeleteGroup):len((*c.CallOptions).DeleteGroup)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.groupClient.DeleteGroup(ctx, req, settings.GRPC...) @@ -340,11 +426,10 @@ func (c *GroupClient) DeleteGroup(ctx context.Context, req *monitoringpb.DeleteG return err } -// ListGroupMembers lists the monitored resources that are members of a group. -func (c *GroupClient) ListGroupMembers(ctx context.Context, req *monitoringpb.ListGroupMembersRequest, opts ...gax.CallOption) *MonitoredResourceIterator { +func (c *groupGRPCClient) ListGroupMembers(ctx context.Context, req *monitoringpb.ListGroupMembersRequest, opts ...gax.CallOption) *MonitoredResourceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListGroupMembers[0:len(c.CallOptions.ListGroupMembers):len(c.CallOptions.ListGroupMembers)], opts...) + opts = append((*c.CallOptions).ListGroupMembers[0:len((*c.CallOptions).ListGroupMembers):len((*c.CallOptions).ListGroupMembers)], opts...) it := &MonitoredResourceIterator{} req = proto.Clone(req).(*monitoringpb.ListGroupMembersRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoredrespb.MonitoredResource, string, error) { diff --git a/monitoring/apiv3/v2/group_client_example_test.go b/monitoring/apiv3/v2/group_client_example_test.go index 6d93f4467d57..b48a4f5bb0f9 100644 --- a/monitoring/apiv3/v2/group_client_example_test.go +++ b/monitoring/apiv3/v2/group_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewGroupClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleGroupClient_ListGroups() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewGroupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListGroupsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleGroupClient_ListGroups() { } func ExampleGroupClient_GetGroup() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewGroupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetGroupRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleGroupClient_GetGroup() { } func ExampleGroupClient_CreateGroup() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewGroupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.CreateGroupRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleGroupClient_CreateGroup() { } func ExampleGroupClient_UpdateGroup() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewGroupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.UpdateGroupRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleGroupClient_DeleteGroup() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.DeleteGroupRequest{ // TODO: Fill request struct fields. @@ -138,14 +136,12 @@ func ExampleGroupClient_DeleteGroup() { } func ExampleGroupClient_ListGroupMembers() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewGroupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListGroupMembersRequest{ // TODO: Fill request struct fields. diff --git a/monitoring/apiv3/v2/metric_client.go b/monitoring/apiv3/v2/metric_client.go index 44af4fafc374..79227eae0c9e 100644 --- a/monitoring/apiv3/v2/metric_client.go +++ b/monitoring/apiv3/v2/metric_client.go @@ -51,7 +51,7 @@ type MetricCallOptions struct { CreateTimeSeries []gax.CallOption } -func defaultMetricClientOptions() []option.ClientOption { +func defaultMetricGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("monitoring.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("monitoring.mtls.googleapis.com:443"), @@ -142,33 +142,130 @@ func defaultMetricCallOptions() *MetricCallOptions { } } +// internalMetricClient is an interface that defines the methods availaible from Cloud Monitoring API. +type internalMetricClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListMonitoredResourceDescriptors(context.Context, *monitoringpb.ListMonitoredResourceDescriptorsRequest, ...gax.CallOption) *MonitoredResourceDescriptorIterator + GetMonitoredResourceDescriptor(context.Context, *monitoringpb.GetMonitoredResourceDescriptorRequest, ...gax.CallOption) (*monitoredrespb.MonitoredResourceDescriptor, error) + ListMetricDescriptors(context.Context, *monitoringpb.ListMetricDescriptorsRequest, ...gax.CallOption) *MetricDescriptorIterator + GetMetricDescriptor(context.Context, *monitoringpb.GetMetricDescriptorRequest, ...gax.CallOption) (*metricpb.MetricDescriptor, error) + CreateMetricDescriptor(context.Context, *monitoringpb.CreateMetricDescriptorRequest, ...gax.CallOption) (*metricpb.MetricDescriptor, error) + DeleteMetricDescriptor(context.Context, *monitoringpb.DeleteMetricDescriptorRequest, ...gax.CallOption) error + ListTimeSeries(context.Context, *monitoringpb.ListTimeSeriesRequest, ...gax.CallOption) *TimeSeriesIterator + CreateTimeSeries(context.Context, *monitoringpb.CreateTimeSeriesRequest, ...gax.CallOption) error +} + // MetricClient is a client for interacting with Cloud Monitoring API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Manages metric descriptors, monitored resource descriptors, and +// time series data. type MetricClient struct { + // The internal transport-dependent client. + internalClient internalMetricClient + + // The call options for this service. + CallOptions *MetricCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *MetricClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *MetricClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *MetricClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListMonitoredResourceDescriptors lists monitored resource descriptors that match a filter. This method does not require a Workspace. +func (c *MetricClient) ListMonitoredResourceDescriptors(ctx context.Context, req *monitoringpb.ListMonitoredResourceDescriptorsRequest, opts ...gax.CallOption) *MonitoredResourceDescriptorIterator { + return c.internalClient.ListMonitoredResourceDescriptors(ctx, req, opts...) +} + +// GetMonitoredResourceDescriptor gets a single monitored resource descriptor. This method does not require a Workspace. +func (c *MetricClient) GetMonitoredResourceDescriptor(ctx context.Context, req *monitoringpb.GetMonitoredResourceDescriptorRequest, opts ...gax.CallOption) (*monitoredrespb.MonitoredResourceDescriptor, error) { + return c.internalClient.GetMonitoredResourceDescriptor(ctx, req, opts...) +} + +// ListMetricDescriptors lists metric descriptors that match a filter. This method does not require a Workspace. +func (c *MetricClient) ListMetricDescriptors(ctx context.Context, req *monitoringpb.ListMetricDescriptorsRequest, opts ...gax.CallOption) *MetricDescriptorIterator { + return c.internalClient.ListMetricDescriptors(ctx, req, opts...) +} + +// GetMetricDescriptor gets a single metric descriptor. This method does not require a Workspace. +func (c *MetricClient) GetMetricDescriptor(ctx context.Context, req *monitoringpb.GetMetricDescriptorRequest, opts ...gax.CallOption) (*metricpb.MetricDescriptor, error) { + return c.internalClient.GetMetricDescriptor(ctx, req, opts...) +} + +// CreateMetricDescriptor creates a new metric descriptor. +// User-created metric descriptors define +// custom metrics (at https://cloud.google.com/monitoring/custom-metrics). +func (c *MetricClient) CreateMetricDescriptor(ctx context.Context, req *monitoringpb.CreateMetricDescriptorRequest, opts ...gax.CallOption) (*metricpb.MetricDescriptor, error) { + return c.internalClient.CreateMetricDescriptor(ctx, req, opts...) +} + +// DeleteMetricDescriptor deletes a metric descriptor. Only user-created +// custom metrics (at https://cloud.google.com/monitoring/custom-metrics) can be +// deleted. +func (c *MetricClient) DeleteMetricDescriptor(ctx context.Context, req *monitoringpb.DeleteMetricDescriptorRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteMetricDescriptor(ctx, req, opts...) +} + +// ListTimeSeries lists time series that match a filter. This method does not require a Workspace. +func (c *MetricClient) ListTimeSeries(ctx context.Context, req *monitoringpb.ListTimeSeriesRequest, opts ...gax.CallOption) *TimeSeriesIterator { + return c.internalClient.ListTimeSeries(ctx, req, opts...) +} + +// CreateTimeSeries creates or adds data to one or more time series. +// The response is empty if all time series in the request were written. +// If any time series could not be written, a corresponding failure message is +// included in the error response. +func (c *MetricClient) CreateTimeSeries(ctx context.Context, req *monitoringpb.CreateTimeSeriesRequest, opts ...gax.CallOption) error { + return c.internalClient.CreateTimeSeries(ctx, req, opts...) +} + +// metricGRPCClient is a client for interacting with Cloud Monitoring API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type metricGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing MetricClient + CallOptions **MetricCallOptions + // The gRPC API client. metricClient monitoringpb.MetricServiceClient - // The call options for this service. - CallOptions *MetricCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewMetricClient creates a new metric service client. +// NewMetricClient creates a new metric service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Manages metric descriptors, monitored resource descriptors, and // time series data. func NewMetricClient(ctx context.Context, opts ...option.ClientOption) (*MetricClient, error) { - clientOpts := defaultMetricClientOptions() - + clientOpts := defaultMetricGRPCClientOptions() if newMetricClientHook != nil { hookOpts, err := newMetricClientHook(ctx, clientHookParams{}) if err != nil { @@ -186,45 +283,47 @@ func NewMetricClient(ctx context.Context, opts ...option.ClientOption) (*MetricC if err != nil { return nil, err } - c := &MetricClient{ + client := MetricClient{CallOptions: defaultMetricCallOptions()} + + c := &metricGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultMetricCallOptions(), - - metricClient: monitoringpb.NewMetricServiceClient(connPool), + metricClient: monitoringpb.NewMetricServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *MetricClient) Connection() *grpc.ClientConn { +func (c *metricGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *MetricClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *MetricClient) setGoogleClientInfo(keyval ...string) { +func (c *metricGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListMonitoredResourceDescriptors lists monitored resource descriptors that match a filter. This method does not require a Workspace. -func (c *MetricClient) ListMonitoredResourceDescriptors(ctx context.Context, req *monitoringpb.ListMonitoredResourceDescriptorsRequest, opts ...gax.CallOption) *MonitoredResourceDescriptorIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *metricGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *metricGRPCClient) ListMonitoredResourceDescriptors(ctx context.Context, req *monitoringpb.ListMonitoredResourceDescriptorsRequest, opts ...gax.CallOption) *MonitoredResourceDescriptorIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListMonitoredResourceDescriptors[0:len(c.CallOptions.ListMonitoredResourceDescriptors):len(c.CallOptions.ListMonitoredResourceDescriptors)], opts...) + opts = append((*c.CallOptions).ListMonitoredResourceDescriptors[0:len((*c.CallOptions).ListMonitoredResourceDescriptors):len((*c.CallOptions).ListMonitoredResourceDescriptors)], opts...) it := &MonitoredResourceDescriptorIterator{} req = proto.Clone(req).(*monitoringpb.ListMonitoredResourceDescriptorsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoredrespb.MonitoredResourceDescriptor, string, error) { @@ -261,8 +360,7 @@ func (c *MetricClient) ListMonitoredResourceDescriptors(ctx context.Context, req return it } -// GetMonitoredResourceDescriptor gets a single monitored resource descriptor. This method does not require a Workspace. -func (c *MetricClient) GetMonitoredResourceDescriptor(ctx context.Context, req *monitoringpb.GetMonitoredResourceDescriptorRequest, opts ...gax.CallOption) (*monitoredrespb.MonitoredResourceDescriptor, error) { +func (c *metricGRPCClient) GetMonitoredResourceDescriptor(ctx context.Context, req *monitoringpb.GetMonitoredResourceDescriptorRequest, opts ...gax.CallOption) (*monitoredrespb.MonitoredResourceDescriptor, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -270,7 +368,7 @@ func (c *MetricClient) GetMonitoredResourceDescriptor(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetMonitoredResourceDescriptor[0:len(c.CallOptions.GetMonitoredResourceDescriptor):len(c.CallOptions.GetMonitoredResourceDescriptor)], opts...) + opts = append((*c.CallOptions).GetMonitoredResourceDescriptor[0:len((*c.CallOptions).GetMonitoredResourceDescriptor):len((*c.CallOptions).GetMonitoredResourceDescriptor)], opts...) var resp *monitoredrespb.MonitoredResourceDescriptor err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -283,11 +381,10 @@ func (c *MetricClient) GetMonitoredResourceDescriptor(ctx context.Context, req * return resp, nil } -// ListMetricDescriptors lists metric descriptors that match a filter. This method does not require a Workspace. -func (c *MetricClient) ListMetricDescriptors(ctx context.Context, req *monitoringpb.ListMetricDescriptorsRequest, opts ...gax.CallOption) *MetricDescriptorIterator { +func (c *metricGRPCClient) ListMetricDescriptors(ctx context.Context, req *monitoringpb.ListMetricDescriptorsRequest, opts ...gax.CallOption) *MetricDescriptorIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListMetricDescriptors[0:len(c.CallOptions.ListMetricDescriptors):len(c.CallOptions.ListMetricDescriptors)], opts...) + opts = append((*c.CallOptions).ListMetricDescriptors[0:len((*c.CallOptions).ListMetricDescriptors):len((*c.CallOptions).ListMetricDescriptors)], opts...) it := &MetricDescriptorIterator{} req = proto.Clone(req).(*monitoringpb.ListMetricDescriptorsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*metricpb.MetricDescriptor, string, error) { @@ -324,8 +421,7 @@ func (c *MetricClient) ListMetricDescriptors(ctx context.Context, req *monitorin return it } -// GetMetricDescriptor gets a single metric descriptor. This method does not require a Workspace. -func (c *MetricClient) GetMetricDescriptor(ctx context.Context, req *monitoringpb.GetMetricDescriptorRequest, opts ...gax.CallOption) (*metricpb.MetricDescriptor, error) { +func (c *metricGRPCClient) GetMetricDescriptor(ctx context.Context, req *monitoringpb.GetMetricDescriptorRequest, opts ...gax.CallOption) (*metricpb.MetricDescriptor, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -333,7 +429,7 @@ func (c *MetricClient) GetMetricDescriptor(ctx context.Context, req *monitoringp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetMetricDescriptor[0:len(c.CallOptions.GetMetricDescriptor):len(c.CallOptions.GetMetricDescriptor)], opts...) + opts = append((*c.CallOptions).GetMetricDescriptor[0:len((*c.CallOptions).GetMetricDescriptor):len((*c.CallOptions).GetMetricDescriptor)], opts...) var resp *metricpb.MetricDescriptor err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -346,10 +442,7 @@ func (c *MetricClient) GetMetricDescriptor(ctx context.Context, req *monitoringp return resp, nil } -// CreateMetricDescriptor creates a new metric descriptor. -// User-created metric descriptors define -// custom metrics (at https://cloud.google.com/monitoring/custom-metrics). -func (c *MetricClient) CreateMetricDescriptor(ctx context.Context, req *monitoringpb.CreateMetricDescriptorRequest, opts ...gax.CallOption) (*metricpb.MetricDescriptor, error) { +func (c *metricGRPCClient) CreateMetricDescriptor(ctx context.Context, req *monitoringpb.CreateMetricDescriptorRequest, opts ...gax.CallOption) (*metricpb.MetricDescriptor, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 12000*time.Millisecond) defer cancel() @@ -357,7 +450,7 @@ func (c *MetricClient) CreateMetricDescriptor(ctx context.Context, req *monitori } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateMetricDescriptor[0:len(c.CallOptions.CreateMetricDescriptor):len(c.CallOptions.CreateMetricDescriptor)], opts...) + opts = append((*c.CallOptions).CreateMetricDescriptor[0:len((*c.CallOptions).CreateMetricDescriptor):len((*c.CallOptions).CreateMetricDescriptor)], opts...) var resp *metricpb.MetricDescriptor err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -370,10 +463,7 @@ func (c *MetricClient) CreateMetricDescriptor(ctx context.Context, req *monitori return resp, nil } -// DeleteMetricDescriptor deletes a metric descriptor. Only user-created -// custom metrics (at https://cloud.google.com/monitoring/custom-metrics) can be -// deleted. -func (c *MetricClient) DeleteMetricDescriptor(ctx context.Context, req *monitoringpb.DeleteMetricDescriptorRequest, opts ...gax.CallOption) error { +func (c *metricGRPCClient) DeleteMetricDescriptor(ctx context.Context, req *monitoringpb.DeleteMetricDescriptorRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -381,7 +471,7 @@ func (c *MetricClient) DeleteMetricDescriptor(ctx context.Context, req *monitori } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteMetricDescriptor[0:len(c.CallOptions.DeleteMetricDescriptor):len(c.CallOptions.DeleteMetricDescriptor)], opts...) + opts = append((*c.CallOptions).DeleteMetricDescriptor[0:len((*c.CallOptions).DeleteMetricDescriptor):len((*c.CallOptions).DeleteMetricDescriptor)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.metricClient.DeleteMetricDescriptor(ctx, req, settings.GRPC...) @@ -390,11 +480,10 @@ func (c *MetricClient) DeleteMetricDescriptor(ctx context.Context, req *monitori return err } -// ListTimeSeries lists time series that match a filter. This method does not require a Workspace. -func (c *MetricClient) ListTimeSeries(ctx context.Context, req *monitoringpb.ListTimeSeriesRequest, opts ...gax.CallOption) *TimeSeriesIterator { +func (c *metricGRPCClient) ListTimeSeries(ctx context.Context, req *monitoringpb.ListTimeSeriesRequest, opts ...gax.CallOption) *TimeSeriesIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTimeSeries[0:len(c.CallOptions.ListTimeSeries):len(c.CallOptions.ListTimeSeries)], opts...) + opts = append((*c.CallOptions).ListTimeSeries[0:len((*c.CallOptions).ListTimeSeries):len((*c.CallOptions).ListTimeSeries)], opts...) it := &TimeSeriesIterator{} req = proto.Clone(req).(*monitoringpb.ListTimeSeriesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.TimeSeries, string, error) { @@ -431,11 +520,7 @@ func (c *MetricClient) ListTimeSeries(ctx context.Context, req *monitoringpb.Lis return it } -// CreateTimeSeries creates or adds data to one or more time series. -// The response is empty if all time series in the request were written. -// If any time series could not be written, a corresponding failure message is -// included in the error response. -func (c *MetricClient) CreateTimeSeries(ctx context.Context, req *monitoringpb.CreateTimeSeriesRequest, opts ...gax.CallOption) error { +func (c *metricGRPCClient) CreateTimeSeries(ctx context.Context, req *monitoringpb.CreateTimeSeriesRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 12000*time.Millisecond) defer cancel() @@ -443,7 +528,7 @@ func (c *MetricClient) CreateTimeSeries(ctx context.Context, req *monitoringpb.C } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTimeSeries[0:len(c.CallOptions.CreateTimeSeries):len(c.CallOptions.CreateTimeSeries)], opts...) + opts = append((*c.CallOptions).CreateTimeSeries[0:len((*c.CallOptions).CreateTimeSeries):len((*c.CallOptions).CreateTimeSeries)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.metricClient.CreateTimeSeries(ctx, req, settings.GRPC...) diff --git a/monitoring/apiv3/v2/metric_client_example_test.go b/monitoring/apiv3/v2/metric_client_example_test.go index 5b8111d64b7e..b0a995175b5e 100644 --- a/monitoring/apiv3/v2/metric_client_example_test.go +++ b/monitoring/apiv3/v2/metric_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewMetricClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleMetricClient_ListMonitoredResourceDescriptors() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewMetricClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListMonitoredResourceDescriptorsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleMetricClient_ListMonitoredResourceDescriptors() { } func ExampleMetricClient_GetMonitoredResourceDescriptor() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewMetricClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetMonitoredResourceDescriptorRequest{ // TODO: Fill request struct fields. @@ -82,14 +81,12 @@ func ExampleMetricClient_GetMonitoredResourceDescriptor() { } func ExampleMetricClient_ListMetricDescriptors() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewMetricClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListMetricDescriptorsRequest{ // TODO: Fill request struct fields. @@ -109,13 +106,12 @@ func ExampleMetricClient_ListMetricDescriptors() { } func ExampleMetricClient_GetMetricDescriptor() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewMetricClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetMetricDescriptorRequest{ // TODO: Fill request struct fields. @@ -129,13 +125,12 @@ func ExampleMetricClient_GetMetricDescriptor() { } func ExampleMetricClient_CreateMetricDescriptor() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewMetricClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.CreateMetricDescriptorRequest{ // TODO: Fill request struct fields. @@ -154,6 +149,7 @@ func ExampleMetricClient_DeleteMetricDescriptor() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.DeleteMetricDescriptorRequest{ // TODO: Fill request struct fields. @@ -165,14 +161,12 @@ func ExampleMetricClient_DeleteMetricDescriptor() { } func ExampleMetricClient_ListTimeSeries() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewMetricClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListTimeSeriesRequest{ // TODO: Fill request struct fields. @@ -197,6 +191,7 @@ func ExampleMetricClient_CreateTimeSeries() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.CreateTimeSeriesRequest{ // TODO: Fill request struct fields. diff --git a/monitoring/apiv3/v2/notification_channel_client.go b/monitoring/apiv3/v2/notification_channel_client.go index 41554bd2f60c..3dbff222ea10 100644 --- a/monitoring/apiv3/v2/notification_channel_client.go +++ b/monitoring/apiv3/v2/notification_channel_client.go @@ -51,7 +51,7 @@ type NotificationChannelCallOptions struct { VerifyNotificationChannel []gax.CallOption } -func defaultNotificationChannelClientOptions() []option.ClientOption { +func defaultNotificationChannelGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("monitoring.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("monitoring.mtls.googleapis.com:443"), @@ -155,33 +155,166 @@ func defaultNotificationChannelCallOptions() *NotificationChannelCallOptions { } } +// internalNotificationChannelClient is an interface that defines the methods availaible from Cloud Monitoring API. +type internalNotificationChannelClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListNotificationChannelDescriptors(context.Context, *monitoringpb.ListNotificationChannelDescriptorsRequest, ...gax.CallOption) *NotificationChannelDescriptorIterator + GetNotificationChannelDescriptor(context.Context, *monitoringpb.GetNotificationChannelDescriptorRequest, ...gax.CallOption) (*monitoringpb.NotificationChannelDescriptor, error) + ListNotificationChannels(context.Context, *monitoringpb.ListNotificationChannelsRequest, ...gax.CallOption) *NotificationChannelIterator + GetNotificationChannel(context.Context, *monitoringpb.GetNotificationChannelRequest, ...gax.CallOption) (*monitoringpb.NotificationChannel, error) + CreateNotificationChannel(context.Context, *monitoringpb.CreateNotificationChannelRequest, ...gax.CallOption) (*monitoringpb.NotificationChannel, error) + UpdateNotificationChannel(context.Context, *monitoringpb.UpdateNotificationChannelRequest, ...gax.CallOption) (*monitoringpb.NotificationChannel, error) + DeleteNotificationChannel(context.Context, *monitoringpb.DeleteNotificationChannelRequest, ...gax.CallOption) error + SendNotificationChannelVerificationCode(context.Context, *monitoringpb.SendNotificationChannelVerificationCodeRequest, ...gax.CallOption) error + GetNotificationChannelVerificationCode(context.Context, *monitoringpb.GetNotificationChannelVerificationCodeRequest, ...gax.CallOption) (*monitoringpb.GetNotificationChannelVerificationCodeResponse, error) + VerifyNotificationChannel(context.Context, *monitoringpb.VerifyNotificationChannelRequest, ...gax.CallOption) (*monitoringpb.NotificationChannel, error) +} + // NotificationChannelClient is a client for interacting with Cloud Monitoring API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The Notification Channel API provides access to configuration that +// controls how messages related to incidents are sent. type NotificationChannelClient struct { + // The internal transport-dependent client. + internalClient internalNotificationChannelClient + + // The call options for this service. + CallOptions *NotificationChannelCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *NotificationChannelClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *NotificationChannelClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *NotificationChannelClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListNotificationChannelDescriptors lists the descriptors for supported channel types. The use of descriptors +// makes it possible for new channel types to be dynamically added. +func (c *NotificationChannelClient) ListNotificationChannelDescriptors(ctx context.Context, req *monitoringpb.ListNotificationChannelDescriptorsRequest, opts ...gax.CallOption) *NotificationChannelDescriptorIterator { + return c.internalClient.ListNotificationChannelDescriptors(ctx, req, opts...) +} + +// GetNotificationChannelDescriptor gets a single channel descriptor. The descriptor indicates which fields +// are expected / permitted for a notification channel of the given type. +func (c *NotificationChannelClient) GetNotificationChannelDescriptor(ctx context.Context, req *monitoringpb.GetNotificationChannelDescriptorRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannelDescriptor, error) { + return c.internalClient.GetNotificationChannelDescriptor(ctx, req, opts...) +} + +// ListNotificationChannels lists the notification channels that have been created for the project. +func (c *NotificationChannelClient) ListNotificationChannels(ctx context.Context, req *monitoringpb.ListNotificationChannelsRequest, opts ...gax.CallOption) *NotificationChannelIterator { + return c.internalClient.ListNotificationChannels(ctx, req, opts...) +} + +// GetNotificationChannel gets a single notification channel. The channel includes the relevant +// configuration details with which the channel was created. However, the +// response may truncate or omit passwords, API keys, or other private key +// matter and thus the response may not be 100% identical to the information +// that was supplied in the call to the create method. +func (c *NotificationChannelClient) GetNotificationChannel(ctx context.Context, req *monitoringpb.GetNotificationChannelRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannel, error) { + return c.internalClient.GetNotificationChannel(ctx, req, opts...) +} + +// CreateNotificationChannel creates a new notification channel, representing a single notification +// endpoint such as an email address, SMS number, or PagerDuty service. +func (c *NotificationChannelClient) CreateNotificationChannel(ctx context.Context, req *monitoringpb.CreateNotificationChannelRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannel, error) { + return c.internalClient.CreateNotificationChannel(ctx, req, opts...) +} + +// UpdateNotificationChannel updates a notification channel. Fields not specified in the field mask +// remain unchanged. +func (c *NotificationChannelClient) UpdateNotificationChannel(ctx context.Context, req *monitoringpb.UpdateNotificationChannelRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannel, error) { + return c.internalClient.UpdateNotificationChannel(ctx, req, opts...) +} + +// DeleteNotificationChannel deletes a notification channel. +func (c *NotificationChannelClient) DeleteNotificationChannel(ctx context.Context, req *monitoringpb.DeleteNotificationChannelRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteNotificationChannel(ctx, req, opts...) +} + +// SendNotificationChannelVerificationCode causes a verification code to be delivered to the channel. The code +// can then be supplied in VerifyNotificationChannel to verify the channel. +func (c *NotificationChannelClient) SendNotificationChannelVerificationCode(ctx context.Context, req *monitoringpb.SendNotificationChannelVerificationCodeRequest, opts ...gax.CallOption) error { + return c.internalClient.SendNotificationChannelVerificationCode(ctx, req, opts...) +} + +// GetNotificationChannelVerificationCode requests a verification code for an already verified channel that can then +// be used in a call to VerifyNotificationChannel() on a different channel +// with an equivalent identity in the same or in a different project. This +// makes it possible to copy a channel between projects without requiring +// manual reverification of the channel. If the channel is not in the +// verified state, this method will fail (in other words, this may only be +// used if the SendNotificationChannelVerificationCode and +// VerifyNotificationChannel paths have already been used to put the given +// channel into the verified state). +// +// There is no guarantee that the verification codes returned by this method +// will be of a similar structure or form as the ones that are delivered +// to the channel via SendNotificationChannelVerificationCode; while +// VerifyNotificationChannel() will recognize both the codes delivered via +// SendNotificationChannelVerificationCode() and returned from +// GetNotificationChannelVerificationCode(), it is typically the case that +// the verification codes delivered via +// SendNotificationChannelVerificationCode() will be shorter and also +// have a shorter expiration (e.g. codes such as “G-123456”) whereas +// GetVerificationCode() will typically return a much longer, websafe base +// 64 encoded string that has a longer expiration time. +func (c *NotificationChannelClient) GetNotificationChannelVerificationCode(ctx context.Context, req *monitoringpb.GetNotificationChannelVerificationCodeRequest, opts ...gax.CallOption) (*monitoringpb.GetNotificationChannelVerificationCodeResponse, error) { + return c.internalClient.GetNotificationChannelVerificationCode(ctx, req, opts...) +} + +// VerifyNotificationChannel verifies a NotificationChannel by proving receipt of the code +// delivered to the channel as a result of calling +// SendNotificationChannelVerificationCode. +func (c *NotificationChannelClient) VerifyNotificationChannel(ctx context.Context, req *monitoringpb.VerifyNotificationChannelRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannel, error) { + return c.internalClient.VerifyNotificationChannel(ctx, req, opts...) +} + +// notificationChannelGRPCClient is a client for interacting with Cloud Monitoring API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type notificationChannelGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing NotificationChannelClient + CallOptions **NotificationChannelCallOptions + // The gRPC API client. notificationChannelClient monitoringpb.NotificationChannelServiceClient - // The call options for this service. - CallOptions *NotificationChannelCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewNotificationChannelClient creates a new notification channel service client. +// NewNotificationChannelClient creates a new notification channel service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The Notification Channel API provides access to configuration that // controls how messages related to incidents are sent. func NewNotificationChannelClient(ctx context.Context, opts ...option.ClientOption) (*NotificationChannelClient, error) { - clientOpts := defaultNotificationChannelClientOptions() - + clientOpts := defaultNotificationChannelGRPCClientOptions() if newNotificationChannelClientHook != nil { hookOpts, err := newNotificationChannelClientHook(ctx, clientHookParams{}) if err != nil { @@ -199,46 +332,47 @@ func NewNotificationChannelClient(ctx context.Context, opts ...option.ClientOpti if err != nil { return nil, err } - c := &NotificationChannelClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultNotificationChannelCallOptions(), + client := NotificationChannelClient{CallOptions: defaultNotificationChannelCallOptions()} + c := ¬ificationChannelGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, notificationChannelClient: monitoringpb.NewNotificationChannelServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *NotificationChannelClient) Connection() *grpc.ClientConn { +func (c *notificationChannelGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *NotificationChannelClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *NotificationChannelClient) setGoogleClientInfo(keyval ...string) { +func (c *notificationChannelGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListNotificationChannelDescriptors lists the descriptors for supported channel types. The use of descriptors -// makes it possible for new channel types to be dynamically added. -func (c *NotificationChannelClient) ListNotificationChannelDescriptors(ctx context.Context, req *monitoringpb.ListNotificationChannelDescriptorsRequest, opts ...gax.CallOption) *NotificationChannelDescriptorIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *notificationChannelGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *notificationChannelGRPCClient) ListNotificationChannelDescriptors(ctx context.Context, req *monitoringpb.ListNotificationChannelDescriptorsRequest, opts ...gax.CallOption) *NotificationChannelDescriptorIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListNotificationChannelDescriptors[0:len(c.CallOptions.ListNotificationChannelDescriptors):len(c.CallOptions.ListNotificationChannelDescriptors)], opts...) + opts = append((*c.CallOptions).ListNotificationChannelDescriptors[0:len((*c.CallOptions).ListNotificationChannelDescriptors):len((*c.CallOptions).ListNotificationChannelDescriptors)], opts...) it := &NotificationChannelDescriptorIterator{} req = proto.Clone(req).(*monitoringpb.ListNotificationChannelDescriptorsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.NotificationChannelDescriptor, string, error) { @@ -275,9 +409,7 @@ func (c *NotificationChannelClient) ListNotificationChannelDescriptors(ctx conte return it } -// GetNotificationChannelDescriptor gets a single channel descriptor. The descriptor indicates which fields -// are expected / permitted for a notification channel of the given type. -func (c *NotificationChannelClient) GetNotificationChannelDescriptor(ctx context.Context, req *monitoringpb.GetNotificationChannelDescriptorRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannelDescriptor, error) { +func (c *notificationChannelGRPCClient) GetNotificationChannelDescriptor(ctx context.Context, req *monitoringpb.GetNotificationChannelDescriptorRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannelDescriptor, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -285,7 +417,7 @@ func (c *NotificationChannelClient) GetNotificationChannelDescriptor(ctx context } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetNotificationChannelDescriptor[0:len(c.CallOptions.GetNotificationChannelDescriptor):len(c.CallOptions.GetNotificationChannelDescriptor)], opts...) + opts = append((*c.CallOptions).GetNotificationChannelDescriptor[0:len((*c.CallOptions).GetNotificationChannelDescriptor):len((*c.CallOptions).GetNotificationChannelDescriptor)], opts...) var resp *monitoringpb.NotificationChannelDescriptor err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -298,11 +430,10 @@ func (c *NotificationChannelClient) GetNotificationChannelDescriptor(ctx context return resp, nil } -// ListNotificationChannels lists the notification channels that have been created for the project. -func (c *NotificationChannelClient) ListNotificationChannels(ctx context.Context, req *monitoringpb.ListNotificationChannelsRequest, opts ...gax.CallOption) *NotificationChannelIterator { +func (c *notificationChannelGRPCClient) ListNotificationChannels(ctx context.Context, req *monitoringpb.ListNotificationChannelsRequest, opts ...gax.CallOption) *NotificationChannelIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListNotificationChannels[0:len(c.CallOptions.ListNotificationChannels):len(c.CallOptions.ListNotificationChannels)], opts...) + opts = append((*c.CallOptions).ListNotificationChannels[0:len((*c.CallOptions).ListNotificationChannels):len((*c.CallOptions).ListNotificationChannels)], opts...) it := &NotificationChannelIterator{} req = proto.Clone(req).(*monitoringpb.ListNotificationChannelsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.NotificationChannel, string, error) { @@ -339,12 +470,7 @@ func (c *NotificationChannelClient) ListNotificationChannels(ctx context.Context return it } -// GetNotificationChannel gets a single notification channel. The channel includes the relevant -// configuration details with which the channel was created. However, the -// response may truncate or omit passwords, API keys, or other private key -// matter and thus the response may not be 100% identical to the information -// that was supplied in the call to the create method. -func (c *NotificationChannelClient) GetNotificationChannel(ctx context.Context, req *monitoringpb.GetNotificationChannelRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannel, error) { +func (c *notificationChannelGRPCClient) GetNotificationChannel(ctx context.Context, req *monitoringpb.GetNotificationChannelRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannel, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -352,7 +478,7 @@ func (c *NotificationChannelClient) GetNotificationChannel(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetNotificationChannel[0:len(c.CallOptions.GetNotificationChannel):len(c.CallOptions.GetNotificationChannel)], opts...) + opts = append((*c.CallOptions).GetNotificationChannel[0:len((*c.CallOptions).GetNotificationChannel):len((*c.CallOptions).GetNotificationChannel)], opts...) var resp *monitoringpb.NotificationChannel err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -365,9 +491,7 @@ func (c *NotificationChannelClient) GetNotificationChannel(ctx context.Context, return resp, nil } -// CreateNotificationChannel creates a new notification channel, representing a single notification -// endpoint such as an email address, SMS number, or PagerDuty service. -func (c *NotificationChannelClient) CreateNotificationChannel(ctx context.Context, req *monitoringpb.CreateNotificationChannelRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannel, error) { +func (c *notificationChannelGRPCClient) CreateNotificationChannel(ctx context.Context, req *monitoringpb.CreateNotificationChannelRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannel, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -375,7 +499,7 @@ func (c *NotificationChannelClient) CreateNotificationChannel(ctx context.Contex } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateNotificationChannel[0:len(c.CallOptions.CreateNotificationChannel):len(c.CallOptions.CreateNotificationChannel)], opts...) + opts = append((*c.CallOptions).CreateNotificationChannel[0:len((*c.CallOptions).CreateNotificationChannel):len((*c.CallOptions).CreateNotificationChannel)], opts...) var resp *monitoringpb.NotificationChannel err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -388,9 +512,7 @@ func (c *NotificationChannelClient) CreateNotificationChannel(ctx context.Contex return resp, nil } -// UpdateNotificationChannel updates a notification channel. Fields not specified in the field mask -// remain unchanged. -func (c *NotificationChannelClient) UpdateNotificationChannel(ctx context.Context, req *monitoringpb.UpdateNotificationChannelRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannel, error) { +func (c *notificationChannelGRPCClient) UpdateNotificationChannel(ctx context.Context, req *monitoringpb.UpdateNotificationChannelRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannel, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -398,7 +520,7 @@ func (c *NotificationChannelClient) UpdateNotificationChannel(ctx context.Contex } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "notification_channel.name", url.QueryEscape(req.GetNotificationChannel().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateNotificationChannel[0:len(c.CallOptions.UpdateNotificationChannel):len(c.CallOptions.UpdateNotificationChannel)], opts...) + opts = append((*c.CallOptions).UpdateNotificationChannel[0:len((*c.CallOptions).UpdateNotificationChannel):len((*c.CallOptions).UpdateNotificationChannel)], opts...) var resp *monitoringpb.NotificationChannel err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -411,8 +533,7 @@ func (c *NotificationChannelClient) UpdateNotificationChannel(ctx context.Contex return resp, nil } -// DeleteNotificationChannel deletes a notification channel. -func (c *NotificationChannelClient) DeleteNotificationChannel(ctx context.Context, req *monitoringpb.DeleteNotificationChannelRequest, opts ...gax.CallOption) error { +func (c *notificationChannelGRPCClient) DeleteNotificationChannel(ctx context.Context, req *monitoringpb.DeleteNotificationChannelRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -420,7 +541,7 @@ func (c *NotificationChannelClient) DeleteNotificationChannel(ctx context.Contex } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteNotificationChannel[0:len(c.CallOptions.DeleteNotificationChannel):len(c.CallOptions.DeleteNotificationChannel)], opts...) + opts = append((*c.CallOptions).DeleteNotificationChannel[0:len((*c.CallOptions).DeleteNotificationChannel):len((*c.CallOptions).DeleteNotificationChannel)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.notificationChannelClient.DeleteNotificationChannel(ctx, req, settings.GRPC...) @@ -429,9 +550,7 @@ func (c *NotificationChannelClient) DeleteNotificationChannel(ctx context.Contex return err } -// SendNotificationChannelVerificationCode causes a verification code to be delivered to the channel. The code -// can then be supplied in VerifyNotificationChannel to verify the channel. -func (c *NotificationChannelClient) SendNotificationChannelVerificationCode(ctx context.Context, req *monitoringpb.SendNotificationChannelVerificationCodeRequest, opts ...gax.CallOption) error { +func (c *notificationChannelGRPCClient) SendNotificationChannelVerificationCode(ctx context.Context, req *monitoringpb.SendNotificationChannelVerificationCodeRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -439,7 +558,7 @@ func (c *NotificationChannelClient) SendNotificationChannelVerificationCode(ctx } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SendNotificationChannelVerificationCode[0:len(c.CallOptions.SendNotificationChannelVerificationCode):len(c.CallOptions.SendNotificationChannelVerificationCode)], opts...) + opts = append((*c.CallOptions).SendNotificationChannelVerificationCode[0:len((*c.CallOptions).SendNotificationChannelVerificationCode):len((*c.CallOptions).SendNotificationChannelVerificationCode)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.notificationChannelClient.SendNotificationChannelVerificationCode(ctx, req, settings.GRPC...) @@ -448,28 +567,7 @@ func (c *NotificationChannelClient) SendNotificationChannelVerificationCode(ctx return err } -// GetNotificationChannelVerificationCode requests a verification code for an already verified channel that can then -// be used in a call to VerifyNotificationChannel() on a different channel -// with an equivalent identity in the same or in a different project. This -// makes it possible to copy a channel between projects without requiring -// manual reverification of the channel. If the channel is not in the -// verified state, this method will fail (in other words, this may only be -// used if the SendNotificationChannelVerificationCode and -// VerifyNotificationChannel paths have already been used to put the given -// channel into the verified state). -// -// There is no guarantee that the verification codes returned by this method -// will be of a similar structure or form as the ones that are delivered -// to the channel via SendNotificationChannelVerificationCode; while -// VerifyNotificationChannel() will recognize both the codes delivered via -// SendNotificationChannelVerificationCode() and returned from -// GetNotificationChannelVerificationCode(), it is typically the case that -// the verification codes delivered via -// SendNotificationChannelVerificationCode() will be shorter and also -// have a shorter expiration (e.g. codes such as “G-123456”) whereas -// GetVerificationCode() will typically return a much longer, websafe base -// 64 encoded string that has a longer expiration time. -func (c *NotificationChannelClient) GetNotificationChannelVerificationCode(ctx context.Context, req *monitoringpb.GetNotificationChannelVerificationCodeRequest, opts ...gax.CallOption) (*monitoringpb.GetNotificationChannelVerificationCodeResponse, error) { +func (c *notificationChannelGRPCClient) GetNotificationChannelVerificationCode(ctx context.Context, req *monitoringpb.GetNotificationChannelVerificationCodeRequest, opts ...gax.CallOption) (*monitoringpb.GetNotificationChannelVerificationCodeResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -477,7 +575,7 @@ func (c *NotificationChannelClient) GetNotificationChannelVerificationCode(ctx c } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetNotificationChannelVerificationCode[0:len(c.CallOptions.GetNotificationChannelVerificationCode):len(c.CallOptions.GetNotificationChannelVerificationCode)], opts...) + opts = append((*c.CallOptions).GetNotificationChannelVerificationCode[0:len((*c.CallOptions).GetNotificationChannelVerificationCode):len((*c.CallOptions).GetNotificationChannelVerificationCode)], opts...) var resp *monitoringpb.GetNotificationChannelVerificationCodeResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -490,10 +588,7 @@ func (c *NotificationChannelClient) GetNotificationChannelVerificationCode(ctx c return resp, nil } -// VerifyNotificationChannel verifies a NotificationChannel by proving receipt of the code -// delivered to the channel as a result of calling -// SendNotificationChannelVerificationCode. -func (c *NotificationChannelClient) VerifyNotificationChannel(ctx context.Context, req *monitoringpb.VerifyNotificationChannelRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannel, error) { +func (c *notificationChannelGRPCClient) VerifyNotificationChannel(ctx context.Context, req *monitoringpb.VerifyNotificationChannelRequest, opts ...gax.CallOption) (*monitoringpb.NotificationChannel, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -501,7 +596,7 @@ func (c *NotificationChannelClient) VerifyNotificationChannel(ctx context.Contex } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.VerifyNotificationChannel[0:len(c.CallOptions.VerifyNotificationChannel):len(c.CallOptions.VerifyNotificationChannel)], opts...) + opts = append((*c.CallOptions).VerifyNotificationChannel[0:len((*c.CallOptions).VerifyNotificationChannel):len((*c.CallOptions).VerifyNotificationChannel)], opts...) var resp *monitoringpb.NotificationChannel err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/monitoring/apiv3/v2/notification_channel_client_example_test.go b/monitoring/apiv3/v2/notification_channel_client_example_test.go index da5da56a8598..178f74b3d2e7 100644 --- a/monitoring/apiv3/v2/notification_channel_client_example_test.go +++ b/monitoring/apiv3/v2/notification_channel_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewNotificationChannelClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleNotificationChannelClient_ListNotificationChannelDescriptors() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewNotificationChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListNotificationChannelDescriptorsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleNotificationChannelClient_ListNotificationChannelDescriptors() { } func ExampleNotificationChannelClient_GetNotificationChannelDescriptor() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewNotificationChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetNotificationChannelDescriptorRequest{ // TODO: Fill request struct fields. @@ -82,14 +81,12 @@ func ExampleNotificationChannelClient_GetNotificationChannelDescriptor() { } func ExampleNotificationChannelClient_ListNotificationChannels() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewNotificationChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListNotificationChannelsRequest{ // TODO: Fill request struct fields. @@ -109,13 +106,12 @@ func ExampleNotificationChannelClient_ListNotificationChannels() { } func ExampleNotificationChannelClient_GetNotificationChannel() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewNotificationChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetNotificationChannelRequest{ // TODO: Fill request struct fields. @@ -129,13 +125,12 @@ func ExampleNotificationChannelClient_GetNotificationChannel() { } func ExampleNotificationChannelClient_CreateNotificationChannel() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewNotificationChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.CreateNotificationChannelRequest{ // TODO: Fill request struct fields. @@ -149,13 +144,12 @@ func ExampleNotificationChannelClient_CreateNotificationChannel() { } func ExampleNotificationChannelClient_UpdateNotificationChannel() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewNotificationChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.UpdateNotificationChannelRequest{ // TODO: Fill request struct fields. @@ -174,6 +168,7 @@ func ExampleNotificationChannelClient_DeleteNotificationChannel() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.DeleteNotificationChannelRequest{ // TODO: Fill request struct fields. @@ -190,6 +185,7 @@ func ExampleNotificationChannelClient_SendNotificationChannelVerificationCode() if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.SendNotificationChannelVerificationCodeRequest{ // TODO: Fill request struct fields. @@ -201,13 +197,12 @@ func ExampleNotificationChannelClient_SendNotificationChannelVerificationCode() } func ExampleNotificationChannelClient_GetNotificationChannelVerificationCode() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewNotificationChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetNotificationChannelVerificationCodeRequest{ // TODO: Fill request struct fields. @@ -221,13 +216,12 @@ func ExampleNotificationChannelClient_GetNotificationChannelVerificationCode() { } func ExampleNotificationChannelClient_VerifyNotificationChannel() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewNotificationChannelClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.VerifyNotificationChannelRequest{ // TODO: Fill request struct fields. diff --git a/monitoring/apiv3/v2/query_client.go b/monitoring/apiv3/v2/query_client.go index 32fef9b92af5..601deecfc3af 100644 --- a/monitoring/apiv3/v2/query_client.go +++ b/monitoring/apiv3/v2/query_client.go @@ -40,7 +40,7 @@ type QueryCallOptions struct { QueryTimeSeries []gax.CallOption } -func defaultQueryClientOptions() []option.ClientOption { +func defaultQueryGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("monitoring.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("monitoring.mtls.googleapis.com:443"), @@ -58,34 +58,83 @@ func defaultQueryCallOptions() *QueryCallOptions { } } +// internalQueryClient is an interface that defines the methods availaible from Cloud Monitoring API. +type internalQueryClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + QueryTimeSeries(context.Context, *monitoringpb.QueryTimeSeriesRequest, ...gax.CallOption) *TimeSeriesDataIterator +} + // QueryClient is a client for interacting with Cloud Monitoring API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The QueryService API is used to manage time series data in Stackdriver +// Monitoring. Time series data is a collection of data points that describes +// the time-varying values of a metric. type QueryClient struct { + // The internal transport-dependent client. + internalClient internalQueryClient + + // The call options for this service. + CallOptions *QueryCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *QueryClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *QueryClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *QueryClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// QueryTimeSeries queries time series using Monitoring Query Language. This method does not require a Workspace. +func (c *QueryClient) QueryTimeSeries(ctx context.Context, req *monitoringpb.QueryTimeSeriesRequest, opts ...gax.CallOption) *TimeSeriesDataIterator { + return c.internalClient.QueryTimeSeries(ctx, req, opts...) +} + +// queryGRPCClient is a client for interacting with Cloud Monitoring API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type queryGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing QueryClient + CallOptions **QueryCallOptions + // The gRPC API client. queryClient monitoringpb.QueryServiceClient - // The call options for this service. - CallOptions *QueryCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewQueryClient creates a new query service client. +// NewQueryClient creates a new query service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The QueryService API is used to manage time series data in Stackdriver // Monitoring. Time series data is a collection of data points that describes // the time-varying values of a metric. func NewQueryClient(ctx context.Context, opts ...option.ClientOption) (*QueryClient, error) { - clientOpts := defaultQueryClientOptions() - + clientOpts := defaultQueryGRPCClientOptions() if newQueryClientHook != nil { hookOpts, err := newQueryClientHook(ctx, clientHookParams{}) if err != nil { @@ -103,45 +152,47 @@ func NewQueryClient(ctx context.Context, opts ...option.ClientOption) (*QueryCli if err != nil { return nil, err } - c := &QueryClient{ + client := QueryClient{CallOptions: defaultQueryCallOptions()} + + c := &queryGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultQueryCallOptions(), - - queryClient: monitoringpb.NewQueryServiceClient(connPool), + queryClient: monitoringpb.NewQueryServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *QueryClient) Connection() *grpc.ClientConn { +func (c *queryGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *QueryClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *QueryClient) setGoogleClientInfo(keyval ...string) { +func (c *queryGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// QueryTimeSeries queries time series using Monitoring Query Language. This method does not require a Workspace. -func (c *QueryClient) QueryTimeSeries(ctx context.Context, req *monitoringpb.QueryTimeSeriesRequest, opts ...gax.CallOption) *TimeSeriesDataIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *queryGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *queryGRPCClient) QueryTimeSeries(ctx context.Context, req *monitoringpb.QueryTimeSeriesRequest, opts ...gax.CallOption) *TimeSeriesDataIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.QueryTimeSeries[0:len(c.CallOptions.QueryTimeSeries):len(c.CallOptions.QueryTimeSeries)], opts...) + opts = append((*c.CallOptions).QueryTimeSeries[0:len((*c.CallOptions).QueryTimeSeries):len((*c.CallOptions).QueryTimeSeries)], opts...) it := &TimeSeriesDataIterator{} req = proto.Clone(req).(*monitoringpb.QueryTimeSeriesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.TimeSeriesData, string, error) { diff --git a/monitoring/apiv3/v2/query_client_example_test.go b/monitoring/apiv3/v2/query_client_example_test.go index 11386ddc5449..d3badcb69660 100644 --- a/monitoring/apiv3/v2/query_client_example_test.go +++ b/monitoring/apiv3/v2/query_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewQueryClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleQueryClient_QueryTimeSeries() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewQueryClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.QueryTimeSeriesRequest{ // TODO: Fill request struct fields. diff --git a/monitoring/apiv3/v2/service_monitoring_client.go b/monitoring/apiv3/v2/service_monitoring_client.go index dd90ca819669..b83aa2a53f9d 100644 --- a/monitoring/apiv3/v2/service_monitoring_client.go +++ b/monitoring/apiv3/v2/service_monitoring_client.go @@ -51,7 +51,7 @@ type ServiceMonitoringCallOptions struct { DeleteServiceLevelObjective []gax.CallOption } -func defaultServiceMonitoringClientOptions() []option.ClientOption { +func defaultServiceMonitoringGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("monitoring.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("monitoring.mtls.googleapis.com:443"), @@ -144,35 +144,139 @@ func defaultServiceMonitoringCallOptions() *ServiceMonitoringCallOptions { } } +// internalServiceMonitoringClient is an interface that defines the methods availaible from Cloud Monitoring API. +type internalServiceMonitoringClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateService(context.Context, *monitoringpb.CreateServiceRequest, ...gax.CallOption) (*monitoringpb.Service, error) + GetService(context.Context, *monitoringpb.GetServiceRequest, ...gax.CallOption) (*monitoringpb.Service, error) + ListServices(context.Context, *monitoringpb.ListServicesRequest, ...gax.CallOption) *ServiceIterator + UpdateService(context.Context, *monitoringpb.UpdateServiceRequest, ...gax.CallOption) (*monitoringpb.Service, error) + DeleteService(context.Context, *monitoringpb.DeleteServiceRequest, ...gax.CallOption) error + CreateServiceLevelObjective(context.Context, *monitoringpb.CreateServiceLevelObjectiveRequest, ...gax.CallOption) (*monitoringpb.ServiceLevelObjective, error) + GetServiceLevelObjective(context.Context, *monitoringpb.GetServiceLevelObjectiveRequest, ...gax.CallOption) (*monitoringpb.ServiceLevelObjective, error) + ListServiceLevelObjectives(context.Context, *monitoringpb.ListServiceLevelObjectivesRequest, ...gax.CallOption) *ServiceLevelObjectiveIterator + UpdateServiceLevelObjective(context.Context, *monitoringpb.UpdateServiceLevelObjectiveRequest, ...gax.CallOption) (*monitoringpb.ServiceLevelObjective, error) + DeleteServiceLevelObjective(context.Context, *monitoringpb.DeleteServiceLevelObjectiveRequest, ...gax.CallOption) error +} + // ServiceMonitoringClient is a client for interacting with Cloud Monitoring API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The Cloud Monitoring Service-Oriented Monitoring API has endpoints for +// managing and querying aspects of a workspace’s services. These include the +// Service's monitored resources, its Service-Level Objectives, and a taxonomy +// of categorized Health Metrics. type ServiceMonitoringClient struct { + // The internal transport-dependent client. + internalClient internalServiceMonitoringClient + + // The call options for this service. + CallOptions *ServiceMonitoringCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ServiceMonitoringClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ServiceMonitoringClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ServiceMonitoringClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateService create a Service. +func (c *ServiceMonitoringClient) CreateService(ctx context.Context, req *monitoringpb.CreateServiceRequest, opts ...gax.CallOption) (*monitoringpb.Service, error) { + return c.internalClient.CreateService(ctx, req, opts...) +} + +// GetService get the named Service. +func (c *ServiceMonitoringClient) GetService(ctx context.Context, req *monitoringpb.GetServiceRequest, opts ...gax.CallOption) (*monitoringpb.Service, error) { + return c.internalClient.GetService(ctx, req, opts...) +} + +// ListServices list Services for this workspace. +func (c *ServiceMonitoringClient) ListServices(ctx context.Context, req *monitoringpb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { + return c.internalClient.ListServices(ctx, req, opts...) +} + +// UpdateService update this Service. +func (c *ServiceMonitoringClient) UpdateService(ctx context.Context, req *monitoringpb.UpdateServiceRequest, opts ...gax.CallOption) (*monitoringpb.Service, error) { + return c.internalClient.UpdateService(ctx, req, opts...) +} + +// DeleteService soft delete this Service. +func (c *ServiceMonitoringClient) DeleteService(ctx context.Context, req *monitoringpb.DeleteServiceRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteService(ctx, req, opts...) +} + +// CreateServiceLevelObjective create a ServiceLevelObjective for the given Service. +func (c *ServiceMonitoringClient) CreateServiceLevelObjective(ctx context.Context, req *monitoringpb.CreateServiceLevelObjectiveRequest, opts ...gax.CallOption) (*monitoringpb.ServiceLevelObjective, error) { + return c.internalClient.CreateServiceLevelObjective(ctx, req, opts...) +} + +// GetServiceLevelObjective get a ServiceLevelObjective by name. +func (c *ServiceMonitoringClient) GetServiceLevelObjective(ctx context.Context, req *monitoringpb.GetServiceLevelObjectiveRequest, opts ...gax.CallOption) (*monitoringpb.ServiceLevelObjective, error) { + return c.internalClient.GetServiceLevelObjective(ctx, req, opts...) +} + +// ListServiceLevelObjectives list the ServiceLevelObjectives for the given Service. +func (c *ServiceMonitoringClient) ListServiceLevelObjectives(ctx context.Context, req *monitoringpb.ListServiceLevelObjectivesRequest, opts ...gax.CallOption) *ServiceLevelObjectiveIterator { + return c.internalClient.ListServiceLevelObjectives(ctx, req, opts...) +} + +// UpdateServiceLevelObjective update the given ServiceLevelObjective. +func (c *ServiceMonitoringClient) UpdateServiceLevelObjective(ctx context.Context, req *monitoringpb.UpdateServiceLevelObjectiveRequest, opts ...gax.CallOption) (*monitoringpb.ServiceLevelObjective, error) { + return c.internalClient.UpdateServiceLevelObjective(ctx, req, opts...) +} + +// DeleteServiceLevelObjective delete the given ServiceLevelObjective. +func (c *ServiceMonitoringClient) DeleteServiceLevelObjective(ctx context.Context, req *monitoringpb.DeleteServiceLevelObjectiveRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteServiceLevelObjective(ctx, req, opts...) +} + +// serviceMonitoringGRPCClient is a client for interacting with Cloud Monitoring API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type serviceMonitoringGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ServiceMonitoringClient + CallOptions **ServiceMonitoringCallOptions + // The gRPC API client. serviceMonitoringClient monitoringpb.ServiceMonitoringServiceClient - // The call options for this service. - CallOptions *ServiceMonitoringCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewServiceMonitoringClient creates a new service monitoring service client. +// NewServiceMonitoringClient creates a new service monitoring service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The Cloud Monitoring Service-Oriented Monitoring API has endpoints for // managing and querying aspects of a workspace’s services. These include the // Service's monitored resources, its Service-Level Objectives, and a taxonomy // of categorized Health Metrics. func NewServiceMonitoringClient(ctx context.Context, opts ...option.ClientOption) (*ServiceMonitoringClient, error) { - clientOpts := defaultServiceMonitoringClientOptions() - + clientOpts := defaultServiceMonitoringGRPCClientOptions() if newServiceMonitoringClientHook != nil { hookOpts, err := newServiceMonitoringClientHook(ctx, clientHookParams{}) if err != nil { @@ -190,42 +294,44 @@ func NewServiceMonitoringClient(ctx context.Context, opts ...option.ClientOption if err != nil { return nil, err } - c := &ServiceMonitoringClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultServiceMonitoringCallOptions(), + client := ServiceMonitoringClient{CallOptions: defaultServiceMonitoringCallOptions()} + c := &serviceMonitoringGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, serviceMonitoringClient: monitoringpb.NewServiceMonitoringServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ServiceMonitoringClient) Connection() *grpc.ClientConn { +func (c *serviceMonitoringGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ServiceMonitoringClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ServiceMonitoringClient) setGoogleClientInfo(keyval ...string) { +func (c *serviceMonitoringGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateService create a Service. -func (c *ServiceMonitoringClient) CreateService(ctx context.Context, req *monitoringpb.CreateServiceRequest, opts ...gax.CallOption) (*monitoringpb.Service, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *serviceMonitoringGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *serviceMonitoringGRPCClient) CreateService(ctx context.Context, req *monitoringpb.CreateServiceRequest, opts ...gax.CallOption) (*monitoringpb.Service, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -233,7 +339,7 @@ func (c *ServiceMonitoringClient) CreateService(ctx context.Context, req *monito } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateService[0:len(c.CallOptions.CreateService):len(c.CallOptions.CreateService)], opts...) + opts = append((*c.CallOptions).CreateService[0:len((*c.CallOptions).CreateService):len((*c.CallOptions).CreateService)], opts...) var resp *monitoringpb.Service err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -246,8 +352,7 @@ func (c *ServiceMonitoringClient) CreateService(ctx context.Context, req *monito return resp, nil } -// GetService get the named Service. -func (c *ServiceMonitoringClient) GetService(ctx context.Context, req *monitoringpb.GetServiceRequest, opts ...gax.CallOption) (*monitoringpb.Service, error) { +func (c *serviceMonitoringGRPCClient) GetService(ctx context.Context, req *monitoringpb.GetServiceRequest, opts ...gax.CallOption) (*monitoringpb.Service, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -255,7 +360,7 @@ func (c *ServiceMonitoringClient) GetService(ctx context.Context, req *monitorin } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetService[0:len(c.CallOptions.GetService):len(c.CallOptions.GetService)], opts...) + opts = append((*c.CallOptions).GetService[0:len((*c.CallOptions).GetService):len((*c.CallOptions).GetService)], opts...) var resp *monitoringpb.Service err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -268,11 +373,10 @@ func (c *ServiceMonitoringClient) GetService(ctx context.Context, req *monitorin return resp, nil } -// ListServices list Services for this workspace. -func (c *ServiceMonitoringClient) ListServices(ctx context.Context, req *monitoringpb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { +func (c *serviceMonitoringGRPCClient) ListServices(ctx context.Context, req *monitoringpb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListServices[0:len(c.CallOptions.ListServices):len(c.CallOptions.ListServices)], opts...) + opts = append((*c.CallOptions).ListServices[0:len((*c.CallOptions).ListServices):len((*c.CallOptions).ListServices)], opts...) it := &ServiceIterator{} req = proto.Clone(req).(*monitoringpb.ListServicesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.Service, string, error) { @@ -309,8 +413,7 @@ func (c *ServiceMonitoringClient) ListServices(ctx context.Context, req *monitor return it } -// UpdateService update this Service. -func (c *ServiceMonitoringClient) UpdateService(ctx context.Context, req *monitoringpb.UpdateServiceRequest, opts ...gax.CallOption) (*monitoringpb.Service, error) { +func (c *serviceMonitoringGRPCClient) UpdateService(ctx context.Context, req *monitoringpb.UpdateServiceRequest, opts ...gax.CallOption) (*monitoringpb.Service, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -318,7 +421,7 @@ func (c *ServiceMonitoringClient) UpdateService(ctx context.Context, req *monito } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service.name", url.QueryEscape(req.GetService().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateService[0:len(c.CallOptions.UpdateService):len(c.CallOptions.UpdateService)], opts...) + opts = append((*c.CallOptions).UpdateService[0:len((*c.CallOptions).UpdateService):len((*c.CallOptions).UpdateService)], opts...) var resp *monitoringpb.Service err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -331,8 +434,7 @@ func (c *ServiceMonitoringClient) UpdateService(ctx context.Context, req *monito return resp, nil } -// DeleteService soft delete this Service. -func (c *ServiceMonitoringClient) DeleteService(ctx context.Context, req *monitoringpb.DeleteServiceRequest, opts ...gax.CallOption) error { +func (c *serviceMonitoringGRPCClient) DeleteService(ctx context.Context, req *monitoringpb.DeleteServiceRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -340,7 +442,7 @@ func (c *ServiceMonitoringClient) DeleteService(ctx context.Context, req *monito } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteService[0:len(c.CallOptions.DeleteService):len(c.CallOptions.DeleteService)], opts...) + opts = append((*c.CallOptions).DeleteService[0:len((*c.CallOptions).DeleteService):len((*c.CallOptions).DeleteService)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.serviceMonitoringClient.DeleteService(ctx, req, settings.GRPC...) @@ -349,8 +451,7 @@ func (c *ServiceMonitoringClient) DeleteService(ctx context.Context, req *monito return err } -// CreateServiceLevelObjective create a ServiceLevelObjective for the given Service. -func (c *ServiceMonitoringClient) CreateServiceLevelObjective(ctx context.Context, req *monitoringpb.CreateServiceLevelObjectiveRequest, opts ...gax.CallOption) (*monitoringpb.ServiceLevelObjective, error) { +func (c *serviceMonitoringGRPCClient) CreateServiceLevelObjective(ctx context.Context, req *monitoringpb.CreateServiceLevelObjectiveRequest, opts ...gax.CallOption) (*monitoringpb.ServiceLevelObjective, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -358,7 +459,7 @@ func (c *ServiceMonitoringClient) CreateServiceLevelObjective(ctx context.Contex } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateServiceLevelObjective[0:len(c.CallOptions.CreateServiceLevelObjective):len(c.CallOptions.CreateServiceLevelObjective)], opts...) + opts = append((*c.CallOptions).CreateServiceLevelObjective[0:len((*c.CallOptions).CreateServiceLevelObjective):len((*c.CallOptions).CreateServiceLevelObjective)], opts...) var resp *monitoringpb.ServiceLevelObjective err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -371,8 +472,7 @@ func (c *ServiceMonitoringClient) CreateServiceLevelObjective(ctx context.Contex return resp, nil } -// GetServiceLevelObjective get a ServiceLevelObjective by name. -func (c *ServiceMonitoringClient) GetServiceLevelObjective(ctx context.Context, req *monitoringpb.GetServiceLevelObjectiveRequest, opts ...gax.CallOption) (*monitoringpb.ServiceLevelObjective, error) { +func (c *serviceMonitoringGRPCClient) GetServiceLevelObjective(ctx context.Context, req *monitoringpb.GetServiceLevelObjectiveRequest, opts ...gax.CallOption) (*monitoringpb.ServiceLevelObjective, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -380,7 +480,7 @@ func (c *ServiceMonitoringClient) GetServiceLevelObjective(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetServiceLevelObjective[0:len(c.CallOptions.GetServiceLevelObjective):len(c.CallOptions.GetServiceLevelObjective)], opts...) + opts = append((*c.CallOptions).GetServiceLevelObjective[0:len((*c.CallOptions).GetServiceLevelObjective):len((*c.CallOptions).GetServiceLevelObjective)], opts...) var resp *monitoringpb.ServiceLevelObjective err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -393,11 +493,10 @@ func (c *ServiceMonitoringClient) GetServiceLevelObjective(ctx context.Context, return resp, nil } -// ListServiceLevelObjectives list the ServiceLevelObjectives for the given Service. -func (c *ServiceMonitoringClient) ListServiceLevelObjectives(ctx context.Context, req *monitoringpb.ListServiceLevelObjectivesRequest, opts ...gax.CallOption) *ServiceLevelObjectiveIterator { +func (c *serviceMonitoringGRPCClient) ListServiceLevelObjectives(ctx context.Context, req *monitoringpb.ListServiceLevelObjectivesRequest, opts ...gax.CallOption) *ServiceLevelObjectiveIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListServiceLevelObjectives[0:len(c.CallOptions.ListServiceLevelObjectives):len(c.CallOptions.ListServiceLevelObjectives)], opts...) + opts = append((*c.CallOptions).ListServiceLevelObjectives[0:len((*c.CallOptions).ListServiceLevelObjectives):len((*c.CallOptions).ListServiceLevelObjectives)], opts...) it := &ServiceLevelObjectiveIterator{} req = proto.Clone(req).(*monitoringpb.ListServiceLevelObjectivesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.ServiceLevelObjective, string, error) { @@ -434,8 +533,7 @@ func (c *ServiceMonitoringClient) ListServiceLevelObjectives(ctx context.Context return it } -// UpdateServiceLevelObjective update the given ServiceLevelObjective. -func (c *ServiceMonitoringClient) UpdateServiceLevelObjective(ctx context.Context, req *monitoringpb.UpdateServiceLevelObjectiveRequest, opts ...gax.CallOption) (*monitoringpb.ServiceLevelObjective, error) { +func (c *serviceMonitoringGRPCClient) UpdateServiceLevelObjective(ctx context.Context, req *monitoringpb.UpdateServiceLevelObjectiveRequest, opts ...gax.CallOption) (*monitoringpb.ServiceLevelObjective, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -443,7 +541,7 @@ func (c *ServiceMonitoringClient) UpdateServiceLevelObjective(ctx context.Contex } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_level_objective.name", url.QueryEscape(req.GetServiceLevelObjective().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateServiceLevelObjective[0:len(c.CallOptions.UpdateServiceLevelObjective):len(c.CallOptions.UpdateServiceLevelObjective)], opts...) + opts = append((*c.CallOptions).UpdateServiceLevelObjective[0:len((*c.CallOptions).UpdateServiceLevelObjective):len((*c.CallOptions).UpdateServiceLevelObjective)], opts...) var resp *monitoringpb.ServiceLevelObjective err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -456,8 +554,7 @@ func (c *ServiceMonitoringClient) UpdateServiceLevelObjective(ctx context.Contex return resp, nil } -// DeleteServiceLevelObjective delete the given ServiceLevelObjective. -func (c *ServiceMonitoringClient) DeleteServiceLevelObjective(ctx context.Context, req *monitoringpb.DeleteServiceLevelObjectiveRequest, opts ...gax.CallOption) error { +func (c *serviceMonitoringGRPCClient) DeleteServiceLevelObjective(ctx context.Context, req *monitoringpb.DeleteServiceLevelObjectiveRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -465,7 +562,7 @@ func (c *ServiceMonitoringClient) DeleteServiceLevelObjective(ctx context.Contex } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteServiceLevelObjective[0:len(c.CallOptions.DeleteServiceLevelObjective):len(c.CallOptions.DeleteServiceLevelObjective)], opts...) + opts = append((*c.CallOptions).DeleteServiceLevelObjective[0:len((*c.CallOptions).DeleteServiceLevelObjective):len((*c.CallOptions).DeleteServiceLevelObjective)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.serviceMonitoringClient.DeleteServiceLevelObjective(ctx, req, settings.GRPC...) diff --git a/monitoring/apiv3/v2/service_monitoring_client_example_test.go b/monitoring/apiv3/v2/service_monitoring_client_example_test.go index 7d1539c80463..8458740b7a5d 100644 --- a/monitoring/apiv3/v2/service_monitoring_client_example_test.go +++ b/monitoring/apiv3/v2/service_monitoring_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewServiceMonitoringClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleServiceMonitoringClient_CreateService() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewServiceMonitoringClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.CreateServiceRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleServiceMonitoringClient_CreateService() { } func ExampleServiceMonitoringClient_GetService() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewServiceMonitoringClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetServiceRequest{ // TODO: Fill request struct fields. @@ -75,14 +75,12 @@ func ExampleServiceMonitoringClient_GetService() { } func ExampleServiceMonitoringClient_ListServices() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewServiceMonitoringClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListServicesRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleServiceMonitoringClient_ListServices() { } func ExampleServiceMonitoringClient_UpdateService() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewServiceMonitoringClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.UpdateServiceRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleServiceMonitoringClient_DeleteService() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.DeleteServiceRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleServiceMonitoringClient_DeleteService() { } func ExampleServiceMonitoringClient_CreateServiceLevelObjective() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewServiceMonitoringClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.CreateServiceLevelObjectiveRequest{ // TODO: Fill request struct fields. @@ -158,13 +155,12 @@ func ExampleServiceMonitoringClient_CreateServiceLevelObjective() { } func ExampleServiceMonitoringClient_GetServiceLevelObjective() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewServiceMonitoringClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetServiceLevelObjectiveRequest{ // TODO: Fill request struct fields. @@ -178,14 +174,12 @@ func ExampleServiceMonitoringClient_GetServiceLevelObjective() { } func ExampleServiceMonitoringClient_ListServiceLevelObjectives() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewServiceMonitoringClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListServiceLevelObjectivesRequest{ // TODO: Fill request struct fields. @@ -205,13 +199,12 @@ func ExampleServiceMonitoringClient_ListServiceLevelObjectives() { } func ExampleServiceMonitoringClient_UpdateServiceLevelObjective() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewServiceMonitoringClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.UpdateServiceLevelObjectiveRequest{ // TODO: Fill request struct fields. @@ -230,6 +223,7 @@ func ExampleServiceMonitoringClient_DeleteServiceLevelObjective() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.DeleteServiceLevelObjectiveRequest{ // TODO: Fill request struct fields. diff --git a/monitoring/apiv3/v2/uptime_check_client.go b/monitoring/apiv3/v2/uptime_check_client.go index 5550e4c32c00..251e3963f3ac 100644 --- a/monitoring/apiv3/v2/uptime_check_client.go +++ b/monitoring/apiv3/v2/uptime_check_client.go @@ -47,7 +47,7 @@ type UptimeCheckCallOptions struct { ListUptimeCheckIps []gax.CallOption } -func defaultUptimeCheckClientOptions() []option.ClientOption { +func defaultUptimeCheckGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("monitoring.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("monitoring.mtls.googleapis.com:443"), @@ -114,27 +114,118 @@ func defaultUptimeCheckCallOptions() *UptimeCheckCallOptions { } } +// internalUptimeCheckClient is an interface that defines the methods availaible from Cloud Monitoring API. +type internalUptimeCheckClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListUptimeCheckConfigs(context.Context, *monitoringpb.ListUptimeCheckConfigsRequest, ...gax.CallOption) *UptimeCheckConfigIterator + GetUptimeCheckConfig(context.Context, *monitoringpb.GetUptimeCheckConfigRequest, ...gax.CallOption) (*monitoringpb.UptimeCheckConfig, error) + CreateUptimeCheckConfig(context.Context, *monitoringpb.CreateUptimeCheckConfigRequest, ...gax.CallOption) (*monitoringpb.UptimeCheckConfig, error) + UpdateUptimeCheckConfig(context.Context, *monitoringpb.UpdateUptimeCheckConfigRequest, ...gax.CallOption) (*monitoringpb.UptimeCheckConfig, error) + DeleteUptimeCheckConfig(context.Context, *monitoringpb.DeleteUptimeCheckConfigRequest, ...gax.CallOption) error + ListUptimeCheckIps(context.Context, *monitoringpb.ListUptimeCheckIpsRequest, ...gax.CallOption) *UptimeCheckIpIterator +} + // UptimeCheckClient is a client for interacting with Cloud Monitoring API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The UptimeCheckService API is used to manage (list, create, delete, edit) +// Uptime check configurations in the Stackdriver Monitoring product. An Uptime +// check is a piece of configuration that determines which resources and +// services to monitor for availability. These configurations can also be +// configured interactively by navigating to the [Cloud Console] +// (http://console.cloud.google.com (at http://console.cloud.google.com)), selecting the appropriate project, +// clicking on “Monitoring” on the left-hand side to navigate to Stackdriver, +// and then clicking on “Uptime”. type UptimeCheckClient struct { + // The internal transport-dependent client. + internalClient internalUptimeCheckClient + + // The call options for this service. + CallOptions *UptimeCheckCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *UptimeCheckClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *UptimeCheckClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *UptimeCheckClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListUptimeCheckConfigs lists the existing valid Uptime check configurations for the project +// (leaving out any invalid configurations). +func (c *UptimeCheckClient) ListUptimeCheckConfigs(ctx context.Context, req *monitoringpb.ListUptimeCheckConfigsRequest, opts ...gax.CallOption) *UptimeCheckConfigIterator { + return c.internalClient.ListUptimeCheckConfigs(ctx, req, opts...) +} + +// GetUptimeCheckConfig gets a single Uptime check configuration. +func (c *UptimeCheckClient) GetUptimeCheckConfig(ctx context.Context, req *monitoringpb.GetUptimeCheckConfigRequest, opts ...gax.CallOption) (*monitoringpb.UptimeCheckConfig, error) { + return c.internalClient.GetUptimeCheckConfig(ctx, req, opts...) +} + +// CreateUptimeCheckConfig creates a new Uptime check configuration. +func (c *UptimeCheckClient) CreateUptimeCheckConfig(ctx context.Context, req *monitoringpb.CreateUptimeCheckConfigRequest, opts ...gax.CallOption) (*monitoringpb.UptimeCheckConfig, error) { + return c.internalClient.CreateUptimeCheckConfig(ctx, req, opts...) +} + +// UpdateUptimeCheckConfig updates an Uptime check configuration. You can either replace the entire +// configuration with a new one or replace only certain fields in the current +// configuration by specifying the fields to be updated via updateMask. +// Returns the updated configuration. +func (c *UptimeCheckClient) UpdateUptimeCheckConfig(ctx context.Context, req *monitoringpb.UpdateUptimeCheckConfigRequest, opts ...gax.CallOption) (*monitoringpb.UptimeCheckConfig, error) { + return c.internalClient.UpdateUptimeCheckConfig(ctx, req, opts...) +} + +// DeleteUptimeCheckConfig deletes an Uptime check configuration. Note that this method will fail +// if the Uptime check configuration is referenced by an alert policy or +// other dependent configs that would be rendered invalid by the deletion. +func (c *UptimeCheckClient) DeleteUptimeCheckConfig(ctx context.Context, req *monitoringpb.DeleteUptimeCheckConfigRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteUptimeCheckConfig(ctx, req, opts...) +} + +// ListUptimeCheckIps returns the list of IP addresses that checkers run from +func (c *UptimeCheckClient) ListUptimeCheckIps(ctx context.Context, req *monitoringpb.ListUptimeCheckIpsRequest, opts ...gax.CallOption) *UptimeCheckIpIterator { + return c.internalClient.ListUptimeCheckIps(ctx, req, opts...) +} + +// uptimeCheckGRPCClient is a client for interacting with Cloud Monitoring API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type uptimeCheckGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing UptimeCheckClient + CallOptions **UptimeCheckCallOptions + // The gRPC API client. uptimeCheckClient monitoringpb.UptimeCheckServiceClient - // The call options for this service. - CallOptions *UptimeCheckCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewUptimeCheckClient creates a new uptime check service client. +// NewUptimeCheckClient creates a new uptime check service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The UptimeCheckService API is used to manage (list, create, delete, edit) // Uptime check configurations in the Stackdriver Monitoring product. An Uptime @@ -145,8 +236,7 @@ type UptimeCheckClient struct { // clicking on “Monitoring” on the left-hand side to navigate to Stackdriver, // and then clicking on “Uptime”. func NewUptimeCheckClient(ctx context.Context, opts ...option.ClientOption) (*UptimeCheckClient, error) { - clientOpts := defaultUptimeCheckClientOptions() - + clientOpts := defaultUptimeCheckGRPCClientOptions() if newUptimeCheckClientHook != nil { hookOpts, err := newUptimeCheckClientHook(ctx, clientHookParams{}) if err != nil { @@ -164,46 +254,47 @@ func NewUptimeCheckClient(ctx context.Context, opts ...option.ClientOption) (*Up if err != nil { return nil, err } - c := &UptimeCheckClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultUptimeCheckCallOptions(), + client := UptimeCheckClient{CallOptions: defaultUptimeCheckCallOptions()} + c := &uptimeCheckGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, uptimeCheckClient: monitoringpb.NewUptimeCheckServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *UptimeCheckClient) Connection() *grpc.ClientConn { +func (c *uptimeCheckGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *UptimeCheckClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *UptimeCheckClient) setGoogleClientInfo(keyval ...string) { +func (c *uptimeCheckGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListUptimeCheckConfigs lists the existing valid Uptime check configurations for the project -// (leaving out any invalid configurations). -func (c *UptimeCheckClient) ListUptimeCheckConfigs(ctx context.Context, req *monitoringpb.ListUptimeCheckConfigsRequest, opts ...gax.CallOption) *UptimeCheckConfigIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *uptimeCheckGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *uptimeCheckGRPCClient) ListUptimeCheckConfigs(ctx context.Context, req *monitoringpb.ListUptimeCheckConfigsRequest, opts ...gax.CallOption) *UptimeCheckConfigIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListUptimeCheckConfigs[0:len(c.CallOptions.ListUptimeCheckConfigs):len(c.CallOptions.ListUptimeCheckConfigs)], opts...) + opts = append((*c.CallOptions).ListUptimeCheckConfigs[0:len((*c.CallOptions).ListUptimeCheckConfigs):len((*c.CallOptions).ListUptimeCheckConfigs)], opts...) it := &UptimeCheckConfigIterator{} req = proto.Clone(req).(*monitoringpb.ListUptimeCheckConfigsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.UptimeCheckConfig, string, error) { @@ -240,8 +331,7 @@ func (c *UptimeCheckClient) ListUptimeCheckConfigs(ctx context.Context, req *mon return it } -// GetUptimeCheckConfig gets a single Uptime check configuration. -func (c *UptimeCheckClient) GetUptimeCheckConfig(ctx context.Context, req *monitoringpb.GetUptimeCheckConfigRequest, opts ...gax.CallOption) (*monitoringpb.UptimeCheckConfig, error) { +func (c *uptimeCheckGRPCClient) GetUptimeCheckConfig(ctx context.Context, req *monitoringpb.GetUptimeCheckConfigRequest, opts ...gax.CallOption) (*monitoringpb.UptimeCheckConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -249,7 +339,7 @@ func (c *UptimeCheckClient) GetUptimeCheckConfig(ctx context.Context, req *monit } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetUptimeCheckConfig[0:len(c.CallOptions.GetUptimeCheckConfig):len(c.CallOptions.GetUptimeCheckConfig)], opts...) + opts = append((*c.CallOptions).GetUptimeCheckConfig[0:len((*c.CallOptions).GetUptimeCheckConfig):len((*c.CallOptions).GetUptimeCheckConfig)], opts...) var resp *monitoringpb.UptimeCheckConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -262,8 +352,7 @@ func (c *UptimeCheckClient) GetUptimeCheckConfig(ctx context.Context, req *monit return resp, nil } -// CreateUptimeCheckConfig creates a new Uptime check configuration. -func (c *UptimeCheckClient) CreateUptimeCheckConfig(ctx context.Context, req *monitoringpb.CreateUptimeCheckConfigRequest, opts ...gax.CallOption) (*monitoringpb.UptimeCheckConfig, error) { +func (c *uptimeCheckGRPCClient) CreateUptimeCheckConfig(ctx context.Context, req *monitoringpb.CreateUptimeCheckConfigRequest, opts ...gax.CallOption) (*monitoringpb.UptimeCheckConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -271,7 +360,7 @@ func (c *UptimeCheckClient) CreateUptimeCheckConfig(ctx context.Context, req *mo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateUptimeCheckConfig[0:len(c.CallOptions.CreateUptimeCheckConfig):len(c.CallOptions.CreateUptimeCheckConfig)], opts...) + opts = append((*c.CallOptions).CreateUptimeCheckConfig[0:len((*c.CallOptions).CreateUptimeCheckConfig):len((*c.CallOptions).CreateUptimeCheckConfig)], opts...) var resp *monitoringpb.UptimeCheckConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -284,11 +373,7 @@ func (c *UptimeCheckClient) CreateUptimeCheckConfig(ctx context.Context, req *mo return resp, nil } -// UpdateUptimeCheckConfig updates an Uptime check configuration. You can either replace the entire -// configuration with a new one or replace only certain fields in the current -// configuration by specifying the fields to be updated via updateMask. -// Returns the updated configuration. -func (c *UptimeCheckClient) UpdateUptimeCheckConfig(ctx context.Context, req *monitoringpb.UpdateUptimeCheckConfigRequest, opts ...gax.CallOption) (*monitoringpb.UptimeCheckConfig, error) { +func (c *uptimeCheckGRPCClient) UpdateUptimeCheckConfig(ctx context.Context, req *monitoringpb.UpdateUptimeCheckConfigRequest, opts ...gax.CallOption) (*monitoringpb.UptimeCheckConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -296,7 +381,7 @@ func (c *UptimeCheckClient) UpdateUptimeCheckConfig(ctx context.Context, req *mo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "uptime_check_config.name", url.QueryEscape(req.GetUptimeCheckConfig().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateUptimeCheckConfig[0:len(c.CallOptions.UpdateUptimeCheckConfig):len(c.CallOptions.UpdateUptimeCheckConfig)], opts...) + opts = append((*c.CallOptions).UpdateUptimeCheckConfig[0:len((*c.CallOptions).UpdateUptimeCheckConfig):len((*c.CallOptions).UpdateUptimeCheckConfig)], opts...) var resp *monitoringpb.UptimeCheckConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -309,10 +394,7 @@ func (c *UptimeCheckClient) UpdateUptimeCheckConfig(ctx context.Context, req *mo return resp, nil } -// DeleteUptimeCheckConfig deletes an Uptime check configuration. Note that this method will fail -// if the Uptime check configuration is referenced by an alert policy or -// other dependent configs that would be rendered invalid by the deletion. -func (c *UptimeCheckClient) DeleteUptimeCheckConfig(ctx context.Context, req *monitoringpb.DeleteUptimeCheckConfigRequest, opts ...gax.CallOption) error { +func (c *uptimeCheckGRPCClient) DeleteUptimeCheckConfig(ctx context.Context, req *monitoringpb.DeleteUptimeCheckConfigRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -320,7 +402,7 @@ func (c *UptimeCheckClient) DeleteUptimeCheckConfig(ctx context.Context, req *mo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteUptimeCheckConfig[0:len(c.CallOptions.DeleteUptimeCheckConfig):len(c.CallOptions.DeleteUptimeCheckConfig)], opts...) + opts = append((*c.CallOptions).DeleteUptimeCheckConfig[0:len((*c.CallOptions).DeleteUptimeCheckConfig):len((*c.CallOptions).DeleteUptimeCheckConfig)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.uptimeCheckClient.DeleteUptimeCheckConfig(ctx, req, settings.GRPC...) @@ -329,10 +411,9 @@ func (c *UptimeCheckClient) DeleteUptimeCheckConfig(ctx context.Context, req *mo return err } -// ListUptimeCheckIps returns the list of IP addresses that checkers run from -func (c *UptimeCheckClient) ListUptimeCheckIps(ctx context.Context, req *monitoringpb.ListUptimeCheckIpsRequest, opts ...gax.CallOption) *UptimeCheckIpIterator { +func (c *uptimeCheckGRPCClient) ListUptimeCheckIps(ctx context.Context, req *monitoringpb.ListUptimeCheckIpsRequest, opts ...gax.CallOption) *UptimeCheckIpIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListUptimeCheckIps[0:len(c.CallOptions.ListUptimeCheckIps):len(c.CallOptions.ListUptimeCheckIps)], opts...) + opts = append((*c.CallOptions).ListUptimeCheckIps[0:len((*c.CallOptions).ListUptimeCheckIps):len((*c.CallOptions).ListUptimeCheckIps)], opts...) it := &UptimeCheckIpIterator{} req = proto.Clone(req).(*monitoringpb.ListUptimeCheckIpsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*monitoringpb.UptimeCheckIp, string, error) { diff --git a/monitoring/apiv3/v2/uptime_check_client_example_test.go b/monitoring/apiv3/v2/uptime_check_client_example_test.go index 2f93953a63c8..4b323b67b5fa 100644 --- a/monitoring/apiv3/v2/uptime_check_client_example_test.go +++ b/monitoring/apiv3/v2/uptime_check_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewUptimeCheckClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleUptimeCheckClient_ListUptimeCheckConfigs() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewUptimeCheckClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListUptimeCheckConfigsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleUptimeCheckClient_ListUptimeCheckConfigs() { } func ExampleUptimeCheckClient_GetUptimeCheckConfig() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewUptimeCheckClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.GetUptimeCheckConfigRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleUptimeCheckClient_GetUptimeCheckConfig() { } func ExampleUptimeCheckClient_CreateUptimeCheckConfig() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewUptimeCheckClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.CreateUptimeCheckConfigRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleUptimeCheckClient_CreateUptimeCheckConfig() { } func ExampleUptimeCheckClient_UpdateUptimeCheckConfig() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - ctx := context.Background() c, err := monitoring.NewUptimeCheckClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.UpdateUptimeCheckConfigRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleUptimeCheckClient_DeleteUptimeCheckConfig() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.DeleteUptimeCheckConfigRequest{ // TODO: Fill request struct fields. @@ -138,14 +136,12 @@ func ExampleUptimeCheckClient_DeleteUptimeCheckConfig() { } func ExampleUptimeCheckClient_ListUptimeCheckIps() { - // import monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := monitoring.NewUptimeCheckClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &monitoringpb.ListUptimeCheckIpsRequest{ // TODO: Fill request struct fields. diff --git a/monitoring/dashboard/apiv1/dashboards_client.go b/monitoring/dashboard/apiv1/dashboards_client.go index d215b91f0847..47bf0c85ba98 100644 --- a/monitoring/dashboard/apiv1/dashboards_client.go +++ b/monitoring/dashboard/apiv1/dashboards_client.go @@ -46,7 +46,7 @@ type DashboardsCallOptions struct { UpdateDashboard []gax.CallOption } -func defaultDashboardsClientOptions() []option.ClientOption { +func defaultDashboardsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("monitoring.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("monitoring.mtls.googleapis.com:443"), @@ -90,33 +90,126 @@ func defaultDashboardsCallOptions() *DashboardsCallOptions { } } +// internalDashboardsClient is an interface that defines the methods availaible from Cloud Monitoring API. +type internalDashboardsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateDashboard(context.Context, *dashboardpb.CreateDashboardRequest, ...gax.CallOption) (*dashboardpb.Dashboard, error) + ListDashboards(context.Context, *dashboardpb.ListDashboardsRequest, ...gax.CallOption) *DashboardIterator + GetDashboard(context.Context, *dashboardpb.GetDashboardRequest, ...gax.CallOption) (*dashboardpb.Dashboard, error) + DeleteDashboard(context.Context, *dashboardpb.DeleteDashboardRequest, ...gax.CallOption) error + UpdateDashboard(context.Context, *dashboardpb.UpdateDashboardRequest, ...gax.CallOption) (*dashboardpb.Dashboard, error) +} + // DashboardsClient is a client for interacting with Cloud Monitoring API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Manages Stackdriver dashboards. A dashboard is an arrangement of data display +// widgets in a specific layout. type DashboardsClient struct { + // The internal transport-dependent client. + internalClient internalDashboardsClient + + // The call options for this service. + CallOptions *DashboardsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *DashboardsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *DashboardsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *DashboardsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateDashboard creates a new custom dashboard. For examples on how you can use this API to +// create dashboards, see Managing dashboards by +// API (at https://cloud.google.com/monitoring/dashboards/api-dashboard). This method requires the +// monitoring.dashboards.create permission on the specified project. For +// more information about permissions, see Cloud Identity and Access +// Management (at https://cloud.google.com/iam). +func (c *DashboardsClient) CreateDashboard(ctx context.Context, req *dashboardpb.CreateDashboardRequest, opts ...gax.CallOption) (*dashboardpb.Dashboard, error) { + return c.internalClient.CreateDashboard(ctx, req, opts...) +} + +// ListDashboards lists the existing dashboards. +// +// This method requires the monitoring.dashboards.list permission +// on the specified project. For more information, see +// Cloud Identity and Access Management (at https://cloud.google.com/iam). +func (c *DashboardsClient) ListDashboards(ctx context.Context, req *dashboardpb.ListDashboardsRequest, opts ...gax.CallOption) *DashboardIterator { + return c.internalClient.ListDashboards(ctx, req, opts...) +} + +// GetDashboard fetches a specific dashboard. +// +// This method requires the monitoring.dashboards.get permission +// on the specified dashboard. For more information, see +// Cloud Identity and Access Management (at https://cloud.google.com/iam). +func (c *DashboardsClient) GetDashboard(ctx context.Context, req *dashboardpb.GetDashboardRequest, opts ...gax.CallOption) (*dashboardpb.Dashboard, error) { + return c.internalClient.GetDashboard(ctx, req, opts...) +} + +// DeleteDashboard deletes an existing custom dashboard. +// +// This method requires the monitoring.dashboards.delete permission +// on the specified dashboard. For more information, see +// Cloud Identity and Access Management (at https://cloud.google.com/iam). +func (c *DashboardsClient) DeleteDashboard(ctx context.Context, req *dashboardpb.DeleteDashboardRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteDashboard(ctx, req, opts...) +} + +// UpdateDashboard replaces an existing custom dashboard with a new definition. +// +// This method requires the monitoring.dashboards.update permission +// on the specified dashboard. For more information, see +// Cloud Identity and Access Management (at https://cloud.google.com/iam). +func (c *DashboardsClient) UpdateDashboard(ctx context.Context, req *dashboardpb.UpdateDashboardRequest, opts ...gax.CallOption) (*dashboardpb.Dashboard, error) { + return c.internalClient.UpdateDashboard(ctx, req, opts...) +} + +// dashboardsGRPCClient is a client for interacting with Cloud Monitoring API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type dashboardsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing DashboardsClient + CallOptions **DashboardsCallOptions + // The gRPC API client. dashboardsClient dashboardpb.DashboardsServiceClient - // The call options for this service. - CallOptions *DashboardsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewDashboardsClient creates a new dashboards service client. +// NewDashboardsClient creates a new dashboards service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Manages Stackdriver dashboards. A dashboard is an arrangement of data display // widgets in a specific layout. func NewDashboardsClient(ctx context.Context, opts ...option.ClientOption) (*DashboardsClient, error) { - clientOpts := defaultDashboardsClientOptions() - + clientOpts := defaultDashboardsGRPCClientOptions() if newDashboardsClientHook != nil { hookOpts, err := newDashboardsClientHook(ctx, clientHookParams{}) if err != nil { @@ -134,47 +227,44 @@ func NewDashboardsClient(ctx context.Context, opts ...option.ClientOption) (*Das if err != nil { return nil, err } - c := &DashboardsClient{ + client := DashboardsClient{CallOptions: defaultDashboardsCallOptions()} + + c := &dashboardsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultDashboardsCallOptions(), - dashboardsClient: dashboardpb.NewDashboardsServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *DashboardsClient) Connection() *grpc.ClientConn { +func (c *dashboardsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *DashboardsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *DashboardsClient) setGoogleClientInfo(keyval ...string) { +func (c *dashboardsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateDashboard creates a new custom dashboard. For examples on how you can use this API to -// create dashboards, see Managing dashboards by -// API (at https://cloud.google.com/monitoring/dashboards/api-dashboard). This method requires the -// monitoring.dashboards.create permission on the specified project. For -// more information about permissions, see Cloud Identity and Access -// Management (at https://cloud.google.com/iam). -func (c *DashboardsClient) CreateDashboard(ctx context.Context, req *dashboardpb.CreateDashboardRequest, opts ...gax.CallOption) (*dashboardpb.Dashboard, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *dashboardsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *dashboardsGRPCClient) CreateDashboard(ctx context.Context, req *dashboardpb.CreateDashboardRequest, opts ...gax.CallOption) (*dashboardpb.Dashboard, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -182,7 +272,7 @@ func (c *DashboardsClient) CreateDashboard(ctx context.Context, req *dashboardpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateDashboard[0:len(c.CallOptions.CreateDashboard):len(c.CallOptions.CreateDashboard)], opts...) + opts = append((*c.CallOptions).CreateDashboard[0:len((*c.CallOptions).CreateDashboard):len((*c.CallOptions).CreateDashboard)], opts...) var resp *dashboardpb.Dashboard err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -195,15 +285,10 @@ func (c *DashboardsClient) CreateDashboard(ctx context.Context, req *dashboardpb return resp, nil } -// ListDashboards lists the existing dashboards. -// -// This method requires the monitoring.dashboards.list permission -// on the specified project. For more information, see -// Cloud Identity and Access Management (at https://cloud.google.com/iam). -func (c *DashboardsClient) ListDashboards(ctx context.Context, req *dashboardpb.ListDashboardsRequest, opts ...gax.CallOption) *DashboardIterator { +func (c *dashboardsGRPCClient) ListDashboards(ctx context.Context, req *dashboardpb.ListDashboardsRequest, opts ...gax.CallOption) *DashboardIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDashboards[0:len(c.CallOptions.ListDashboards):len(c.CallOptions.ListDashboards)], opts...) + opts = append((*c.CallOptions).ListDashboards[0:len((*c.CallOptions).ListDashboards):len((*c.CallOptions).ListDashboards)], opts...) it := &DashboardIterator{} req = proto.Clone(req).(*dashboardpb.ListDashboardsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*dashboardpb.Dashboard, string, error) { @@ -240,12 +325,7 @@ func (c *DashboardsClient) ListDashboards(ctx context.Context, req *dashboardpb. return it } -// GetDashboard fetches a specific dashboard. -// -// This method requires the monitoring.dashboards.get permission -// on the specified dashboard. For more information, see -// Cloud Identity and Access Management (at https://cloud.google.com/iam). -func (c *DashboardsClient) GetDashboard(ctx context.Context, req *dashboardpb.GetDashboardRequest, opts ...gax.CallOption) (*dashboardpb.Dashboard, error) { +func (c *dashboardsGRPCClient) GetDashboard(ctx context.Context, req *dashboardpb.GetDashboardRequest, opts ...gax.CallOption) (*dashboardpb.Dashboard, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -253,7 +333,7 @@ func (c *DashboardsClient) GetDashboard(ctx context.Context, req *dashboardpb.Ge } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetDashboard[0:len(c.CallOptions.GetDashboard):len(c.CallOptions.GetDashboard)], opts...) + opts = append((*c.CallOptions).GetDashboard[0:len((*c.CallOptions).GetDashboard):len((*c.CallOptions).GetDashboard)], opts...) var resp *dashboardpb.Dashboard err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -266,12 +346,7 @@ func (c *DashboardsClient) GetDashboard(ctx context.Context, req *dashboardpb.Ge return resp, nil } -// DeleteDashboard deletes an existing custom dashboard. -// -// This method requires the monitoring.dashboards.delete permission -// on the specified dashboard. For more information, see -// Cloud Identity and Access Management (at https://cloud.google.com/iam). -func (c *DashboardsClient) DeleteDashboard(ctx context.Context, req *dashboardpb.DeleteDashboardRequest, opts ...gax.CallOption) error { +func (c *dashboardsGRPCClient) DeleteDashboard(ctx context.Context, req *dashboardpb.DeleteDashboardRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -279,7 +354,7 @@ func (c *DashboardsClient) DeleteDashboard(ctx context.Context, req *dashboardpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteDashboard[0:len(c.CallOptions.DeleteDashboard):len(c.CallOptions.DeleteDashboard)], opts...) + opts = append((*c.CallOptions).DeleteDashboard[0:len((*c.CallOptions).DeleteDashboard):len((*c.CallOptions).DeleteDashboard)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.dashboardsClient.DeleteDashboard(ctx, req, settings.GRPC...) @@ -288,12 +363,7 @@ func (c *DashboardsClient) DeleteDashboard(ctx context.Context, req *dashboardpb return err } -// UpdateDashboard replaces an existing custom dashboard with a new definition. -// -// This method requires the monitoring.dashboards.update permission -// on the specified dashboard. For more information, see -// Cloud Identity and Access Management (at https://cloud.google.com/iam). -func (c *DashboardsClient) UpdateDashboard(ctx context.Context, req *dashboardpb.UpdateDashboardRequest, opts ...gax.CallOption) (*dashboardpb.Dashboard, error) { +func (c *dashboardsGRPCClient) UpdateDashboard(ctx context.Context, req *dashboardpb.UpdateDashboardRequest, opts ...gax.CallOption) (*dashboardpb.Dashboard, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -301,7 +371,7 @@ func (c *DashboardsClient) UpdateDashboard(ctx context.Context, req *dashboardpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "dashboard.name", url.QueryEscape(req.GetDashboard().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateDashboard[0:len(c.CallOptions.UpdateDashboard):len(c.CallOptions.UpdateDashboard)], opts...) + opts = append((*c.CallOptions).UpdateDashboard[0:len((*c.CallOptions).UpdateDashboard):len((*c.CallOptions).UpdateDashboard)], opts...) var resp *dashboardpb.Dashboard err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/monitoring/dashboard/apiv1/dashboards_client_example_test.go b/monitoring/dashboard/apiv1/dashboards_client_example_test.go index 995c652f1ba1..717ec3d9da4c 100644 --- a/monitoring/dashboard/apiv1/dashboards_client_example_test.go +++ b/monitoring/dashboard/apiv1/dashboards_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewDashboardsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleDashboardsClient_CreateDashboard() { - // import dashboardpb "google.golang.org/genproto/googleapis/monitoring/dashboard/v1" - ctx := context.Background() c, err := dashboard.NewDashboardsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dashboardpb.CreateDashboardRequest{ // TODO: Fill request struct fields. @@ -55,14 +56,12 @@ func ExampleDashboardsClient_CreateDashboard() { } func ExampleDashboardsClient_ListDashboards() { - // import dashboardpb "google.golang.org/genproto/googleapis/monitoring/dashboard/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := dashboard.NewDashboardsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dashboardpb.ListDashboardsRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleDashboardsClient_ListDashboards() { } func ExampleDashboardsClient_GetDashboard() { - // import dashboardpb "google.golang.org/genproto/googleapis/monitoring/dashboard/v1" - ctx := context.Background() c, err := dashboard.NewDashboardsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dashboardpb.GetDashboardRequest{ // TODO: Fill request struct fields. @@ -107,6 +105,7 @@ func ExampleDashboardsClient_DeleteDashboard() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &dashboardpb.DeleteDashboardRequest{ // TODO: Fill request struct fields. @@ -118,13 +117,12 @@ func ExampleDashboardsClient_DeleteDashboard() { } func ExampleDashboardsClient_UpdateDashboard() { - // import dashboardpb "google.golang.org/genproto/googleapis/monitoring/dashboard/v1" - ctx := context.Background() c, err := dashboard.NewDashboardsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &dashboardpb.UpdateDashboardRequest{ // TODO: Fill request struct fields. diff --git a/monitoring/dashboard/apiv1/doc.go b/monitoring/dashboard/apiv1/doc.go index 93f3e8f4f8f8..ab41e9205b0d 100644 --- a/monitoring/dashboard/apiv1/doc.go +++ b/monitoring/dashboard/apiv1/doc.go @@ -21,8 +21,8 @@ // be associated with a Workspace, with a few exceptions as noted on the // individual method pages. The table entries below are presented in // alphabetical order, not in order of common use. For explanations of the -// concepts found in the table entries, read the [Cloud Monitoring -// documentation](/monitoring/docs). +// concepts found in the table entries, read the Cloud Monitoring +// documentation (at /monitoring/docs). // // Use of Context // @@ -33,7 +33,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package dashboard // import "cloud.google.com/go/monitoring/dashboard/apiv1" import ( @@ -53,7 +53,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/networkconnectivity/apiv1alpha1/doc.go b/networkconnectivity/apiv1alpha1/doc.go index b13a2f32c7f7..f0ef2c31164c 100644 --- a/networkconnectivity/apiv1alpha1/doc.go +++ b/networkconnectivity/apiv1alpha1/doc.go @@ -20,6 +20,8 @@ // The Network Connectivity API will be home to various services which // provide information pertaining to network connectivity. // +// NOTE: This package is in alpha. It is not stable, and is likely to change. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package networkconnectivity // import "cloud.google.com/go/networkconnectivity/apiv1alpha1" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/networkconnectivity/apiv1alpha1/hub_client.go b/networkconnectivity/apiv1alpha1/hub_client.go index 00ade2ab327d..a1cc9d5857c6 100644 --- a/networkconnectivity/apiv1alpha1/hub_client.go +++ b/networkconnectivity/apiv1alpha1/hub_client.go @@ -54,7 +54,7 @@ type HubCallOptions struct { DeleteSpoke []gax.CallOption } -func defaultHubClientOptions() []option.ClientOption { +func defaultHubGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("networkconnectivity.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("networkconnectivity.mtls.googleapis.com:443"), @@ -121,40 +121,191 @@ func defaultHubCallOptions() *HubCallOptions { } } +// internalHubClient is an interface that defines the methods availaible from Network Connectivity API. +type internalHubClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListHubs(context.Context, *networkconnectivitypb.ListHubsRequest, ...gax.CallOption) *HubIterator + GetHub(context.Context, *networkconnectivitypb.GetHubRequest, ...gax.CallOption) (*networkconnectivitypb.Hub, error) + CreateHub(context.Context, *networkconnectivitypb.CreateHubRequest, ...gax.CallOption) (*CreateHubOperation, error) + CreateHubOperation(name string) *CreateHubOperation + UpdateHub(context.Context, *networkconnectivitypb.UpdateHubRequest, ...gax.CallOption) (*UpdateHubOperation, error) + UpdateHubOperation(name string) *UpdateHubOperation + DeleteHub(context.Context, *networkconnectivitypb.DeleteHubRequest, ...gax.CallOption) (*DeleteHubOperation, error) + DeleteHubOperation(name string) *DeleteHubOperation + ListSpokes(context.Context, *networkconnectivitypb.ListSpokesRequest, ...gax.CallOption) *SpokeIterator + GetSpoke(context.Context, *networkconnectivitypb.GetSpokeRequest, ...gax.CallOption) (*networkconnectivitypb.Spoke, error) + CreateSpoke(context.Context, *networkconnectivitypb.CreateSpokeRequest, ...gax.CallOption) (*CreateSpokeOperation, error) + CreateSpokeOperation(name string) *CreateSpokeOperation + UpdateSpoke(context.Context, *networkconnectivitypb.UpdateSpokeRequest, ...gax.CallOption) (*UpdateSpokeOperation, error) + UpdateSpokeOperation(name string) *UpdateSpokeOperation + DeleteSpoke(context.Context, *networkconnectivitypb.DeleteSpokeRequest, ...gax.CallOption) (*DeleteSpokeOperation, error) + DeleteSpokeOperation(name string) *DeleteSpokeOperation +} + // HubClient is a client for interacting with Network Connectivity API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Network Connectivity Center is a hub-and-spoke abstraction for +// network connectivity management in Google Cloud. It reduces +// operational complexity through a simple, centralized connectivity management +// model. type HubClient struct { + // The internal transport-dependent client. + internalClient internalHubClient + + // The call options for this service. + CallOptions *HubCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *HubClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *HubClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *HubClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListHubs lists Hubs in a given project and location. +func (c *HubClient) ListHubs(ctx context.Context, req *networkconnectivitypb.ListHubsRequest, opts ...gax.CallOption) *HubIterator { + return c.internalClient.ListHubs(ctx, req, opts...) +} + +// GetHub gets details of a single Hub. +func (c *HubClient) GetHub(ctx context.Context, req *networkconnectivitypb.GetHubRequest, opts ...gax.CallOption) (*networkconnectivitypb.Hub, error) { + return c.internalClient.GetHub(ctx, req, opts...) +} + +// CreateHub creates a new Hub in a given project and location. +func (c *HubClient) CreateHub(ctx context.Context, req *networkconnectivitypb.CreateHubRequest, opts ...gax.CallOption) (*CreateHubOperation, error) { + return c.internalClient.CreateHub(ctx, req, opts...) +} + +// CreateHubOperation returns a new CreateHubOperation from a given name. +// The name must be that of a previously created CreateHubOperation, possibly from a different process. +func (c *HubClient) CreateHubOperation(name string) *CreateHubOperation { + return c.internalClient.CreateHubOperation(name) +} + +// UpdateHub updates the parameters of a single Hub. +func (c *HubClient) UpdateHub(ctx context.Context, req *networkconnectivitypb.UpdateHubRequest, opts ...gax.CallOption) (*UpdateHubOperation, error) { + return c.internalClient.UpdateHub(ctx, req, opts...) +} + +// UpdateHubOperation returns a new UpdateHubOperation from a given name. +// The name must be that of a previously created UpdateHubOperation, possibly from a different process. +func (c *HubClient) UpdateHubOperation(name string) *UpdateHubOperation { + return c.internalClient.UpdateHubOperation(name) +} + +// DeleteHub deletes a single Hub. +func (c *HubClient) DeleteHub(ctx context.Context, req *networkconnectivitypb.DeleteHubRequest, opts ...gax.CallOption) (*DeleteHubOperation, error) { + return c.internalClient.DeleteHub(ctx, req, opts...) +} + +// DeleteHubOperation returns a new DeleteHubOperation from a given name. +// The name must be that of a previously created DeleteHubOperation, possibly from a different process. +func (c *HubClient) DeleteHubOperation(name string) *DeleteHubOperation { + return c.internalClient.DeleteHubOperation(name) +} + +// ListSpokes lists Spokes in a given project and location. +func (c *HubClient) ListSpokes(ctx context.Context, req *networkconnectivitypb.ListSpokesRequest, opts ...gax.CallOption) *SpokeIterator { + return c.internalClient.ListSpokes(ctx, req, opts...) +} + +// GetSpoke gets details of a single Spoke. +func (c *HubClient) GetSpoke(ctx context.Context, req *networkconnectivitypb.GetSpokeRequest, opts ...gax.CallOption) (*networkconnectivitypb.Spoke, error) { + return c.internalClient.GetSpoke(ctx, req, opts...) +} + +// CreateSpoke creates a new Spoke in a given project and location. +func (c *HubClient) CreateSpoke(ctx context.Context, req *networkconnectivitypb.CreateSpokeRequest, opts ...gax.CallOption) (*CreateSpokeOperation, error) { + return c.internalClient.CreateSpoke(ctx, req, opts...) +} + +// CreateSpokeOperation returns a new CreateSpokeOperation from a given name. +// The name must be that of a previously created CreateSpokeOperation, possibly from a different process. +func (c *HubClient) CreateSpokeOperation(name string) *CreateSpokeOperation { + return c.internalClient.CreateSpokeOperation(name) +} + +// UpdateSpoke updates the parameters of a single Spoke. +func (c *HubClient) UpdateSpoke(ctx context.Context, req *networkconnectivitypb.UpdateSpokeRequest, opts ...gax.CallOption) (*UpdateSpokeOperation, error) { + return c.internalClient.UpdateSpoke(ctx, req, opts...) +} + +// UpdateSpokeOperation returns a new UpdateSpokeOperation from a given name. +// The name must be that of a previously created UpdateSpokeOperation, possibly from a different process. +func (c *HubClient) UpdateSpokeOperation(name string) *UpdateSpokeOperation { + return c.internalClient.UpdateSpokeOperation(name) +} + +// DeleteSpoke deletes a single Spoke. +func (c *HubClient) DeleteSpoke(ctx context.Context, req *networkconnectivitypb.DeleteSpokeRequest, opts ...gax.CallOption) (*DeleteSpokeOperation, error) { + return c.internalClient.DeleteSpoke(ctx, req, opts...) +} + +// DeleteSpokeOperation returns a new DeleteSpokeOperation from a given name. +// The name must be that of a previously created DeleteSpokeOperation, possibly from a different process. +func (c *HubClient) DeleteSpokeOperation(name string) *DeleteSpokeOperation { + return c.internalClient.DeleteSpokeOperation(name) +} + +// hubGRPCClient is a client for interacting with Network Connectivity API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type hubGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing HubClient + CallOptions **HubCallOptions + // The gRPC API client. hubClient networkconnectivitypb.HubServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *HubCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewHubClient creates a new hub service client. +// NewHubClient creates a new hub service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Network Connectivity Center is a hub-and-spoke abstraction for // network connectivity management in Google Cloud. It reduces // operational complexity through a simple, centralized connectivity management // model. func NewHubClient(ctx context.Context, opts ...option.ClientOption) (*HubClient, error) { - clientOpts := defaultHubClientOptions() - + clientOpts := defaultHubGRPCClientOptions() if newHubClientHook != nil { hookOpts, err := newHubClientHook(ctx, clientHookParams{}) if err != nil { @@ -172,16 +323,19 @@ func NewHubClient(ctx context.Context, opts ...option.ClientOption) (*HubClient, if err != nil { return nil, err } - c := &HubClient{ + client := HubClient{CallOptions: defaultHubCallOptions()} + + c := &hubGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultHubCallOptions(), - - hubClient: networkconnectivitypb.NewHubServiceClient(connPool), + hubClient: networkconnectivitypb.NewHubServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -191,36 +345,36 @@ func NewHubClient(ctx context.Context, opts ...option.ClientOption) (*HubClient, // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *HubClient) Connection() *grpc.ClientConn { +func (c *hubGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *HubClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *HubClient) setGoogleClientInfo(keyval ...string) { +func (c *hubGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListHubs lists Hubs in a given project and location. -func (c *HubClient) ListHubs(ctx context.Context, req *networkconnectivitypb.ListHubsRequest, opts ...gax.CallOption) *HubIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *hubGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *hubGRPCClient) ListHubs(ctx context.Context, req *networkconnectivitypb.ListHubsRequest, opts ...gax.CallOption) *HubIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListHubs[0:len(c.CallOptions.ListHubs):len(c.CallOptions.ListHubs)], opts...) + opts = append((*c.CallOptions).ListHubs[0:len((*c.CallOptions).ListHubs):len((*c.CallOptions).ListHubs)], opts...) it := &HubIterator{} req = proto.Clone(req).(*networkconnectivitypb.ListHubsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*networkconnectivitypb.Hub, string, error) { @@ -257,8 +411,7 @@ func (c *HubClient) ListHubs(ctx context.Context, req *networkconnectivitypb.Lis return it } -// GetHub gets details of a single Hub. -func (c *HubClient) GetHub(ctx context.Context, req *networkconnectivitypb.GetHubRequest, opts ...gax.CallOption) (*networkconnectivitypb.Hub, error) { +func (c *hubGRPCClient) GetHub(ctx context.Context, req *networkconnectivitypb.GetHubRequest, opts ...gax.CallOption) (*networkconnectivitypb.Hub, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -266,7 +419,7 @@ func (c *HubClient) GetHub(ctx context.Context, req *networkconnectivitypb.GetHu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetHub[0:len(c.CallOptions.GetHub):len(c.CallOptions.GetHub)], opts...) + opts = append((*c.CallOptions).GetHub[0:len((*c.CallOptions).GetHub):len((*c.CallOptions).GetHub)], opts...) var resp *networkconnectivitypb.Hub err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -279,8 +432,7 @@ func (c *HubClient) GetHub(ctx context.Context, req *networkconnectivitypb.GetHu return resp, nil } -// CreateHub creates a new Hub in a given project and location. -func (c *HubClient) CreateHub(ctx context.Context, req *networkconnectivitypb.CreateHubRequest, opts ...gax.CallOption) (*CreateHubOperation, error) { +func (c *hubGRPCClient) CreateHub(ctx context.Context, req *networkconnectivitypb.CreateHubRequest, opts ...gax.CallOption) (*CreateHubOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -288,7 +440,7 @@ func (c *HubClient) CreateHub(ctx context.Context, req *networkconnectivitypb.Cr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateHub[0:len(c.CallOptions.CreateHub):len(c.CallOptions.CreateHub)], opts...) + opts = append((*c.CallOptions).CreateHub[0:len((*c.CallOptions).CreateHub):len((*c.CallOptions).CreateHub)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -299,12 +451,11 @@ func (c *HubClient) CreateHub(ctx context.Context, req *networkconnectivitypb.Cr return nil, err } return &CreateHubOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateHub updates the parameters of a single Hub. -func (c *HubClient) UpdateHub(ctx context.Context, req *networkconnectivitypb.UpdateHubRequest, opts ...gax.CallOption) (*UpdateHubOperation, error) { +func (c *hubGRPCClient) UpdateHub(ctx context.Context, req *networkconnectivitypb.UpdateHubRequest, opts ...gax.CallOption) (*UpdateHubOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -312,7 +463,7 @@ func (c *HubClient) UpdateHub(ctx context.Context, req *networkconnectivitypb.Up } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "hub.name", url.QueryEscape(req.GetHub().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateHub[0:len(c.CallOptions.UpdateHub):len(c.CallOptions.UpdateHub)], opts...) + opts = append((*c.CallOptions).UpdateHub[0:len((*c.CallOptions).UpdateHub):len((*c.CallOptions).UpdateHub)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -323,12 +474,11 @@ func (c *HubClient) UpdateHub(ctx context.Context, req *networkconnectivitypb.Up return nil, err } return &UpdateHubOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteHub deletes a single Hub. -func (c *HubClient) DeleteHub(ctx context.Context, req *networkconnectivitypb.DeleteHubRequest, opts ...gax.CallOption) (*DeleteHubOperation, error) { +func (c *hubGRPCClient) DeleteHub(ctx context.Context, req *networkconnectivitypb.DeleteHubRequest, opts ...gax.CallOption) (*DeleteHubOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -336,7 +486,7 @@ func (c *HubClient) DeleteHub(ctx context.Context, req *networkconnectivitypb.De } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteHub[0:len(c.CallOptions.DeleteHub):len(c.CallOptions.DeleteHub)], opts...) + opts = append((*c.CallOptions).DeleteHub[0:len((*c.CallOptions).DeleteHub):len((*c.CallOptions).DeleteHub)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -347,15 +497,14 @@ func (c *HubClient) DeleteHub(ctx context.Context, req *networkconnectivitypb.De return nil, err } return &DeleteHubOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListSpokes lists Spokes in a given project and location. -func (c *HubClient) ListSpokes(ctx context.Context, req *networkconnectivitypb.ListSpokesRequest, opts ...gax.CallOption) *SpokeIterator { +func (c *hubGRPCClient) ListSpokes(ctx context.Context, req *networkconnectivitypb.ListSpokesRequest, opts ...gax.CallOption) *SpokeIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSpokes[0:len(c.CallOptions.ListSpokes):len(c.CallOptions.ListSpokes)], opts...) + opts = append((*c.CallOptions).ListSpokes[0:len((*c.CallOptions).ListSpokes):len((*c.CallOptions).ListSpokes)], opts...) it := &SpokeIterator{} req = proto.Clone(req).(*networkconnectivitypb.ListSpokesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*networkconnectivitypb.Spoke, string, error) { @@ -392,8 +541,7 @@ func (c *HubClient) ListSpokes(ctx context.Context, req *networkconnectivitypb.L return it } -// GetSpoke gets details of a single Spoke. -func (c *HubClient) GetSpoke(ctx context.Context, req *networkconnectivitypb.GetSpokeRequest, opts ...gax.CallOption) (*networkconnectivitypb.Spoke, error) { +func (c *hubGRPCClient) GetSpoke(ctx context.Context, req *networkconnectivitypb.GetSpokeRequest, opts ...gax.CallOption) (*networkconnectivitypb.Spoke, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -401,7 +549,7 @@ func (c *HubClient) GetSpoke(ctx context.Context, req *networkconnectivitypb.Get } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSpoke[0:len(c.CallOptions.GetSpoke):len(c.CallOptions.GetSpoke)], opts...) + opts = append((*c.CallOptions).GetSpoke[0:len((*c.CallOptions).GetSpoke):len((*c.CallOptions).GetSpoke)], opts...) var resp *networkconnectivitypb.Spoke err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -414,8 +562,7 @@ func (c *HubClient) GetSpoke(ctx context.Context, req *networkconnectivitypb.Get return resp, nil } -// CreateSpoke creates a new Spoke in a given project and location. -func (c *HubClient) CreateSpoke(ctx context.Context, req *networkconnectivitypb.CreateSpokeRequest, opts ...gax.CallOption) (*CreateSpokeOperation, error) { +func (c *hubGRPCClient) CreateSpoke(ctx context.Context, req *networkconnectivitypb.CreateSpokeRequest, opts ...gax.CallOption) (*CreateSpokeOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -423,7 +570,7 @@ func (c *HubClient) CreateSpoke(ctx context.Context, req *networkconnectivitypb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSpoke[0:len(c.CallOptions.CreateSpoke):len(c.CallOptions.CreateSpoke)], opts...) + opts = append((*c.CallOptions).CreateSpoke[0:len((*c.CallOptions).CreateSpoke):len((*c.CallOptions).CreateSpoke)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -434,12 +581,11 @@ func (c *HubClient) CreateSpoke(ctx context.Context, req *networkconnectivitypb. return nil, err } return &CreateSpokeOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateSpoke updates the parameters of a single Spoke. -func (c *HubClient) UpdateSpoke(ctx context.Context, req *networkconnectivitypb.UpdateSpokeRequest, opts ...gax.CallOption) (*UpdateSpokeOperation, error) { +func (c *hubGRPCClient) UpdateSpoke(ctx context.Context, req *networkconnectivitypb.UpdateSpokeRequest, opts ...gax.CallOption) (*UpdateSpokeOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -447,7 +593,7 @@ func (c *HubClient) UpdateSpoke(ctx context.Context, req *networkconnectivitypb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "spoke.name", url.QueryEscape(req.GetSpoke().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSpoke[0:len(c.CallOptions.UpdateSpoke):len(c.CallOptions.UpdateSpoke)], opts...) + opts = append((*c.CallOptions).UpdateSpoke[0:len((*c.CallOptions).UpdateSpoke):len((*c.CallOptions).UpdateSpoke)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -458,12 +604,11 @@ func (c *HubClient) UpdateSpoke(ctx context.Context, req *networkconnectivitypb. return nil, err } return &UpdateSpokeOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteSpoke deletes a single Spoke. -func (c *HubClient) DeleteSpoke(ctx context.Context, req *networkconnectivitypb.DeleteSpokeRequest, opts ...gax.CallOption) (*DeleteSpokeOperation, error) { +func (c *hubGRPCClient) DeleteSpoke(ctx context.Context, req *networkconnectivitypb.DeleteSpokeRequest, opts ...gax.CallOption) (*DeleteSpokeOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -471,7 +616,7 @@ func (c *HubClient) DeleteSpoke(ctx context.Context, req *networkconnectivitypb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteSpoke[0:len(c.CallOptions.DeleteSpoke):len(c.CallOptions.DeleteSpoke)], opts...) + opts = append((*c.CallOptions).DeleteSpoke[0:len((*c.CallOptions).DeleteSpoke):len((*c.CallOptions).DeleteSpoke)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -482,7 +627,7 @@ func (c *HubClient) DeleteSpoke(ctx context.Context, req *networkconnectivitypb. return nil, err } return &DeleteSpokeOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -493,9 +638,9 @@ type CreateHubOperation struct { // CreateHubOperation returns a new CreateHubOperation from a given name. // The name must be that of a previously created CreateHubOperation, possibly from a different process. -func (c *HubClient) CreateHubOperation(name string) *CreateHubOperation { +func (c *hubGRPCClient) CreateHubOperation(name string) *CreateHubOperation { return &CreateHubOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -562,9 +707,9 @@ type CreateSpokeOperation struct { // CreateSpokeOperation returns a new CreateSpokeOperation from a given name. // The name must be that of a previously created CreateSpokeOperation, possibly from a different process. -func (c *HubClient) CreateSpokeOperation(name string) *CreateSpokeOperation { +func (c *hubGRPCClient) CreateSpokeOperation(name string) *CreateSpokeOperation { return &CreateSpokeOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -631,9 +776,9 @@ type DeleteHubOperation struct { // DeleteHubOperation returns a new DeleteHubOperation from a given name. // The name must be that of a previously created DeleteHubOperation, possibly from a different process. -func (c *HubClient) DeleteHubOperation(name string) *DeleteHubOperation { +func (c *hubGRPCClient) DeleteHubOperation(name string) *DeleteHubOperation { return &DeleteHubOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -689,9 +834,9 @@ type DeleteSpokeOperation struct { // DeleteSpokeOperation returns a new DeleteSpokeOperation from a given name. // The name must be that of a previously created DeleteSpokeOperation, possibly from a different process. -func (c *HubClient) DeleteSpokeOperation(name string) *DeleteSpokeOperation { +func (c *hubGRPCClient) DeleteSpokeOperation(name string) *DeleteSpokeOperation { return &DeleteSpokeOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -747,9 +892,9 @@ type UpdateHubOperation struct { // UpdateHubOperation returns a new UpdateHubOperation from a given name. // The name must be that of a previously created UpdateHubOperation, possibly from a different process. -func (c *HubClient) UpdateHubOperation(name string) *UpdateHubOperation { +func (c *hubGRPCClient) UpdateHubOperation(name string) *UpdateHubOperation { return &UpdateHubOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -816,9 +961,9 @@ type UpdateSpokeOperation struct { // UpdateSpokeOperation returns a new UpdateSpokeOperation from a given name. // The name must be that of a previously created UpdateSpokeOperation, possibly from a different process. -func (c *HubClient) UpdateSpokeOperation(name string) *UpdateSpokeOperation { +func (c *hubGRPCClient) UpdateSpokeOperation(name string) *UpdateSpokeOperation { return &UpdateSpokeOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/networkconnectivity/apiv1alpha1/hub_client_example_test.go b/networkconnectivity/apiv1alpha1/hub_client_example_test.go index 9c374de57752..f9d4c24a1f84 100644 --- a/networkconnectivity/apiv1alpha1/hub_client_example_test.go +++ b/networkconnectivity/apiv1alpha1/hub_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewHubClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleHubClient_ListHubs() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.ListHubsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleHubClient_ListHubs() { } func ExampleHubClient_GetHub() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.GetHubRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleHubClient_GetHub() { } func ExampleHubClient_CreateHub() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.CreateHubRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleHubClient_CreateHub() { } func ExampleHubClient_UpdateHub() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.UpdateHubRequest{ // TODO: Fill request struct fields. @@ -132,13 +129,12 @@ func ExampleHubClient_UpdateHub() { } func ExampleHubClient_DeleteHub() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.DeleteHubRequest{ // TODO: Fill request struct fields. @@ -155,14 +151,12 @@ func ExampleHubClient_DeleteHub() { } func ExampleHubClient_ListSpokes() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.ListSpokesRequest{ // TODO: Fill request struct fields. @@ -182,13 +176,12 @@ func ExampleHubClient_ListSpokes() { } func ExampleHubClient_GetSpoke() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.GetSpokeRequest{ // TODO: Fill request struct fields. @@ -202,13 +195,12 @@ func ExampleHubClient_GetSpoke() { } func ExampleHubClient_CreateSpoke() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.CreateSpokeRequest{ // TODO: Fill request struct fields. @@ -227,13 +219,12 @@ func ExampleHubClient_CreateSpoke() { } func ExampleHubClient_UpdateSpoke() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.UpdateSpokeRequest{ // TODO: Fill request struct fields. @@ -252,13 +243,12 @@ func ExampleHubClient_UpdateSpoke() { } func ExampleHubClient_DeleteSpoke() { - // import networkconnectivitypb "google.golang.org/genproto/googleapis/cloud/networkconnectivity/v1alpha1" - ctx := context.Background() c, err := networkconnectivity.NewHubClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &networkconnectivitypb.DeleteSpokeRequest{ // TODO: Fill request struct fields. diff --git a/notebooks/apiv1beta1/doc.go b/notebooks/apiv1beta1/doc.go index 66e398595d0f..cd1a3d2a7cbc 100644 --- a/notebooks/apiv1beta1/doc.go +++ b/notebooks/apiv1beta1/doc.go @@ -20,6 +20,8 @@ // AI Platform Notebooks API is used to manage notebook resources in Google // Cloud. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package notebooks // import "cloud.google.com/go/notebooks/apiv1beta1" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/notebooks/apiv1beta1/notebook_client.go b/notebooks/apiv1beta1/notebook_client.go index ff054e5a7404..375e584215ba 100644 --- a/notebooks/apiv1beta1/notebook_client.go +++ b/notebooks/apiv1beta1/notebook_client.go @@ -62,7 +62,7 @@ type NotebookCallOptions struct { DeleteEnvironment []gax.CallOption } -func defaultNotebookClientOptions() []option.ClientOption { +func defaultNotebookGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("notebooks.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("notebooks.mtls.googleapis.com:443"), @@ -98,37 +98,302 @@ func defaultNotebookCallOptions() *NotebookCallOptions { } } +// internalNotebookClient is an interface that defines the methods availaible from Notebooks API. +type internalNotebookClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListInstances(context.Context, *notebookspb.ListInstancesRequest, ...gax.CallOption) *InstanceIterator + GetInstance(context.Context, *notebookspb.GetInstanceRequest, ...gax.CallOption) (*notebookspb.Instance, error) + CreateInstance(context.Context, *notebookspb.CreateInstanceRequest, ...gax.CallOption) (*CreateInstanceOperation, error) + CreateInstanceOperation(name string) *CreateInstanceOperation + RegisterInstance(context.Context, *notebookspb.RegisterInstanceRequest, ...gax.CallOption) (*RegisterInstanceOperation, error) + RegisterInstanceOperation(name string) *RegisterInstanceOperation + SetInstanceAccelerator(context.Context, *notebookspb.SetInstanceAcceleratorRequest, ...gax.CallOption) (*SetInstanceAcceleratorOperation, error) + SetInstanceAcceleratorOperation(name string) *SetInstanceAcceleratorOperation + SetInstanceMachineType(context.Context, *notebookspb.SetInstanceMachineTypeRequest, ...gax.CallOption) (*SetInstanceMachineTypeOperation, error) + SetInstanceMachineTypeOperation(name string) *SetInstanceMachineTypeOperation + SetInstanceLabels(context.Context, *notebookspb.SetInstanceLabelsRequest, ...gax.CallOption) (*SetInstanceLabelsOperation, error) + SetInstanceLabelsOperation(name string) *SetInstanceLabelsOperation + DeleteInstance(context.Context, *notebookspb.DeleteInstanceRequest, ...gax.CallOption) (*DeleteInstanceOperation, error) + DeleteInstanceOperation(name string) *DeleteInstanceOperation + StartInstance(context.Context, *notebookspb.StartInstanceRequest, ...gax.CallOption) (*StartInstanceOperation, error) + StartInstanceOperation(name string) *StartInstanceOperation + StopInstance(context.Context, *notebookspb.StopInstanceRequest, ...gax.CallOption) (*StopInstanceOperation, error) + StopInstanceOperation(name string) *StopInstanceOperation + ResetInstance(context.Context, *notebookspb.ResetInstanceRequest, ...gax.CallOption) (*ResetInstanceOperation, error) + ResetInstanceOperation(name string) *ResetInstanceOperation + ReportInstanceInfo(context.Context, *notebookspb.ReportInstanceInfoRequest, ...gax.CallOption) (*ReportInstanceInfoOperation, error) + ReportInstanceInfoOperation(name string) *ReportInstanceInfoOperation + IsInstanceUpgradeable(context.Context, *notebookspb.IsInstanceUpgradeableRequest, ...gax.CallOption) (*notebookspb.IsInstanceUpgradeableResponse, error) + UpgradeInstance(context.Context, *notebookspb.UpgradeInstanceRequest, ...gax.CallOption) (*UpgradeInstanceOperation, error) + UpgradeInstanceOperation(name string) *UpgradeInstanceOperation + UpgradeInstanceInternal(context.Context, *notebookspb.UpgradeInstanceInternalRequest, ...gax.CallOption) (*UpgradeInstanceInternalOperation, error) + UpgradeInstanceInternalOperation(name string) *UpgradeInstanceInternalOperation + ListEnvironments(context.Context, *notebookspb.ListEnvironmentsRequest, ...gax.CallOption) *EnvironmentIterator + GetEnvironment(context.Context, *notebookspb.GetEnvironmentRequest, ...gax.CallOption) (*notebookspb.Environment, error) + CreateEnvironment(context.Context, *notebookspb.CreateEnvironmentRequest, ...gax.CallOption) (*CreateEnvironmentOperation, error) + CreateEnvironmentOperation(name string) *CreateEnvironmentOperation + DeleteEnvironment(context.Context, *notebookspb.DeleteEnvironmentRequest, ...gax.CallOption) (*DeleteEnvironmentOperation, error) + DeleteEnvironmentOperation(name string) *DeleteEnvironmentOperation +} + // NotebookClient is a client for interacting with Notebooks API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// API v1beta1 service for Cloud AI Platform Notebooks. type NotebookClient struct { + // The internal transport-dependent client. + internalClient internalNotebookClient + + // The call options for this service. + CallOptions *NotebookCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *NotebookClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *NotebookClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *NotebookClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListInstances lists instances in a given project and location. +func (c *NotebookClient) ListInstances(ctx context.Context, req *notebookspb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { + return c.internalClient.ListInstances(ctx, req, opts...) +} + +// GetInstance gets details of a single Instance. +func (c *NotebookClient) GetInstance(ctx context.Context, req *notebookspb.GetInstanceRequest, opts ...gax.CallOption) (*notebookspb.Instance, error) { + return c.internalClient.GetInstance(ctx, req, opts...) +} + +// CreateInstance creates a new Instance in a given project and location. +func (c *NotebookClient) CreateInstance(ctx context.Context, req *notebookspb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { + return c.internalClient.CreateInstance(ctx, req, opts...) +} + +// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. +// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. +func (c *NotebookClient) CreateInstanceOperation(name string) *CreateInstanceOperation { + return c.internalClient.CreateInstanceOperation(name) +} + +// RegisterInstance registers an existing legacy notebook instance to the Notebooks API server. +// Legacy instances are instances created with the legacy Compute Engine +// calls. They are not manageable by the Notebooks API out of the box. This +// call makes these instances manageable by the Notebooks API. +func (c *NotebookClient) RegisterInstance(ctx context.Context, req *notebookspb.RegisterInstanceRequest, opts ...gax.CallOption) (*RegisterInstanceOperation, error) { + return c.internalClient.RegisterInstance(ctx, req, opts...) +} + +// RegisterInstanceOperation returns a new RegisterInstanceOperation from a given name. +// The name must be that of a previously created RegisterInstanceOperation, possibly from a different process. +func (c *NotebookClient) RegisterInstanceOperation(name string) *RegisterInstanceOperation { + return c.internalClient.RegisterInstanceOperation(name) +} + +// SetInstanceAccelerator updates the guest accelerators of a single Instance. +func (c *NotebookClient) SetInstanceAccelerator(ctx context.Context, req *notebookspb.SetInstanceAcceleratorRequest, opts ...gax.CallOption) (*SetInstanceAcceleratorOperation, error) { + return c.internalClient.SetInstanceAccelerator(ctx, req, opts...) +} + +// SetInstanceAcceleratorOperation returns a new SetInstanceAcceleratorOperation from a given name. +// The name must be that of a previously created SetInstanceAcceleratorOperation, possibly from a different process. +func (c *NotebookClient) SetInstanceAcceleratorOperation(name string) *SetInstanceAcceleratorOperation { + return c.internalClient.SetInstanceAcceleratorOperation(name) +} + +// SetInstanceMachineType updates the machine type of a single Instance. +func (c *NotebookClient) SetInstanceMachineType(ctx context.Context, req *notebookspb.SetInstanceMachineTypeRequest, opts ...gax.CallOption) (*SetInstanceMachineTypeOperation, error) { + return c.internalClient.SetInstanceMachineType(ctx, req, opts...) +} + +// SetInstanceMachineTypeOperation returns a new SetInstanceMachineTypeOperation from a given name. +// The name must be that of a previously created SetInstanceMachineTypeOperation, possibly from a different process. +func (c *NotebookClient) SetInstanceMachineTypeOperation(name string) *SetInstanceMachineTypeOperation { + return c.internalClient.SetInstanceMachineTypeOperation(name) +} + +// SetInstanceLabels updates the labels of an Instance. +func (c *NotebookClient) SetInstanceLabels(ctx context.Context, req *notebookspb.SetInstanceLabelsRequest, opts ...gax.CallOption) (*SetInstanceLabelsOperation, error) { + return c.internalClient.SetInstanceLabels(ctx, req, opts...) +} + +// SetInstanceLabelsOperation returns a new SetInstanceLabelsOperation from a given name. +// The name must be that of a previously created SetInstanceLabelsOperation, possibly from a different process. +func (c *NotebookClient) SetInstanceLabelsOperation(name string) *SetInstanceLabelsOperation { + return c.internalClient.SetInstanceLabelsOperation(name) +} + +// DeleteInstance deletes a single Instance. +func (c *NotebookClient) DeleteInstance(ctx context.Context, req *notebookspb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { + return c.internalClient.DeleteInstance(ctx, req, opts...) +} + +// DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. +// The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. +func (c *NotebookClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { + return c.internalClient.DeleteInstanceOperation(name) +} + +// StartInstance starts a notebook instance. +func (c *NotebookClient) StartInstance(ctx context.Context, req *notebookspb.StartInstanceRequest, opts ...gax.CallOption) (*StartInstanceOperation, error) { + return c.internalClient.StartInstance(ctx, req, opts...) +} + +// StartInstanceOperation returns a new StartInstanceOperation from a given name. +// The name must be that of a previously created StartInstanceOperation, possibly from a different process. +func (c *NotebookClient) StartInstanceOperation(name string) *StartInstanceOperation { + return c.internalClient.StartInstanceOperation(name) +} + +// StopInstance stops a notebook instance. +func (c *NotebookClient) StopInstance(ctx context.Context, req *notebookspb.StopInstanceRequest, opts ...gax.CallOption) (*StopInstanceOperation, error) { + return c.internalClient.StopInstance(ctx, req, opts...) +} + +// StopInstanceOperation returns a new StopInstanceOperation from a given name. +// The name must be that of a previously created StopInstanceOperation, possibly from a different process. +func (c *NotebookClient) StopInstanceOperation(name string) *StopInstanceOperation { + return c.internalClient.StopInstanceOperation(name) +} + +// ResetInstance resets a notebook instance. +func (c *NotebookClient) ResetInstance(ctx context.Context, req *notebookspb.ResetInstanceRequest, opts ...gax.CallOption) (*ResetInstanceOperation, error) { + return c.internalClient.ResetInstance(ctx, req, opts...) +} + +// ResetInstanceOperation returns a new ResetInstanceOperation from a given name. +// The name must be that of a previously created ResetInstanceOperation, possibly from a different process. +func (c *NotebookClient) ResetInstanceOperation(name string) *ResetInstanceOperation { + return c.internalClient.ResetInstanceOperation(name) +} + +// ReportInstanceInfo allows notebook instances to +// report their latest instance information to the Notebooks +// API server. The server will merge the reported information to +// the instance metadata store. Do not use this method directly. +func (c *NotebookClient) ReportInstanceInfo(ctx context.Context, req *notebookspb.ReportInstanceInfoRequest, opts ...gax.CallOption) (*ReportInstanceInfoOperation, error) { + return c.internalClient.ReportInstanceInfo(ctx, req, opts...) +} + +// ReportInstanceInfoOperation returns a new ReportInstanceInfoOperation from a given name. +// The name must be that of a previously created ReportInstanceInfoOperation, possibly from a different process. +func (c *NotebookClient) ReportInstanceInfoOperation(name string) *ReportInstanceInfoOperation { + return c.internalClient.ReportInstanceInfoOperation(name) +} + +// IsInstanceUpgradeable check if a notebook instance is upgradable. +func (c *NotebookClient) IsInstanceUpgradeable(ctx context.Context, req *notebookspb.IsInstanceUpgradeableRequest, opts ...gax.CallOption) (*notebookspb.IsInstanceUpgradeableResponse, error) { + return c.internalClient.IsInstanceUpgradeable(ctx, req, opts...) +} + +// UpgradeInstance upgrades a notebook instance to the latest version. +func (c *NotebookClient) UpgradeInstance(ctx context.Context, req *notebookspb.UpgradeInstanceRequest, opts ...gax.CallOption) (*UpgradeInstanceOperation, error) { + return c.internalClient.UpgradeInstance(ctx, req, opts...) +} + +// UpgradeInstanceOperation returns a new UpgradeInstanceOperation from a given name. +// The name must be that of a previously created UpgradeInstanceOperation, possibly from a different process. +func (c *NotebookClient) UpgradeInstanceOperation(name string) *UpgradeInstanceOperation { + return c.internalClient.UpgradeInstanceOperation(name) +} + +// UpgradeInstanceInternal allows notebook instances to +// call this endpoint to upgrade themselves. Do not use this method directly. +func (c *NotebookClient) UpgradeInstanceInternal(ctx context.Context, req *notebookspb.UpgradeInstanceInternalRequest, opts ...gax.CallOption) (*UpgradeInstanceInternalOperation, error) { + return c.internalClient.UpgradeInstanceInternal(ctx, req, opts...) +} + +// UpgradeInstanceInternalOperation returns a new UpgradeInstanceInternalOperation from a given name. +// The name must be that of a previously created UpgradeInstanceInternalOperation, possibly from a different process. +func (c *NotebookClient) UpgradeInstanceInternalOperation(name string) *UpgradeInstanceInternalOperation { + return c.internalClient.UpgradeInstanceInternalOperation(name) +} + +// ListEnvironments lists environments in a project. +func (c *NotebookClient) ListEnvironments(ctx context.Context, req *notebookspb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { + return c.internalClient.ListEnvironments(ctx, req, opts...) +} + +// GetEnvironment gets details of a single Environment. +func (c *NotebookClient) GetEnvironment(ctx context.Context, req *notebookspb.GetEnvironmentRequest, opts ...gax.CallOption) (*notebookspb.Environment, error) { + return c.internalClient.GetEnvironment(ctx, req, opts...) +} + +// CreateEnvironment creates a new Environment. +func (c *NotebookClient) CreateEnvironment(ctx context.Context, req *notebookspb.CreateEnvironmentRequest, opts ...gax.CallOption) (*CreateEnvironmentOperation, error) { + return c.internalClient.CreateEnvironment(ctx, req, opts...) +} + +// CreateEnvironmentOperation returns a new CreateEnvironmentOperation from a given name. +// The name must be that of a previously created CreateEnvironmentOperation, possibly from a different process. +func (c *NotebookClient) CreateEnvironmentOperation(name string) *CreateEnvironmentOperation { + return c.internalClient.CreateEnvironmentOperation(name) +} + +// DeleteEnvironment deletes a single Environment. +func (c *NotebookClient) DeleteEnvironment(ctx context.Context, req *notebookspb.DeleteEnvironmentRequest, opts ...gax.CallOption) (*DeleteEnvironmentOperation, error) { + return c.internalClient.DeleteEnvironment(ctx, req, opts...) +} + +// DeleteEnvironmentOperation returns a new DeleteEnvironmentOperation from a given name. +// The name must be that of a previously created DeleteEnvironmentOperation, possibly from a different process. +func (c *NotebookClient) DeleteEnvironmentOperation(name string) *DeleteEnvironmentOperation { + return c.internalClient.DeleteEnvironmentOperation(name) +} + +// notebookGRPCClient is a client for interacting with Notebooks API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type notebookGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing NotebookClient + CallOptions **NotebookCallOptions + // The gRPC API client. notebookClient notebookspb.NotebookServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *NotebookCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewNotebookClient creates a new notebook service client. +// NewNotebookClient creates a new notebook service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // API v1beta1 service for Cloud AI Platform Notebooks. func NewNotebookClient(ctx context.Context, opts ...option.ClientOption) (*NotebookClient, error) { - clientOpts := defaultNotebookClientOptions() - + clientOpts := defaultNotebookGRPCClientOptions() if newNotebookClientHook != nil { hookOpts, err := newNotebookClientHook(ctx, clientHookParams{}) if err != nil { @@ -146,16 +411,19 @@ func NewNotebookClient(ctx context.Context, opts ...option.ClientOption) (*Noteb if err != nil { return nil, err } - c := &NotebookClient{ + client := NotebookClient{CallOptions: defaultNotebookCallOptions()} + + c := ¬ebookGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultNotebookCallOptions(), - - notebookClient: notebookspb.NewNotebookServiceClient(connPool), + notebookClient: notebookspb.NewNotebookServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -165,36 +433,36 @@ func NewNotebookClient(ctx context.Context, opts ...option.ClientOption) (*Noteb // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *NotebookClient) Connection() *grpc.ClientConn { +func (c *notebookGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *NotebookClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *NotebookClient) setGoogleClientInfo(keyval ...string) { +func (c *notebookGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListInstances lists instances in a given project and location. -func (c *NotebookClient) ListInstances(ctx context.Context, req *notebookspb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *notebookGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *notebookGRPCClient) ListInstances(ctx context.Context, req *notebookspb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListInstances[0:len(c.CallOptions.ListInstances):len(c.CallOptions.ListInstances)], opts...) + opts = append((*c.CallOptions).ListInstances[0:len((*c.CallOptions).ListInstances):len((*c.CallOptions).ListInstances)], opts...) it := &InstanceIterator{} req = proto.Clone(req).(*notebookspb.ListInstancesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*notebookspb.Instance, string, error) { @@ -231,8 +499,7 @@ func (c *NotebookClient) ListInstances(ctx context.Context, req *notebookspb.Lis return it } -// GetInstance gets details of a single Instance. -func (c *NotebookClient) GetInstance(ctx context.Context, req *notebookspb.GetInstanceRequest, opts ...gax.CallOption) (*notebookspb.Instance, error) { +func (c *notebookGRPCClient) GetInstance(ctx context.Context, req *notebookspb.GetInstanceRequest, opts ...gax.CallOption) (*notebookspb.Instance, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -240,7 +507,7 @@ func (c *NotebookClient) GetInstance(ctx context.Context, req *notebookspb.GetIn } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetInstance[0:len(c.CallOptions.GetInstance):len(c.CallOptions.GetInstance)], opts...) + opts = append((*c.CallOptions).GetInstance[0:len((*c.CallOptions).GetInstance):len((*c.CallOptions).GetInstance)], opts...) var resp *notebookspb.Instance err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -253,8 +520,7 @@ func (c *NotebookClient) GetInstance(ctx context.Context, req *notebookspb.GetIn return resp, nil } -// CreateInstance creates a new Instance in a given project and location. -func (c *NotebookClient) CreateInstance(ctx context.Context, req *notebookspb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { +func (c *notebookGRPCClient) CreateInstance(ctx context.Context, req *notebookspb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -262,7 +528,7 @@ func (c *NotebookClient) CreateInstance(ctx context.Context, req *notebookspb.Cr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateInstance[0:len(c.CallOptions.CreateInstance):len(c.CallOptions.CreateInstance)], opts...) + opts = append((*c.CallOptions).CreateInstance[0:len((*c.CallOptions).CreateInstance):len((*c.CallOptions).CreateInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -273,15 +539,11 @@ func (c *NotebookClient) CreateInstance(ctx context.Context, req *notebookspb.Cr return nil, err } return &CreateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// RegisterInstance registers an existing legacy notebook instance to the Notebooks API server. -// Legacy instances are instances created with the legacy Compute Engine -// calls. They are not manageable by the Notebooks API out of the box. This -// call makes these instances manageable by the Notebooks API. -func (c *NotebookClient) RegisterInstance(ctx context.Context, req *notebookspb.RegisterInstanceRequest, opts ...gax.CallOption) (*RegisterInstanceOperation, error) { +func (c *notebookGRPCClient) RegisterInstance(ctx context.Context, req *notebookspb.RegisterInstanceRequest, opts ...gax.CallOption) (*RegisterInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -289,7 +551,7 @@ func (c *NotebookClient) RegisterInstance(ctx context.Context, req *notebookspb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RegisterInstance[0:len(c.CallOptions.RegisterInstance):len(c.CallOptions.RegisterInstance)], opts...) + opts = append((*c.CallOptions).RegisterInstance[0:len((*c.CallOptions).RegisterInstance):len((*c.CallOptions).RegisterInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -300,12 +562,11 @@ func (c *NotebookClient) RegisterInstance(ctx context.Context, req *notebookspb. return nil, err } return &RegisterInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// SetInstanceAccelerator updates the guest accelerators of a single Instance. -func (c *NotebookClient) SetInstanceAccelerator(ctx context.Context, req *notebookspb.SetInstanceAcceleratorRequest, opts ...gax.CallOption) (*SetInstanceAcceleratorOperation, error) { +func (c *notebookGRPCClient) SetInstanceAccelerator(ctx context.Context, req *notebookspb.SetInstanceAcceleratorRequest, opts ...gax.CallOption) (*SetInstanceAcceleratorOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -313,7 +574,7 @@ func (c *NotebookClient) SetInstanceAccelerator(ctx context.Context, req *notebo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetInstanceAccelerator[0:len(c.CallOptions.SetInstanceAccelerator):len(c.CallOptions.SetInstanceAccelerator)], opts...) + opts = append((*c.CallOptions).SetInstanceAccelerator[0:len((*c.CallOptions).SetInstanceAccelerator):len((*c.CallOptions).SetInstanceAccelerator)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -324,12 +585,11 @@ func (c *NotebookClient) SetInstanceAccelerator(ctx context.Context, req *notebo return nil, err } return &SetInstanceAcceleratorOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// SetInstanceMachineType updates the machine type of a single Instance. -func (c *NotebookClient) SetInstanceMachineType(ctx context.Context, req *notebookspb.SetInstanceMachineTypeRequest, opts ...gax.CallOption) (*SetInstanceMachineTypeOperation, error) { +func (c *notebookGRPCClient) SetInstanceMachineType(ctx context.Context, req *notebookspb.SetInstanceMachineTypeRequest, opts ...gax.CallOption) (*SetInstanceMachineTypeOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -337,7 +597,7 @@ func (c *NotebookClient) SetInstanceMachineType(ctx context.Context, req *notebo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetInstanceMachineType[0:len(c.CallOptions.SetInstanceMachineType):len(c.CallOptions.SetInstanceMachineType)], opts...) + opts = append((*c.CallOptions).SetInstanceMachineType[0:len((*c.CallOptions).SetInstanceMachineType):len((*c.CallOptions).SetInstanceMachineType)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -348,12 +608,11 @@ func (c *NotebookClient) SetInstanceMachineType(ctx context.Context, req *notebo return nil, err } return &SetInstanceMachineTypeOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// SetInstanceLabels updates the labels of an Instance. -func (c *NotebookClient) SetInstanceLabels(ctx context.Context, req *notebookspb.SetInstanceLabelsRequest, opts ...gax.CallOption) (*SetInstanceLabelsOperation, error) { +func (c *notebookGRPCClient) SetInstanceLabels(ctx context.Context, req *notebookspb.SetInstanceLabelsRequest, opts ...gax.CallOption) (*SetInstanceLabelsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -361,7 +620,7 @@ func (c *NotebookClient) SetInstanceLabels(ctx context.Context, req *notebookspb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetInstanceLabels[0:len(c.CallOptions.SetInstanceLabels):len(c.CallOptions.SetInstanceLabels)], opts...) + opts = append((*c.CallOptions).SetInstanceLabels[0:len((*c.CallOptions).SetInstanceLabels):len((*c.CallOptions).SetInstanceLabels)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -372,12 +631,11 @@ func (c *NotebookClient) SetInstanceLabels(ctx context.Context, req *notebookspb return nil, err } return &SetInstanceLabelsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteInstance deletes a single Instance. -func (c *NotebookClient) DeleteInstance(ctx context.Context, req *notebookspb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { +func (c *notebookGRPCClient) DeleteInstance(ctx context.Context, req *notebookspb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -385,7 +643,7 @@ func (c *NotebookClient) DeleteInstance(ctx context.Context, req *notebookspb.De } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteInstance[0:len(c.CallOptions.DeleteInstance):len(c.CallOptions.DeleteInstance)], opts...) + opts = append((*c.CallOptions).DeleteInstance[0:len((*c.CallOptions).DeleteInstance):len((*c.CallOptions).DeleteInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -396,12 +654,11 @@ func (c *NotebookClient) DeleteInstance(ctx context.Context, req *notebookspb.De return nil, err } return &DeleteInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// StartInstance starts a notebook instance. -func (c *NotebookClient) StartInstance(ctx context.Context, req *notebookspb.StartInstanceRequest, opts ...gax.CallOption) (*StartInstanceOperation, error) { +func (c *notebookGRPCClient) StartInstance(ctx context.Context, req *notebookspb.StartInstanceRequest, opts ...gax.CallOption) (*StartInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -409,7 +666,7 @@ func (c *NotebookClient) StartInstance(ctx context.Context, req *notebookspb.Sta } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.StartInstance[0:len(c.CallOptions.StartInstance):len(c.CallOptions.StartInstance)], opts...) + opts = append((*c.CallOptions).StartInstance[0:len((*c.CallOptions).StartInstance):len((*c.CallOptions).StartInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -420,12 +677,11 @@ func (c *NotebookClient) StartInstance(ctx context.Context, req *notebookspb.Sta return nil, err } return &StartInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// StopInstance stops a notebook instance. -func (c *NotebookClient) StopInstance(ctx context.Context, req *notebookspb.StopInstanceRequest, opts ...gax.CallOption) (*StopInstanceOperation, error) { +func (c *notebookGRPCClient) StopInstance(ctx context.Context, req *notebookspb.StopInstanceRequest, opts ...gax.CallOption) (*StopInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -433,7 +689,7 @@ func (c *NotebookClient) StopInstance(ctx context.Context, req *notebookspb.Stop } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.StopInstance[0:len(c.CallOptions.StopInstance):len(c.CallOptions.StopInstance)], opts...) + opts = append((*c.CallOptions).StopInstance[0:len((*c.CallOptions).StopInstance):len((*c.CallOptions).StopInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -444,12 +700,11 @@ func (c *NotebookClient) StopInstance(ctx context.Context, req *notebookspb.Stop return nil, err } return &StopInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ResetInstance resets a notebook instance. -func (c *NotebookClient) ResetInstance(ctx context.Context, req *notebookspb.ResetInstanceRequest, opts ...gax.CallOption) (*ResetInstanceOperation, error) { +func (c *notebookGRPCClient) ResetInstance(ctx context.Context, req *notebookspb.ResetInstanceRequest, opts ...gax.CallOption) (*ResetInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -457,7 +712,7 @@ func (c *NotebookClient) ResetInstance(ctx context.Context, req *notebookspb.Res } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ResetInstance[0:len(c.CallOptions.ResetInstance):len(c.CallOptions.ResetInstance)], opts...) + opts = append((*c.CallOptions).ResetInstance[0:len((*c.CallOptions).ResetInstance):len((*c.CallOptions).ResetInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -468,15 +723,11 @@ func (c *NotebookClient) ResetInstance(ctx context.Context, req *notebookspb.Res return nil, err } return &ResetInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ReportInstanceInfo allows notebook instances to -// report their latest instance information to the Notebooks -// API server. The server will merge the reported information to -// the instance metadata store. Do not use this method directly. -func (c *NotebookClient) ReportInstanceInfo(ctx context.Context, req *notebookspb.ReportInstanceInfoRequest, opts ...gax.CallOption) (*ReportInstanceInfoOperation, error) { +func (c *notebookGRPCClient) ReportInstanceInfo(ctx context.Context, req *notebookspb.ReportInstanceInfoRequest, opts ...gax.CallOption) (*ReportInstanceInfoOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -484,7 +735,7 @@ func (c *NotebookClient) ReportInstanceInfo(ctx context.Context, req *notebooksp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ReportInstanceInfo[0:len(c.CallOptions.ReportInstanceInfo):len(c.CallOptions.ReportInstanceInfo)], opts...) + opts = append((*c.CallOptions).ReportInstanceInfo[0:len((*c.CallOptions).ReportInstanceInfo):len((*c.CallOptions).ReportInstanceInfo)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -495,12 +746,11 @@ func (c *NotebookClient) ReportInstanceInfo(ctx context.Context, req *notebooksp return nil, err } return &ReportInstanceInfoOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// IsInstanceUpgradeable check if a notebook instance is upgradable. -func (c *NotebookClient) IsInstanceUpgradeable(ctx context.Context, req *notebookspb.IsInstanceUpgradeableRequest, opts ...gax.CallOption) (*notebookspb.IsInstanceUpgradeableResponse, error) { +func (c *notebookGRPCClient) IsInstanceUpgradeable(ctx context.Context, req *notebookspb.IsInstanceUpgradeableRequest, opts ...gax.CallOption) (*notebookspb.IsInstanceUpgradeableResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -508,7 +758,7 @@ func (c *NotebookClient) IsInstanceUpgradeable(ctx context.Context, req *noteboo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "notebook_instance", url.QueryEscape(req.GetNotebookInstance()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.IsInstanceUpgradeable[0:len(c.CallOptions.IsInstanceUpgradeable):len(c.CallOptions.IsInstanceUpgradeable)], opts...) + opts = append((*c.CallOptions).IsInstanceUpgradeable[0:len((*c.CallOptions).IsInstanceUpgradeable):len((*c.CallOptions).IsInstanceUpgradeable)], opts...) var resp *notebookspb.IsInstanceUpgradeableResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -521,8 +771,7 @@ func (c *NotebookClient) IsInstanceUpgradeable(ctx context.Context, req *noteboo return resp, nil } -// UpgradeInstance upgrades a notebook instance to the latest version. -func (c *NotebookClient) UpgradeInstance(ctx context.Context, req *notebookspb.UpgradeInstanceRequest, opts ...gax.CallOption) (*UpgradeInstanceOperation, error) { +func (c *notebookGRPCClient) UpgradeInstance(ctx context.Context, req *notebookspb.UpgradeInstanceRequest, opts ...gax.CallOption) (*UpgradeInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -530,7 +779,7 @@ func (c *NotebookClient) UpgradeInstance(ctx context.Context, req *notebookspb.U } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpgradeInstance[0:len(c.CallOptions.UpgradeInstance):len(c.CallOptions.UpgradeInstance)], opts...) + opts = append((*c.CallOptions).UpgradeInstance[0:len((*c.CallOptions).UpgradeInstance):len((*c.CallOptions).UpgradeInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -541,13 +790,11 @@ func (c *NotebookClient) UpgradeInstance(ctx context.Context, req *notebookspb.U return nil, err } return &UpgradeInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpgradeInstanceInternal allows notebook instances to -// call this endpoint to upgrade themselves. Do not use this method directly. -func (c *NotebookClient) UpgradeInstanceInternal(ctx context.Context, req *notebookspb.UpgradeInstanceInternalRequest, opts ...gax.CallOption) (*UpgradeInstanceInternalOperation, error) { +func (c *notebookGRPCClient) UpgradeInstanceInternal(ctx context.Context, req *notebookspb.UpgradeInstanceInternalRequest, opts ...gax.CallOption) (*UpgradeInstanceInternalOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -555,7 +802,7 @@ func (c *NotebookClient) UpgradeInstanceInternal(ctx context.Context, req *noteb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpgradeInstanceInternal[0:len(c.CallOptions.UpgradeInstanceInternal):len(c.CallOptions.UpgradeInstanceInternal)], opts...) + opts = append((*c.CallOptions).UpgradeInstanceInternal[0:len((*c.CallOptions).UpgradeInstanceInternal):len((*c.CallOptions).UpgradeInstanceInternal)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -566,15 +813,14 @@ func (c *NotebookClient) UpgradeInstanceInternal(ctx context.Context, req *noteb return nil, err } return &UpgradeInstanceInternalOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListEnvironments lists environments in a project. -func (c *NotebookClient) ListEnvironments(ctx context.Context, req *notebookspb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { +func (c *notebookGRPCClient) ListEnvironments(ctx context.Context, req *notebookspb.ListEnvironmentsRequest, opts ...gax.CallOption) *EnvironmentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListEnvironments[0:len(c.CallOptions.ListEnvironments):len(c.CallOptions.ListEnvironments)], opts...) + opts = append((*c.CallOptions).ListEnvironments[0:len((*c.CallOptions).ListEnvironments):len((*c.CallOptions).ListEnvironments)], opts...) it := &EnvironmentIterator{} req = proto.Clone(req).(*notebookspb.ListEnvironmentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*notebookspb.Environment, string, error) { @@ -611,8 +857,7 @@ func (c *NotebookClient) ListEnvironments(ctx context.Context, req *notebookspb. return it } -// GetEnvironment gets details of a single Environment. -func (c *NotebookClient) GetEnvironment(ctx context.Context, req *notebookspb.GetEnvironmentRequest, opts ...gax.CallOption) (*notebookspb.Environment, error) { +func (c *notebookGRPCClient) GetEnvironment(ctx context.Context, req *notebookspb.GetEnvironmentRequest, opts ...gax.CallOption) (*notebookspb.Environment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -620,7 +865,7 @@ func (c *NotebookClient) GetEnvironment(ctx context.Context, req *notebookspb.Ge } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEnvironment[0:len(c.CallOptions.GetEnvironment):len(c.CallOptions.GetEnvironment)], opts...) + opts = append((*c.CallOptions).GetEnvironment[0:len((*c.CallOptions).GetEnvironment):len((*c.CallOptions).GetEnvironment)], opts...) var resp *notebookspb.Environment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -633,8 +878,7 @@ func (c *NotebookClient) GetEnvironment(ctx context.Context, req *notebookspb.Ge return resp, nil } -// CreateEnvironment creates a new Environment. -func (c *NotebookClient) CreateEnvironment(ctx context.Context, req *notebookspb.CreateEnvironmentRequest, opts ...gax.CallOption) (*CreateEnvironmentOperation, error) { +func (c *notebookGRPCClient) CreateEnvironment(ctx context.Context, req *notebookspb.CreateEnvironmentRequest, opts ...gax.CallOption) (*CreateEnvironmentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -642,7 +886,7 @@ func (c *NotebookClient) CreateEnvironment(ctx context.Context, req *notebookspb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateEnvironment[0:len(c.CallOptions.CreateEnvironment):len(c.CallOptions.CreateEnvironment)], opts...) + opts = append((*c.CallOptions).CreateEnvironment[0:len((*c.CallOptions).CreateEnvironment):len((*c.CallOptions).CreateEnvironment)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -653,12 +897,11 @@ func (c *NotebookClient) CreateEnvironment(ctx context.Context, req *notebookspb return nil, err } return &CreateEnvironmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteEnvironment deletes a single Environment. -func (c *NotebookClient) DeleteEnvironment(ctx context.Context, req *notebookspb.DeleteEnvironmentRequest, opts ...gax.CallOption) (*DeleteEnvironmentOperation, error) { +func (c *notebookGRPCClient) DeleteEnvironment(ctx context.Context, req *notebookspb.DeleteEnvironmentRequest, opts ...gax.CallOption) (*DeleteEnvironmentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -666,7 +909,7 @@ func (c *NotebookClient) DeleteEnvironment(ctx context.Context, req *notebookspb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteEnvironment[0:len(c.CallOptions.DeleteEnvironment):len(c.CallOptions.DeleteEnvironment)], opts...) + opts = append((*c.CallOptions).DeleteEnvironment[0:len((*c.CallOptions).DeleteEnvironment):len((*c.CallOptions).DeleteEnvironment)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -677,7 +920,7 @@ func (c *NotebookClient) DeleteEnvironment(ctx context.Context, req *notebookspb return nil, err } return &DeleteEnvironmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -688,9 +931,9 @@ type CreateEnvironmentOperation struct { // CreateEnvironmentOperation returns a new CreateEnvironmentOperation from a given name. // The name must be that of a previously created CreateEnvironmentOperation, possibly from a different process. -func (c *NotebookClient) CreateEnvironmentOperation(name string) *CreateEnvironmentOperation { +func (c *notebookGRPCClient) CreateEnvironmentOperation(name string) *CreateEnvironmentOperation { return &CreateEnvironmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -757,9 +1000,9 @@ type CreateInstanceOperation struct { // CreateInstanceOperation returns a new CreateInstanceOperation from a given name. // The name must be that of a previously created CreateInstanceOperation, possibly from a different process. -func (c *NotebookClient) CreateInstanceOperation(name string) *CreateInstanceOperation { +func (c *notebookGRPCClient) CreateInstanceOperation(name string) *CreateInstanceOperation { return &CreateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -826,9 +1069,9 @@ type DeleteEnvironmentOperation struct { // DeleteEnvironmentOperation returns a new DeleteEnvironmentOperation from a given name. // The name must be that of a previously created DeleteEnvironmentOperation, possibly from a different process. -func (c *NotebookClient) DeleteEnvironmentOperation(name string) *DeleteEnvironmentOperation { +func (c *notebookGRPCClient) DeleteEnvironmentOperation(name string) *DeleteEnvironmentOperation { return &DeleteEnvironmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -884,9 +1127,9 @@ type DeleteInstanceOperation struct { // DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. // The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. -func (c *NotebookClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { +func (c *notebookGRPCClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { return &DeleteInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -942,9 +1185,9 @@ type RegisterInstanceOperation struct { // RegisterInstanceOperation returns a new RegisterInstanceOperation from a given name. // The name must be that of a previously created RegisterInstanceOperation, possibly from a different process. -func (c *NotebookClient) RegisterInstanceOperation(name string) *RegisterInstanceOperation { +func (c *notebookGRPCClient) RegisterInstanceOperation(name string) *RegisterInstanceOperation { return &RegisterInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1011,9 +1254,9 @@ type ReportInstanceInfoOperation struct { // ReportInstanceInfoOperation returns a new ReportInstanceInfoOperation from a given name. // The name must be that of a previously created ReportInstanceInfoOperation, possibly from a different process. -func (c *NotebookClient) ReportInstanceInfoOperation(name string) *ReportInstanceInfoOperation { +func (c *notebookGRPCClient) ReportInstanceInfoOperation(name string) *ReportInstanceInfoOperation { return &ReportInstanceInfoOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1080,9 +1323,9 @@ type ResetInstanceOperation struct { // ResetInstanceOperation returns a new ResetInstanceOperation from a given name. // The name must be that of a previously created ResetInstanceOperation, possibly from a different process. -func (c *NotebookClient) ResetInstanceOperation(name string) *ResetInstanceOperation { +func (c *notebookGRPCClient) ResetInstanceOperation(name string) *ResetInstanceOperation { return &ResetInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1149,9 +1392,9 @@ type SetInstanceAcceleratorOperation struct { // SetInstanceAcceleratorOperation returns a new SetInstanceAcceleratorOperation from a given name. // The name must be that of a previously created SetInstanceAcceleratorOperation, possibly from a different process. -func (c *NotebookClient) SetInstanceAcceleratorOperation(name string) *SetInstanceAcceleratorOperation { +func (c *notebookGRPCClient) SetInstanceAcceleratorOperation(name string) *SetInstanceAcceleratorOperation { return &SetInstanceAcceleratorOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1218,9 +1461,9 @@ type SetInstanceLabelsOperation struct { // SetInstanceLabelsOperation returns a new SetInstanceLabelsOperation from a given name. // The name must be that of a previously created SetInstanceLabelsOperation, possibly from a different process. -func (c *NotebookClient) SetInstanceLabelsOperation(name string) *SetInstanceLabelsOperation { +func (c *notebookGRPCClient) SetInstanceLabelsOperation(name string) *SetInstanceLabelsOperation { return &SetInstanceLabelsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1287,9 +1530,9 @@ type SetInstanceMachineTypeOperation struct { // SetInstanceMachineTypeOperation returns a new SetInstanceMachineTypeOperation from a given name. // The name must be that of a previously created SetInstanceMachineTypeOperation, possibly from a different process. -func (c *NotebookClient) SetInstanceMachineTypeOperation(name string) *SetInstanceMachineTypeOperation { +func (c *notebookGRPCClient) SetInstanceMachineTypeOperation(name string) *SetInstanceMachineTypeOperation { return &SetInstanceMachineTypeOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1356,9 +1599,9 @@ type StartInstanceOperation struct { // StartInstanceOperation returns a new StartInstanceOperation from a given name. // The name must be that of a previously created StartInstanceOperation, possibly from a different process. -func (c *NotebookClient) StartInstanceOperation(name string) *StartInstanceOperation { +func (c *notebookGRPCClient) StartInstanceOperation(name string) *StartInstanceOperation { return &StartInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1425,9 +1668,9 @@ type StopInstanceOperation struct { // StopInstanceOperation returns a new StopInstanceOperation from a given name. // The name must be that of a previously created StopInstanceOperation, possibly from a different process. -func (c *NotebookClient) StopInstanceOperation(name string) *StopInstanceOperation { +func (c *notebookGRPCClient) StopInstanceOperation(name string) *StopInstanceOperation { return &StopInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1494,9 +1737,9 @@ type UpgradeInstanceOperation struct { // UpgradeInstanceOperation returns a new UpgradeInstanceOperation from a given name. // The name must be that of a previously created UpgradeInstanceOperation, possibly from a different process. -func (c *NotebookClient) UpgradeInstanceOperation(name string) *UpgradeInstanceOperation { +func (c *notebookGRPCClient) UpgradeInstanceOperation(name string) *UpgradeInstanceOperation { return &UpgradeInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1563,9 +1806,9 @@ type UpgradeInstanceInternalOperation struct { // UpgradeInstanceInternalOperation returns a new UpgradeInstanceInternalOperation from a given name. // The name must be that of a previously created UpgradeInstanceInternalOperation, possibly from a different process. -func (c *NotebookClient) UpgradeInstanceInternalOperation(name string) *UpgradeInstanceInternalOperation { +func (c *notebookGRPCClient) UpgradeInstanceInternalOperation(name string) *UpgradeInstanceInternalOperation { return &UpgradeInstanceInternalOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/notebooks/apiv1beta1/notebook_client_example_test.go b/notebooks/apiv1beta1/notebook_client_example_test.go index 07ba748e1dda..cab21c1f1534 100644 --- a/notebooks/apiv1beta1/notebook_client_example_test.go +++ b/notebooks/apiv1beta1/notebook_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewNotebookClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleNotebookClient_ListInstances() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.ListInstancesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleNotebookClient_ListInstances() { } func ExampleNotebookClient_GetInstance() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.GetInstanceRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleNotebookClient_GetInstance() { } func ExampleNotebookClient_CreateInstance() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.CreateInstanceRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleNotebookClient_CreateInstance() { } func ExampleNotebookClient_RegisterInstance() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.RegisterInstanceRequest{ // TODO: Fill request struct fields. @@ -132,13 +129,12 @@ func ExampleNotebookClient_RegisterInstance() { } func ExampleNotebookClient_SetInstanceAccelerator() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.SetInstanceAcceleratorRequest{ // TODO: Fill request struct fields. @@ -157,13 +153,12 @@ func ExampleNotebookClient_SetInstanceAccelerator() { } func ExampleNotebookClient_SetInstanceMachineType() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.SetInstanceMachineTypeRequest{ // TODO: Fill request struct fields. @@ -182,13 +177,12 @@ func ExampleNotebookClient_SetInstanceMachineType() { } func ExampleNotebookClient_SetInstanceLabels() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.SetInstanceLabelsRequest{ // TODO: Fill request struct fields. @@ -207,13 +201,12 @@ func ExampleNotebookClient_SetInstanceLabels() { } func ExampleNotebookClient_DeleteInstance() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.DeleteInstanceRequest{ // TODO: Fill request struct fields. @@ -230,13 +223,12 @@ func ExampleNotebookClient_DeleteInstance() { } func ExampleNotebookClient_StartInstance() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.StartInstanceRequest{ // TODO: Fill request struct fields. @@ -255,13 +247,12 @@ func ExampleNotebookClient_StartInstance() { } func ExampleNotebookClient_StopInstance() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.StopInstanceRequest{ // TODO: Fill request struct fields. @@ -280,13 +271,12 @@ func ExampleNotebookClient_StopInstance() { } func ExampleNotebookClient_ResetInstance() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.ResetInstanceRequest{ // TODO: Fill request struct fields. @@ -305,13 +295,12 @@ func ExampleNotebookClient_ResetInstance() { } func ExampleNotebookClient_ReportInstanceInfo() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.ReportInstanceInfoRequest{ // TODO: Fill request struct fields. @@ -330,13 +319,12 @@ func ExampleNotebookClient_ReportInstanceInfo() { } func ExampleNotebookClient_IsInstanceUpgradeable() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.IsInstanceUpgradeableRequest{ // TODO: Fill request struct fields. @@ -350,13 +338,12 @@ func ExampleNotebookClient_IsInstanceUpgradeable() { } func ExampleNotebookClient_UpgradeInstance() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.UpgradeInstanceRequest{ // TODO: Fill request struct fields. @@ -375,13 +362,12 @@ func ExampleNotebookClient_UpgradeInstance() { } func ExampleNotebookClient_UpgradeInstanceInternal() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.UpgradeInstanceInternalRequest{ // TODO: Fill request struct fields. @@ -400,14 +386,12 @@ func ExampleNotebookClient_UpgradeInstanceInternal() { } func ExampleNotebookClient_ListEnvironments() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.ListEnvironmentsRequest{ // TODO: Fill request struct fields. @@ -427,13 +411,12 @@ func ExampleNotebookClient_ListEnvironments() { } func ExampleNotebookClient_GetEnvironment() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.GetEnvironmentRequest{ // TODO: Fill request struct fields. @@ -447,13 +430,12 @@ func ExampleNotebookClient_GetEnvironment() { } func ExampleNotebookClient_CreateEnvironment() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.CreateEnvironmentRequest{ // TODO: Fill request struct fields. @@ -472,13 +454,12 @@ func ExampleNotebookClient_CreateEnvironment() { } func ExampleNotebookClient_DeleteEnvironment() { - // import notebookspb "google.golang.org/genproto/googleapis/cloud/notebooks/v1beta1" - ctx := context.Background() c, err := notebooks.NewNotebookClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := ¬ebookspb.DeleteEnvironmentRequest{ // TODO: Fill request struct fields. diff --git a/orgpolicy/apiv2/doc.go b/orgpolicy/apiv2/doc.go index c2631c9377f2..ec85c079bac3 100644 --- a/orgpolicy/apiv2/doc.go +++ b/orgpolicy/apiv2/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package orgpolicy // import "cloud.google.com/go/orgpolicy/apiv2" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/orgpolicy/apiv2/org_policy_client.go b/orgpolicy/apiv2/org_policy_client.go index e135a726e913..31c43ee38e68 100644 --- a/orgpolicy/apiv2/org_policy_client.go +++ b/orgpolicy/apiv2/org_policy_client.go @@ -48,7 +48,7 @@ type CallOptions struct { DeletePolicy []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("orgpolicy.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("orgpolicy.mtls.googleapis.com:443"), @@ -149,27 +149,155 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Organization Policy API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListConstraints(context.Context, *orgpolicypb.ListConstraintsRequest, ...gax.CallOption) *ConstraintIterator + ListPolicies(context.Context, *orgpolicypb.ListPoliciesRequest, ...gax.CallOption) *PolicyIterator + GetPolicy(context.Context, *orgpolicypb.GetPolicyRequest, ...gax.CallOption) (*orgpolicypb.Policy, error) + GetEffectivePolicy(context.Context, *orgpolicypb.GetEffectivePolicyRequest, ...gax.CallOption) (*orgpolicypb.Policy, error) + CreatePolicy(context.Context, *orgpolicypb.CreatePolicyRequest, ...gax.CallOption) (*orgpolicypb.Policy, error) + UpdatePolicy(context.Context, *orgpolicypb.UpdatePolicyRequest, ...gax.CallOption) (*orgpolicypb.Policy, error) + DeletePolicy(context.Context, *orgpolicypb.DeletePolicyRequest, ...gax.CallOption) error +} + // Client is a client for interacting with Organization Policy API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// An interface for managing organization policies. +// +// The Cloud Org Policy service provides a simple mechanism for organizations to +// restrict the allowed configurations across their entire Cloud Resource +// hierarchy. +// +// You can use a policy to configure restrictions in Cloud resources. For +// example, you can enforce a policy that restricts which Google +// Cloud Platform APIs can be activated in a certain part of your resource +// hierarchy, or prevents serial port access to VM instances in a particular +// folder. +// +// Policies are inherited down through the resource hierarchy. A policy +// applied to a parent resource automatically applies to all its child resources +// unless overridden with a policy lower in the hierarchy. +// +// A constraint defines an aspect of a resource’s configuration that can be +// controlled by an organization’s policy administrator. Policies are a +// collection of constraints that defines their allowable configuration on a +// particular resource and its child resources. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListConstraints lists Constraints that could be applied on the specified resource. +func (c *Client) ListConstraints(ctx context.Context, req *orgpolicypb.ListConstraintsRequest, opts ...gax.CallOption) *ConstraintIterator { + return c.internalClient.ListConstraints(ctx, req, opts...) +} + +// ListPolicies retrieves all of the Policies that exist on a particular resource. +func (c *Client) ListPolicies(ctx context.Context, req *orgpolicypb.ListPoliciesRequest, opts ...gax.CallOption) *PolicyIterator { + return c.internalClient.ListPolicies(ctx, req, opts...) +} + +// GetPolicy gets a Policy on a resource. +// +// If no Policy is set on the resource, NOT_FOUND is returned. The +// etag value can be used with UpdatePolicy() to update a +// Policy during read-modify-write. +func (c *Client) GetPolicy(ctx context.Context, req *orgpolicypb.GetPolicyRequest, opts ...gax.CallOption) (*orgpolicypb.Policy, error) { + return c.internalClient.GetPolicy(ctx, req, opts...) +} + +// GetEffectivePolicy gets the effective Policy on a resource. This is the result of merging +// Policies in the resource hierarchy and evaluating conditions. The +// returned Policy will not have an etag or condition set because it is +// a computed Policy across multiple resources. +// Subtrees of Resource Manager resource hierarchy with ‘under:’ prefix will +// not be expanded. +func (c *Client) GetEffectivePolicy(ctx context.Context, req *orgpolicypb.GetEffectivePolicyRequest, opts ...gax.CallOption) (*orgpolicypb.Policy, error) { + return c.internalClient.GetEffectivePolicy(ctx, req, opts...) +} + +// CreatePolicy creates a Policy. +// +// Returns a google.rpc.Status with google.rpc.Code.NOT_FOUND if the +// constraint does not exist. +// Returns a google.rpc.Status with google.rpc.Code.ALREADY_EXISTS if the +// policy already exists on the given Cloud resource. +func (c *Client) CreatePolicy(ctx context.Context, req *orgpolicypb.CreatePolicyRequest, opts ...gax.CallOption) (*orgpolicypb.Policy, error) { + return c.internalClient.CreatePolicy(ctx, req, opts...) +} + +// UpdatePolicy updates a Policy. +// +// Returns a google.rpc.Status with google.rpc.Code.NOT_FOUND if the +// constraint or the policy do not exist. +// Returns a google.rpc.Status with google.rpc.Code.ABORTED if the etag +// supplied in the request does not match the persisted etag of the policy +// +// Note: the supplied policy will perform a full overwrite of all +// fields. +func (c *Client) UpdatePolicy(ctx context.Context, req *orgpolicypb.UpdatePolicyRequest, opts ...gax.CallOption) (*orgpolicypb.Policy, error) { + return c.internalClient.UpdatePolicy(ctx, req, opts...) +} + +// DeletePolicy deletes a Policy. +// +// Returns a google.rpc.Status with google.rpc.Code.NOT_FOUND if the +// constraint or Org Policy does not exist. +func (c *Client) DeletePolicy(ctx context.Context, req *orgpolicypb.DeletePolicyRequest, opts ...gax.CallOption) error { + return c.internalClient.DeletePolicy(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Organization Policy API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client orgpolicypb.OrgPolicyClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new org policy client. +// NewClient creates a new org policy client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // An interface for managing organization policies. // @@ -192,8 +320,7 @@ type Client struct { // collection of constraints that defines their allowable configuration on a // particular resource and its child resources. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -211,45 +338,47 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: orgpolicypb.NewOrgPolicyClient(connPool), + client: orgpolicypb.NewOrgPolicyClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListConstraints lists Constraints that could be applied on the specified resource. -func (c *Client) ListConstraints(ctx context.Context, req *orgpolicypb.ListConstraintsRequest, opts ...gax.CallOption) *ConstraintIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ListConstraints(ctx context.Context, req *orgpolicypb.ListConstraintsRequest, opts ...gax.CallOption) *ConstraintIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListConstraints[0:len(c.CallOptions.ListConstraints):len(c.CallOptions.ListConstraints)], opts...) + opts = append((*c.CallOptions).ListConstraints[0:len((*c.CallOptions).ListConstraints):len((*c.CallOptions).ListConstraints)], opts...) it := &ConstraintIterator{} req = proto.Clone(req).(*orgpolicypb.ListConstraintsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*orgpolicypb.Constraint, string, error) { @@ -286,11 +415,10 @@ func (c *Client) ListConstraints(ctx context.Context, req *orgpolicypb.ListConst return it } -// ListPolicies retrieves all of the Policies that exist on a particular resource. -func (c *Client) ListPolicies(ctx context.Context, req *orgpolicypb.ListPoliciesRequest, opts ...gax.CallOption) *PolicyIterator { +func (c *gRPCClient) ListPolicies(ctx context.Context, req *orgpolicypb.ListPoliciesRequest, opts ...gax.CallOption) *PolicyIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListPolicies[0:len(c.CallOptions.ListPolicies):len(c.CallOptions.ListPolicies)], opts...) + opts = append((*c.CallOptions).ListPolicies[0:len((*c.CallOptions).ListPolicies):len((*c.CallOptions).ListPolicies)], opts...) it := &PolicyIterator{} req = proto.Clone(req).(*orgpolicypb.ListPoliciesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*orgpolicypb.Policy, string, error) { @@ -327,12 +455,7 @@ func (c *Client) ListPolicies(ctx context.Context, req *orgpolicypb.ListPolicies return it } -// GetPolicy gets a Policy on a resource. -// -// If no Policy is set on the resource, NOT_FOUND is returned. The -// etag value can be used with UpdatePolicy() to update a -// Policy during read-modify-write. -func (c *Client) GetPolicy(ctx context.Context, req *orgpolicypb.GetPolicyRequest, opts ...gax.CallOption) (*orgpolicypb.Policy, error) { +func (c *gRPCClient) GetPolicy(ctx context.Context, req *orgpolicypb.GetPolicyRequest, opts ...gax.CallOption) (*orgpolicypb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -340,7 +463,7 @@ func (c *Client) GetPolicy(ctx context.Context, req *orgpolicypb.GetPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetPolicy[0:len(c.CallOptions.GetPolicy):len(c.CallOptions.GetPolicy)], opts...) + opts = append((*c.CallOptions).GetPolicy[0:len((*c.CallOptions).GetPolicy):len((*c.CallOptions).GetPolicy)], opts...) var resp *orgpolicypb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -353,13 +476,7 @@ func (c *Client) GetPolicy(ctx context.Context, req *orgpolicypb.GetPolicyReques return resp, nil } -// GetEffectivePolicy gets the effective Policy on a resource. This is the result of merging -// Policies in the resource hierarchy and evaluating conditions. The -// returned Policy will not have an etag or condition set because it is -// a computed Policy across multiple resources. -// Subtrees of Resource Manager resource hierarchy with ‘under:’ prefix will -// not be expanded. -func (c *Client) GetEffectivePolicy(ctx context.Context, req *orgpolicypb.GetEffectivePolicyRequest, opts ...gax.CallOption) (*orgpolicypb.Policy, error) { +func (c *gRPCClient) GetEffectivePolicy(ctx context.Context, req *orgpolicypb.GetEffectivePolicyRequest, opts ...gax.CallOption) (*orgpolicypb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -367,7 +484,7 @@ func (c *Client) GetEffectivePolicy(ctx context.Context, req *orgpolicypb.GetEff } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEffectivePolicy[0:len(c.CallOptions.GetEffectivePolicy):len(c.CallOptions.GetEffectivePolicy)], opts...) + opts = append((*c.CallOptions).GetEffectivePolicy[0:len((*c.CallOptions).GetEffectivePolicy):len((*c.CallOptions).GetEffectivePolicy)], opts...) var resp *orgpolicypb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -380,13 +497,7 @@ func (c *Client) GetEffectivePolicy(ctx context.Context, req *orgpolicypb.GetEff return resp, nil } -// CreatePolicy creates a Policy. -// -// Returns a google.rpc.Status with google.rpc.Code.NOT_FOUND if the -// constraint does not exist. -// Returns a google.rpc.Status with google.rpc.Code.ALREADY_EXISTS if the -// policy already exists on the given Cloud resource. -func (c *Client) CreatePolicy(ctx context.Context, req *orgpolicypb.CreatePolicyRequest, opts ...gax.CallOption) (*orgpolicypb.Policy, error) { +func (c *gRPCClient) CreatePolicy(ctx context.Context, req *orgpolicypb.CreatePolicyRequest, opts ...gax.CallOption) (*orgpolicypb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -394,7 +505,7 @@ func (c *Client) CreatePolicy(ctx context.Context, req *orgpolicypb.CreatePolicy } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreatePolicy[0:len(c.CallOptions.CreatePolicy):len(c.CallOptions.CreatePolicy)], opts...) + opts = append((*c.CallOptions).CreatePolicy[0:len((*c.CallOptions).CreatePolicy):len((*c.CallOptions).CreatePolicy)], opts...) var resp *orgpolicypb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -407,16 +518,7 @@ func (c *Client) CreatePolicy(ctx context.Context, req *orgpolicypb.CreatePolicy return resp, nil } -// UpdatePolicy updates a Policy. -// -// Returns a google.rpc.Status with google.rpc.Code.NOT_FOUND if the -// constraint or the policy do not exist. -// Returns a google.rpc.Status with google.rpc.Code.ABORTED if the etag -// supplied in the request does not match the persisted etag of the policy -// -// Note: the supplied policy will perform a full overwrite of all -// fields. -func (c *Client) UpdatePolicy(ctx context.Context, req *orgpolicypb.UpdatePolicyRequest, opts ...gax.CallOption) (*orgpolicypb.Policy, error) { +func (c *gRPCClient) UpdatePolicy(ctx context.Context, req *orgpolicypb.UpdatePolicyRequest, opts ...gax.CallOption) (*orgpolicypb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -424,7 +526,7 @@ func (c *Client) UpdatePolicy(ctx context.Context, req *orgpolicypb.UpdatePolicy } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "policy.name", url.QueryEscape(req.GetPolicy().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdatePolicy[0:len(c.CallOptions.UpdatePolicy):len(c.CallOptions.UpdatePolicy)], opts...) + opts = append((*c.CallOptions).UpdatePolicy[0:len((*c.CallOptions).UpdatePolicy):len((*c.CallOptions).UpdatePolicy)], opts...) var resp *orgpolicypb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -437,11 +539,7 @@ func (c *Client) UpdatePolicy(ctx context.Context, req *orgpolicypb.UpdatePolicy return resp, nil } -// DeletePolicy deletes a Policy. -// -// Returns a google.rpc.Status with google.rpc.Code.NOT_FOUND if the -// constraint or Org Policy does not exist. -func (c *Client) DeletePolicy(ctx context.Context, req *orgpolicypb.DeletePolicyRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeletePolicy(ctx context.Context, req *orgpolicypb.DeletePolicyRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -449,7 +547,7 @@ func (c *Client) DeletePolicy(ctx context.Context, req *orgpolicypb.DeletePolicy } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeletePolicy[0:len(c.CallOptions.DeletePolicy):len(c.CallOptions.DeletePolicy)], opts...) + opts = append((*c.CallOptions).DeletePolicy[0:len((*c.CallOptions).DeletePolicy):len((*c.CallOptions).DeletePolicy)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeletePolicy(ctx, req, settings.GRPC...) diff --git a/orgpolicy/apiv2/org_policy_client_example_test.go b/orgpolicy/apiv2/org_policy_client_example_test.go index 5fb8ed10d53b..38af79fd85f4 100644 --- a/orgpolicy/apiv2/org_policy_client_example_test.go +++ b/orgpolicy/apiv2/org_policy_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ListConstraints() { - // import orgpolicypb "google.golang.org/genproto/googleapis/cloud/orgpolicy/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := orgpolicy.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &orgpolicypb.ListConstraintsRequest{ // TODO: Fill request struct fields. @@ -62,14 +62,12 @@ func ExampleClient_ListConstraints() { } func ExampleClient_ListPolicies() { - // import orgpolicypb "google.golang.org/genproto/googleapis/cloud/orgpolicy/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := orgpolicy.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &orgpolicypb.ListPoliciesRequest{ // TODO: Fill request struct fields. @@ -89,13 +87,12 @@ func ExampleClient_ListPolicies() { } func ExampleClient_GetPolicy() { - // import orgpolicypb "google.golang.org/genproto/googleapis/cloud/orgpolicy/v2" - ctx := context.Background() c, err := orgpolicy.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &orgpolicypb.GetPolicyRequest{ // TODO: Fill request struct fields. @@ -109,13 +106,12 @@ func ExampleClient_GetPolicy() { } func ExampleClient_GetEffectivePolicy() { - // import orgpolicypb "google.golang.org/genproto/googleapis/cloud/orgpolicy/v2" - ctx := context.Background() c, err := orgpolicy.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &orgpolicypb.GetEffectivePolicyRequest{ // TODO: Fill request struct fields. @@ -129,13 +125,12 @@ func ExampleClient_GetEffectivePolicy() { } func ExampleClient_CreatePolicy() { - // import orgpolicypb "google.golang.org/genproto/googleapis/cloud/orgpolicy/v2" - ctx := context.Background() c, err := orgpolicy.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &orgpolicypb.CreatePolicyRequest{ // TODO: Fill request struct fields. @@ -149,13 +144,12 @@ func ExampleClient_CreatePolicy() { } func ExampleClient_UpdatePolicy() { - // import orgpolicypb "google.golang.org/genproto/googleapis/cloud/orgpolicy/v2" - ctx := context.Background() c, err := orgpolicy.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &orgpolicypb.UpdatePolicyRequest{ // TODO: Fill request struct fields. @@ -174,6 +168,7 @@ func ExampleClient_DeletePolicy() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &orgpolicypb.DeletePolicyRequest{ // TODO: Fill request struct fields. diff --git a/osconfig/agentendpoint/apiv1/agent_endpoint_client.go b/osconfig/agentendpoint/apiv1/agent_endpoint_client.go index b07008741791..35f45a3ed4ac 100644 --- a/osconfig/agentendpoint/apiv1/agent_endpoint_client.go +++ b/osconfig/agentendpoint/apiv1/agent_endpoint_client.go @@ -43,7 +43,7 @@ type CallOptions struct { ReportInventory []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("osconfig.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("osconfig.mtls.googleapis.com:443"), @@ -130,32 +130,110 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from OS Config API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ReceiveTaskNotification(context.Context, *agentendpointpb.ReceiveTaskNotificationRequest, ...gax.CallOption) (agentendpointpb.AgentEndpointService_ReceiveTaskNotificationClient, error) + StartNextTask(context.Context, *agentendpointpb.StartNextTaskRequest, ...gax.CallOption) (*agentendpointpb.StartNextTaskResponse, error) + ReportTaskProgress(context.Context, *agentendpointpb.ReportTaskProgressRequest, ...gax.CallOption) (*agentendpointpb.ReportTaskProgressResponse, error) + ReportTaskComplete(context.Context, *agentendpointpb.ReportTaskCompleteRequest, ...gax.CallOption) (*agentendpointpb.ReportTaskCompleteResponse, error) + RegisterAgent(context.Context, *agentendpointpb.RegisterAgentRequest, ...gax.CallOption) (*agentendpointpb.RegisterAgentResponse, error) + ReportInventory(context.Context, *agentendpointpb.ReportInventoryRequest, ...gax.CallOption) (*agentendpointpb.ReportInventoryResponse, error) +} + // Client is a client for interacting with OS Config API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// OS Config agent endpoint API. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ReceiveTaskNotification stream established by client to receive Task notifications. +func (c *Client) ReceiveTaskNotification(ctx context.Context, req *agentendpointpb.ReceiveTaskNotificationRequest, opts ...gax.CallOption) (agentendpointpb.AgentEndpointService_ReceiveTaskNotificationClient, error) { + return c.internalClient.ReceiveTaskNotification(ctx, req, opts...) +} + +// StartNextTask signals the start of a task execution and returns the task info. +func (c *Client) StartNextTask(ctx context.Context, req *agentendpointpb.StartNextTaskRequest, opts ...gax.CallOption) (*agentendpointpb.StartNextTaskResponse, error) { + return c.internalClient.StartNextTask(ctx, req, opts...) +} + +// ReportTaskProgress signals an intermediary progress checkpoint in task execution. +func (c *Client) ReportTaskProgress(ctx context.Context, req *agentendpointpb.ReportTaskProgressRequest, opts ...gax.CallOption) (*agentendpointpb.ReportTaskProgressResponse, error) { + return c.internalClient.ReportTaskProgress(ctx, req, opts...) +} + +// ReportTaskComplete signals that the task execution is complete and optionally returns the next +// task. +func (c *Client) ReportTaskComplete(ctx context.Context, req *agentendpointpb.ReportTaskCompleteRequest, opts ...gax.CallOption) (*agentendpointpb.ReportTaskCompleteResponse, error) { + return c.internalClient.ReportTaskComplete(ctx, req, opts...) +} + +// RegisterAgent registers the agent running on the VM. +func (c *Client) RegisterAgent(ctx context.Context, req *agentendpointpb.RegisterAgentRequest, opts ...gax.CallOption) (*agentendpointpb.RegisterAgentResponse, error) { + return c.internalClient.RegisterAgent(ctx, req, opts...) +} + +// ReportInventory reports the VMs current inventory. +func (c *Client) ReportInventory(ctx context.Context, req *agentendpointpb.ReportInventoryRequest, opts ...gax.CallOption) (*agentendpointpb.ReportInventoryResponse, error) { + return c.internalClient.ReportInventory(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with OS Config API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client agentendpointpb.AgentEndpointServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new agent endpoint service client. +// NewClient creates a new agent endpoint service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // OS Config agent endpoint API. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -173,44 +251,45 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: agentendpointpb.NewAgentEndpointServiceClient(connPool), + client: agentendpointpb.NewAgentEndpointServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ReceiveTaskNotification stream established by client to receive Task notifications. -func (c *Client) ReceiveTaskNotification(ctx context.Context, req *agentendpointpb.ReceiveTaskNotificationRequest, opts ...gax.CallOption) (agentendpointpb.AgentEndpointService_ReceiveTaskNotificationClient, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ReceiveTaskNotification(ctx context.Context, req *agentendpointpb.ReceiveTaskNotificationRequest, opts ...gax.CallOption) (agentendpointpb.AgentEndpointService_ReceiveTaskNotificationClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ReceiveTaskNotification[0:len(c.CallOptions.ReceiveTaskNotification):len(c.CallOptions.ReceiveTaskNotification)], opts...) var resp agentendpointpb.AgentEndpointService_ReceiveTaskNotificationClient err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -223,15 +302,14 @@ func (c *Client) ReceiveTaskNotification(ctx context.Context, req *agentendpoint return resp, nil } -// StartNextTask signals the start of a task execution and returns the task info. -func (c *Client) StartNextTask(ctx context.Context, req *agentendpointpb.StartNextTaskRequest, opts ...gax.CallOption) (*agentendpointpb.StartNextTaskResponse, error) { +func (c *gRPCClient) StartNextTask(ctx context.Context, req *agentendpointpb.StartNextTaskRequest, opts ...gax.CallOption) (*agentendpointpb.StartNextTaskResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.StartNextTask[0:len(c.CallOptions.StartNextTask):len(c.CallOptions.StartNextTask)], opts...) + opts = append((*c.CallOptions).StartNextTask[0:len((*c.CallOptions).StartNextTask):len((*c.CallOptions).StartNextTask)], opts...) var resp *agentendpointpb.StartNextTaskResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -244,15 +322,14 @@ func (c *Client) StartNextTask(ctx context.Context, req *agentendpointpb.StartNe return resp, nil } -// ReportTaskProgress signals an intermediary progress checkpoint in task execution. -func (c *Client) ReportTaskProgress(ctx context.Context, req *agentendpointpb.ReportTaskProgressRequest, opts ...gax.CallOption) (*agentendpointpb.ReportTaskProgressResponse, error) { +func (c *gRPCClient) ReportTaskProgress(ctx context.Context, req *agentendpointpb.ReportTaskProgressRequest, opts ...gax.CallOption) (*agentendpointpb.ReportTaskProgressResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ReportTaskProgress[0:len(c.CallOptions.ReportTaskProgress):len(c.CallOptions.ReportTaskProgress)], opts...) + opts = append((*c.CallOptions).ReportTaskProgress[0:len((*c.CallOptions).ReportTaskProgress):len((*c.CallOptions).ReportTaskProgress)], opts...) var resp *agentendpointpb.ReportTaskProgressResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -265,16 +342,14 @@ func (c *Client) ReportTaskProgress(ctx context.Context, req *agentendpointpb.Re return resp, nil } -// ReportTaskComplete signals that the task execution is complete and optionally returns the next -// task. -func (c *Client) ReportTaskComplete(ctx context.Context, req *agentendpointpb.ReportTaskCompleteRequest, opts ...gax.CallOption) (*agentendpointpb.ReportTaskCompleteResponse, error) { +func (c *gRPCClient) ReportTaskComplete(ctx context.Context, req *agentendpointpb.ReportTaskCompleteRequest, opts ...gax.CallOption) (*agentendpointpb.ReportTaskCompleteResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ReportTaskComplete[0:len(c.CallOptions.ReportTaskComplete):len(c.CallOptions.ReportTaskComplete)], opts...) + opts = append((*c.CallOptions).ReportTaskComplete[0:len((*c.CallOptions).ReportTaskComplete):len((*c.CallOptions).ReportTaskComplete)], opts...) var resp *agentendpointpb.ReportTaskCompleteResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -287,15 +362,14 @@ func (c *Client) ReportTaskComplete(ctx context.Context, req *agentendpointpb.Re return resp, nil } -// RegisterAgent registers the agent running on the VM. -func (c *Client) RegisterAgent(ctx context.Context, req *agentendpointpb.RegisterAgentRequest, opts ...gax.CallOption) (*agentendpointpb.RegisterAgentResponse, error) { +func (c *gRPCClient) RegisterAgent(ctx context.Context, req *agentendpointpb.RegisterAgentRequest, opts ...gax.CallOption) (*agentendpointpb.RegisterAgentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.RegisterAgent[0:len(c.CallOptions.RegisterAgent):len(c.CallOptions.RegisterAgent)], opts...) + opts = append((*c.CallOptions).RegisterAgent[0:len((*c.CallOptions).RegisterAgent):len((*c.CallOptions).RegisterAgent)], opts...) var resp *agentendpointpb.RegisterAgentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -308,15 +382,14 @@ func (c *Client) RegisterAgent(ctx context.Context, req *agentendpointpb.Registe return resp, nil } -// ReportInventory reports the VMs current inventory. -func (c *Client) ReportInventory(ctx context.Context, req *agentendpointpb.ReportInventoryRequest, opts ...gax.CallOption) (*agentendpointpb.ReportInventoryResponse, error) { +func (c *gRPCClient) ReportInventory(ctx context.Context, req *agentendpointpb.ReportInventoryRequest, opts ...gax.CallOption) (*agentendpointpb.ReportInventoryResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ReportInventory[0:len(c.CallOptions.ReportInventory):len(c.CallOptions.ReportInventory)], opts...) + opts = append((*c.CallOptions).ReportInventory[0:len((*c.CallOptions).ReportInventory):len((*c.CallOptions).ReportInventory)], opts...) var resp *agentendpointpb.ReportInventoryResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/osconfig/agentendpoint/apiv1/agent_endpoint_client_example_test.go b/osconfig/agentendpoint/apiv1/agent_endpoint_client_example_test.go index 2068d60ecc3f..1067dd3a3285 100644 --- a/osconfig/agentendpoint/apiv1/agent_endpoint_client_example_test.go +++ b/osconfig/agentendpoint/apiv1/agent_endpoint_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_StartNextTask() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.StartNextTaskRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleClient_StartNextTask() { } func ExampleClient_ReportTaskProgress() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.ReportTaskProgressRequest{ // TODO: Fill request struct fields. @@ -74,13 +74,12 @@ func ExampleClient_ReportTaskProgress() { } func ExampleClient_ReportTaskComplete() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.ReportTaskCompleteRequest{ // TODO: Fill request struct fields. @@ -94,13 +93,12 @@ func ExampleClient_ReportTaskComplete() { } func ExampleClient_RegisterAgent() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.RegisterAgentRequest{ // TODO: Fill request struct fields. @@ -114,13 +112,12 @@ func ExampleClient_RegisterAgent() { } func ExampleClient_ReportInventory() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.ReportInventoryRequest{ // TODO: Fill request struct fields. diff --git a/osconfig/agentendpoint/apiv1/doc.go b/osconfig/agentendpoint/apiv1/doc.go index 33b8ebdd6157..26fda8549217 100644 --- a/osconfig/agentendpoint/apiv1/doc.go +++ b/osconfig/agentendpoint/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package agentendpoint // import "cloud.google.com/go/osconfig/agentendpoint/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/osconfig/agentendpoint/apiv1beta/agent_endpoint_client.go b/osconfig/agentendpoint/apiv1beta/agent_endpoint_client.go index c2bd56376a19..28ec9dcc8ad3 100644 --- a/osconfig/agentendpoint/apiv1beta/agent_endpoint_client.go +++ b/osconfig/agentendpoint/apiv1beta/agent_endpoint_client.go @@ -43,7 +43,7 @@ type CallOptions struct { RegisterAgent []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("osconfig.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("osconfig.mtls.googleapis.com:443"), @@ -130,32 +130,111 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud OS Config API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ReceiveTaskNotification(context.Context, *agentendpointpb.ReceiveTaskNotificationRequest, ...gax.CallOption) (agentendpointpb.AgentEndpointService_ReceiveTaskNotificationClient, error) + StartNextTask(context.Context, *agentendpointpb.StartNextTaskRequest, ...gax.CallOption) (*agentendpointpb.StartNextTaskResponse, error) + ReportTaskProgress(context.Context, *agentendpointpb.ReportTaskProgressRequest, ...gax.CallOption) (*agentendpointpb.ReportTaskProgressResponse, error) + ReportTaskComplete(context.Context, *agentendpointpb.ReportTaskCompleteRequest, ...gax.CallOption) (*agentendpointpb.ReportTaskCompleteResponse, error) + LookupEffectiveGuestPolicy(context.Context, *agentendpointpb.LookupEffectiveGuestPolicyRequest, ...gax.CallOption) (*agentendpointpb.EffectiveGuestPolicy, error) + RegisterAgent(context.Context, *agentendpointpb.RegisterAgentRequest, ...gax.CallOption) (*agentendpointpb.RegisterAgentResponse, error) +} + // Client is a client for interacting with Cloud OS Config API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// OS Config agent endpoint API. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ReceiveTaskNotification stream established by client to receive Task notifications. +func (c *Client) ReceiveTaskNotification(ctx context.Context, req *agentendpointpb.ReceiveTaskNotificationRequest, opts ...gax.CallOption) (agentendpointpb.AgentEndpointService_ReceiveTaskNotificationClient, error) { + return c.internalClient.ReceiveTaskNotification(ctx, req, opts...) +} + +// StartNextTask signals the start of a task execution and returns the task info. +func (c *Client) StartNextTask(ctx context.Context, req *agentendpointpb.StartNextTaskRequest, opts ...gax.CallOption) (*agentendpointpb.StartNextTaskResponse, error) { + return c.internalClient.StartNextTask(ctx, req, opts...) +} + +// ReportTaskProgress signals an intermediary progress checkpoint in task execution. +func (c *Client) ReportTaskProgress(ctx context.Context, req *agentendpointpb.ReportTaskProgressRequest, opts ...gax.CallOption) (*agentendpointpb.ReportTaskProgressResponse, error) { + return c.internalClient.ReportTaskProgress(ctx, req, opts...) +} + +// ReportTaskComplete signals that the task execution is complete and optionally returns the next +// task. +func (c *Client) ReportTaskComplete(ctx context.Context, req *agentendpointpb.ReportTaskCompleteRequest, opts ...gax.CallOption) (*agentendpointpb.ReportTaskCompleteResponse, error) { + return c.internalClient.ReportTaskComplete(ctx, req, opts...) +} + +// LookupEffectiveGuestPolicy lookup the effective guest policy that applies to a VM instance. This +// lookup merges all policies that are assigned to the instance ancestry. +func (c *Client) LookupEffectiveGuestPolicy(ctx context.Context, req *agentendpointpb.LookupEffectiveGuestPolicyRequest, opts ...gax.CallOption) (*agentendpointpb.EffectiveGuestPolicy, error) { + return c.internalClient.LookupEffectiveGuestPolicy(ctx, req, opts...) +} + +// RegisterAgent registers the agent running on the VM. +func (c *Client) RegisterAgent(ctx context.Context, req *agentendpointpb.RegisterAgentRequest, opts ...gax.CallOption) (*agentendpointpb.RegisterAgentResponse, error) { + return c.internalClient.RegisterAgent(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud OS Config API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client agentendpointpb.AgentEndpointServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new agent endpoint service client. +// NewClient creates a new agent endpoint service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // OS Config agent endpoint API. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -173,44 +252,45 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: agentendpointpb.NewAgentEndpointServiceClient(connPool), + client: agentendpointpb.NewAgentEndpointServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ReceiveTaskNotification stream established by client to receive Task notifications. -func (c *Client) ReceiveTaskNotification(ctx context.Context, req *agentendpointpb.ReceiveTaskNotificationRequest, opts ...gax.CallOption) (agentendpointpb.AgentEndpointService_ReceiveTaskNotificationClient, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ReceiveTaskNotification(ctx context.Context, req *agentendpointpb.ReceiveTaskNotificationRequest, opts ...gax.CallOption) (agentendpointpb.AgentEndpointService_ReceiveTaskNotificationClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ReceiveTaskNotification[0:len(c.CallOptions.ReceiveTaskNotification):len(c.CallOptions.ReceiveTaskNotification)], opts...) var resp agentendpointpb.AgentEndpointService_ReceiveTaskNotificationClient err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -223,15 +303,14 @@ func (c *Client) ReceiveTaskNotification(ctx context.Context, req *agentendpoint return resp, nil } -// StartNextTask signals the start of a task execution and returns the task info. -func (c *Client) StartNextTask(ctx context.Context, req *agentendpointpb.StartNextTaskRequest, opts ...gax.CallOption) (*agentendpointpb.StartNextTaskResponse, error) { +func (c *gRPCClient) StartNextTask(ctx context.Context, req *agentendpointpb.StartNextTaskRequest, opts ...gax.CallOption) (*agentendpointpb.StartNextTaskResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.StartNextTask[0:len(c.CallOptions.StartNextTask):len(c.CallOptions.StartNextTask)], opts...) + opts = append((*c.CallOptions).StartNextTask[0:len((*c.CallOptions).StartNextTask):len((*c.CallOptions).StartNextTask)], opts...) var resp *agentendpointpb.StartNextTaskResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -244,15 +323,14 @@ func (c *Client) StartNextTask(ctx context.Context, req *agentendpointpb.StartNe return resp, nil } -// ReportTaskProgress signals an intermediary progress checkpoint in task execution. -func (c *Client) ReportTaskProgress(ctx context.Context, req *agentendpointpb.ReportTaskProgressRequest, opts ...gax.CallOption) (*agentendpointpb.ReportTaskProgressResponse, error) { +func (c *gRPCClient) ReportTaskProgress(ctx context.Context, req *agentendpointpb.ReportTaskProgressRequest, opts ...gax.CallOption) (*agentendpointpb.ReportTaskProgressResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ReportTaskProgress[0:len(c.CallOptions.ReportTaskProgress):len(c.CallOptions.ReportTaskProgress)], opts...) + opts = append((*c.CallOptions).ReportTaskProgress[0:len((*c.CallOptions).ReportTaskProgress):len((*c.CallOptions).ReportTaskProgress)], opts...) var resp *agentendpointpb.ReportTaskProgressResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -265,16 +343,14 @@ func (c *Client) ReportTaskProgress(ctx context.Context, req *agentendpointpb.Re return resp, nil } -// ReportTaskComplete signals that the task execution is complete and optionally returns the next -// task. -func (c *Client) ReportTaskComplete(ctx context.Context, req *agentendpointpb.ReportTaskCompleteRequest, opts ...gax.CallOption) (*agentendpointpb.ReportTaskCompleteResponse, error) { +func (c *gRPCClient) ReportTaskComplete(ctx context.Context, req *agentendpointpb.ReportTaskCompleteRequest, opts ...gax.CallOption) (*agentendpointpb.ReportTaskCompleteResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ReportTaskComplete[0:len(c.CallOptions.ReportTaskComplete):len(c.CallOptions.ReportTaskComplete)], opts...) + opts = append((*c.CallOptions).ReportTaskComplete[0:len((*c.CallOptions).ReportTaskComplete):len((*c.CallOptions).ReportTaskComplete)], opts...) var resp *agentendpointpb.ReportTaskCompleteResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -287,16 +363,14 @@ func (c *Client) ReportTaskComplete(ctx context.Context, req *agentendpointpb.Re return resp, nil } -// LookupEffectiveGuestPolicy lookup the effective guest policy that applies to a VM instance. This -// lookup merges all policies that are assigned to the instance ancestry. -func (c *Client) LookupEffectiveGuestPolicy(ctx context.Context, req *agentendpointpb.LookupEffectiveGuestPolicyRequest, opts ...gax.CallOption) (*agentendpointpb.EffectiveGuestPolicy, error) { +func (c *gRPCClient) LookupEffectiveGuestPolicy(ctx context.Context, req *agentendpointpb.LookupEffectiveGuestPolicyRequest, opts ...gax.CallOption) (*agentendpointpb.EffectiveGuestPolicy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.LookupEffectiveGuestPolicy[0:len(c.CallOptions.LookupEffectiveGuestPolicy):len(c.CallOptions.LookupEffectiveGuestPolicy)], opts...) + opts = append((*c.CallOptions).LookupEffectiveGuestPolicy[0:len((*c.CallOptions).LookupEffectiveGuestPolicy):len((*c.CallOptions).LookupEffectiveGuestPolicy)], opts...) var resp *agentendpointpb.EffectiveGuestPolicy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -309,15 +383,14 @@ func (c *Client) LookupEffectiveGuestPolicy(ctx context.Context, req *agentendpo return resp, nil } -// RegisterAgent registers the agent running on the VM. -func (c *Client) RegisterAgent(ctx context.Context, req *agentendpointpb.RegisterAgentRequest, opts ...gax.CallOption) (*agentendpointpb.RegisterAgentResponse, error) { +func (c *gRPCClient) RegisterAgent(ctx context.Context, req *agentendpointpb.RegisterAgentRequest, opts ...gax.CallOption) (*agentendpointpb.RegisterAgentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.RegisterAgent[0:len(c.CallOptions.RegisterAgent):len(c.CallOptions.RegisterAgent)], opts...) + opts = append((*c.CallOptions).RegisterAgent[0:len((*c.CallOptions).RegisterAgent):len((*c.CallOptions).RegisterAgent)], opts...) var resp *agentendpointpb.RegisterAgentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/osconfig/agentendpoint/apiv1beta/agent_endpoint_client_example_test.go b/osconfig/agentendpoint/apiv1beta/agent_endpoint_client_example_test.go index 890e3a16fc2c..1a5800958115 100644 --- a/osconfig/agentendpoint/apiv1beta/agent_endpoint_client_example_test.go +++ b/osconfig/agentendpoint/apiv1beta/agent_endpoint_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_StartNextTask() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1beta" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.StartNextTaskRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleClient_StartNextTask() { } func ExampleClient_ReportTaskProgress() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1beta" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.ReportTaskProgressRequest{ // TODO: Fill request struct fields. @@ -74,13 +74,12 @@ func ExampleClient_ReportTaskProgress() { } func ExampleClient_ReportTaskComplete() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1beta" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.ReportTaskCompleteRequest{ // TODO: Fill request struct fields. @@ -94,13 +93,12 @@ func ExampleClient_ReportTaskComplete() { } func ExampleClient_LookupEffectiveGuestPolicy() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1beta" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.LookupEffectiveGuestPolicyRequest{ // TODO: Fill request struct fields. @@ -114,13 +112,12 @@ func ExampleClient_LookupEffectiveGuestPolicy() { } func ExampleClient_RegisterAgent() { - // import agentendpointpb "google.golang.org/genproto/googleapis/cloud/osconfig/agentendpoint/v1beta" - ctx := context.Background() c, err := agentendpoint.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &agentendpointpb.RegisterAgentRequest{ // TODO: Fill request struct fields. diff --git a/osconfig/agentendpoint/apiv1beta/doc.go b/osconfig/agentendpoint/apiv1beta/doc.go index 544cb79b9b83..6842d1813802 100644 --- a/osconfig/agentendpoint/apiv1beta/doc.go +++ b/osconfig/agentendpoint/apiv1beta/doc.go @@ -20,6 +20,8 @@ // OS management tools that can be used for patch management, patch // compliance, and configuration management on VM instances. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package agentendpoint // import "cloud.google.com/go/osconfig/agentendpoint/apiv1beta" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/osconfig/apiv1/doc.go b/osconfig/apiv1/doc.go index 1ffe83b1e54d..1065817fc701 100644 --- a/osconfig/apiv1/doc.go +++ b/osconfig/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package osconfig // import "cloud.google.com/go/osconfig/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/osconfig/apiv1/os_config_client.go b/osconfig/apiv1/os_config_client.go index 1b563805f523..ca51fed3fa25 100644 --- a/osconfig/apiv1/os_config_client.go +++ b/osconfig/apiv1/os_config_client.go @@ -50,7 +50,7 @@ type CallOptions struct { DeletePatchDeployment []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("osconfig.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("osconfig.mtls.googleapis.com:443"), @@ -166,35 +166,135 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from OS Config API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ExecutePatchJob(context.Context, *osconfigpb.ExecutePatchJobRequest, ...gax.CallOption) (*osconfigpb.PatchJob, error) + GetPatchJob(context.Context, *osconfigpb.GetPatchJobRequest, ...gax.CallOption) (*osconfigpb.PatchJob, error) + CancelPatchJob(context.Context, *osconfigpb.CancelPatchJobRequest, ...gax.CallOption) (*osconfigpb.PatchJob, error) + ListPatchJobs(context.Context, *osconfigpb.ListPatchJobsRequest, ...gax.CallOption) *PatchJobIterator + ListPatchJobInstanceDetails(context.Context, *osconfigpb.ListPatchJobInstanceDetailsRequest, ...gax.CallOption) *PatchJobInstanceDetailsIterator + CreatePatchDeployment(context.Context, *osconfigpb.CreatePatchDeploymentRequest, ...gax.CallOption) (*osconfigpb.PatchDeployment, error) + GetPatchDeployment(context.Context, *osconfigpb.GetPatchDeploymentRequest, ...gax.CallOption) (*osconfigpb.PatchDeployment, error) + ListPatchDeployments(context.Context, *osconfigpb.ListPatchDeploymentsRequest, ...gax.CallOption) *PatchDeploymentIterator + DeletePatchDeployment(context.Context, *osconfigpb.DeletePatchDeploymentRequest, ...gax.CallOption) error +} + // Client is a client for interacting with OS Config API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// OS Config API +// +// The OS Config service is a server-side component that you can use to +// manage package installations and patch jobs for virtual machine instances. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ExecutePatchJob patch VM instances by creating and running a patch job. +func (c *Client) ExecutePatchJob(ctx context.Context, req *osconfigpb.ExecutePatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { + return c.internalClient.ExecutePatchJob(ctx, req, opts...) +} + +// GetPatchJob get the patch job. This can be used to track the progress of an +// ongoing patch job or review the details of completed jobs. +func (c *Client) GetPatchJob(ctx context.Context, req *osconfigpb.GetPatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { + return c.internalClient.GetPatchJob(ctx, req, opts...) +} + +// CancelPatchJob cancel a patch job. The patch job must be active. Canceled patch jobs +// cannot be restarted. +func (c *Client) CancelPatchJob(ctx context.Context, req *osconfigpb.CancelPatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { + return c.internalClient.CancelPatchJob(ctx, req, opts...) +} + +// ListPatchJobs get a list of patch jobs. +func (c *Client) ListPatchJobs(ctx context.Context, req *osconfigpb.ListPatchJobsRequest, opts ...gax.CallOption) *PatchJobIterator { + return c.internalClient.ListPatchJobs(ctx, req, opts...) +} + +// ListPatchJobInstanceDetails get a list of instance details for a given patch job. +func (c *Client) ListPatchJobInstanceDetails(ctx context.Context, req *osconfigpb.ListPatchJobInstanceDetailsRequest, opts ...gax.CallOption) *PatchJobInstanceDetailsIterator { + return c.internalClient.ListPatchJobInstanceDetails(ctx, req, opts...) +} + +// CreatePatchDeployment create an OS Config patch deployment. +func (c *Client) CreatePatchDeployment(ctx context.Context, req *osconfigpb.CreatePatchDeploymentRequest, opts ...gax.CallOption) (*osconfigpb.PatchDeployment, error) { + return c.internalClient.CreatePatchDeployment(ctx, req, opts...) +} + +// GetPatchDeployment get an OS Config patch deployment. +func (c *Client) GetPatchDeployment(ctx context.Context, req *osconfigpb.GetPatchDeploymentRequest, opts ...gax.CallOption) (*osconfigpb.PatchDeployment, error) { + return c.internalClient.GetPatchDeployment(ctx, req, opts...) +} + +// ListPatchDeployments get a page of OS Config patch deployments. +func (c *Client) ListPatchDeployments(ctx context.Context, req *osconfigpb.ListPatchDeploymentsRequest, opts ...gax.CallOption) *PatchDeploymentIterator { + return c.internalClient.ListPatchDeployments(ctx, req, opts...) +} + +// DeletePatchDeployment delete an OS Config patch deployment. +func (c *Client) DeletePatchDeployment(ctx context.Context, req *osconfigpb.DeletePatchDeploymentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeletePatchDeployment(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with OS Config API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client osconfigpb.OsConfigServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new os config service client. +// NewClient creates a new os config service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // OS Config API // // The OS Config service is a server-side component that you can use to // manage package installations and patch jobs for virtual machine instances. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -212,42 +312,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: osconfigpb.NewOsConfigServiceClient(connPool), + client: osconfigpb.NewOsConfigServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ExecutePatchJob patch VM instances by creating and running a patch job. -func (c *Client) ExecutePatchJob(ctx context.Context, req *osconfigpb.ExecutePatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ExecutePatchJob(ctx context.Context, req *osconfigpb.ExecutePatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -255,7 +357,7 @@ func (c *Client) ExecutePatchJob(ctx context.Context, req *osconfigpb.ExecutePat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExecutePatchJob[0:len(c.CallOptions.ExecutePatchJob):len(c.CallOptions.ExecutePatchJob)], opts...) + opts = append((*c.CallOptions).ExecutePatchJob[0:len((*c.CallOptions).ExecutePatchJob):len((*c.CallOptions).ExecutePatchJob)], opts...) var resp *osconfigpb.PatchJob err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -268,9 +370,7 @@ func (c *Client) ExecutePatchJob(ctx context.Context, req *osconfigpb.ExecutePat return resp, nil } -// GetPatchJob get the patch job. This can be used to track the progress of an -// ongoing patch job or review the details of completed jobs. -func (c *Client) GetPatchJob(ctx context.Context, req *osconfigpb.GetPatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { +func (c *gRPCClient) GetPatchJob(ctx context.Context, req *osconfigpb.GetPatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -278,7 +378,7 @@ func (c *Client) GetPatchJob(ctx context.Context, req *osconfigpb.GetPatchJobReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetPatchJob[0:len(c.CallOptions.GetPatchJob):len(c.CallOptions.GetPatchJob)], opts...) + opts = append((*c.CallOptions).GetPatchJob[0:len((*c.CallOptions).GetPatchJob):len((*c.CallOptions).GetPatchJob)], opts...) var resp *osconfigpb.PatchJob err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -291,9 +391,7 @@ func (c *Client) GetPatchJob(ctx context.Context, req *osconfigpb.GetPatchJobReq return resp, nil } -// CancelPatchJob cancel a patch job. The patch job must be active. Canceled patch jobs -// cannot be restarted. -func (c *Client) CancelPatchJob(ctx context.Context, req *osconfigpb.CancelPatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { +func (c *gRPCClient) CancelPatchJob(ctx context.Context, req *osconfigpb.CancelPatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -301,7 +399,7 @@ func (c *Client) CancelPatchJob(ctx context.Context, req *osconfigpb.CancelPatch } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CancelPatchJob[0:len(c.CallOptions.CancelPatchJob):len(c.CallOptions.CancelPatchJob)], opts...) + opts = append((*c.CallOptions).CancelPatchJob[0:len((*c.CallOptions).CancelPatchJob):len((*c.CallOptions).CancelPatchJob)], opts...) var resp *osconfigpb.PatchJob err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -314,11 +412,10 @@ func (c *Client) CancelPatchJob(ctx context.Context, req *osconfigpb.CancelPatch return resp, nil } -// ListPatchJobs get a list of patch jobs. -func (c *Client) ListPatchJobs(ctx context.Context, req *osconfigpb.ListPatchJobsRequest, opts ...gax.CallOption) *PatchJobIterator { +func (c *gRPCClient) ListPatchJobs(ctx context.Context, req *osconfigpb.ListPatchJobsRequest, opts ...gax.CallOption) *PatchJobIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListPatchJobs[0:len(c.CallOptions.ListPatchJobs):len(c.CallOptions.ListPatchJobs)], opts...) + opts = append((*c.CallOptions).ListPatchJobs[0:len((*c.CallOptions).ListPatchJobs):len((*c.CallOptions).ListPatchJobs)], opts...) it := &PatchJobIterator{} req = proto.Clone(req).(*osconfigpb.ListPatchJobsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.PatchJob, string, error) { @@ -355,11 +452,10 @@ func (c *Client) ListPatchJobs(ctx context.Context, req *osconfigpb.ListPatchJob return it } -// ListPatchJobInstanceDetails get a list of instance details for a given patch job. -func (c *Client) ListPatchJobInstanceDetails(ctx context.Context, req *osconfigpb.ListPatchJobInstanceDetailsRequest, opts ...gax.CallOption) *PatchJobInstanceDetailsIterator { +func (c *gRPCClient) ListPatchJobInstanceDetails(ctx context.Context, req *osconfigpb.ListPatchJobInstanceDetailsRequest, opts ...gax.CallOption) *PatchJobInstanceDetailsIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListPatchJobInstanceDetails[0:len(c.CallOptions.ListPatchJobInstanceDetails):len(c.CallOptions.ListPatchJobInstanceDetails)], opts...) + opts = append((*c.CallOptions).ListPatchJobInstanceDetails[0:len((*c.CallOptions).ListPatchJobInstanceDetails):len((*c.CallOptions).ListPatchJobInstanceDetails)], opts...) it := &PatchJobInstanceDetailsIterator{} req = proto.Clone(req).(*osconfigpb.ListPatchJobInstanceDetailsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.PatchJobInstanceDetails, string, error) { @@ -396,8 +492,7 @@ func (c *Client) ListPatchJobInstanceDetails(ctx context.Context, req *osconfigp return it } -// CreatePatchDeployment create an OS Config patch deployment. -func (c *Client) CreatePatchDeployment(ctx context.Context, req *osconfigpb.CreatePatchDeploymentRequest, opts ...gax.CallOption) (*osconfigpb.PatchDeployment, error) { +func (c *gRPCClient) CreatePatchDeployment(ctx context.Context, req *osconfigpb.CreatePatchDeploymentRequest, opts ...gax.CallOption) (*osconfigpb.PatchDeployment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -405,7 +500,7 @@ func (c *Client) CreatePatchDeployment(ctx context.Context, req *osconfigpb.Crea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreatePatchDeployment[0:len(c.CallOptions.CreatePatchDeployment):len(c.CallOptions.CreatePatchDeployment)], opts...) + opts = append((*c.CallOptions).CreatePatchDeployment[0:len((*c.CallOptions).CreatePatchDeployment):len((*c.CallOptions).CreatePatchDeployment)], opts...) var resp *osconfigpb.PatchDeployment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -418,8 +513,7 @@ func (c *Client) CreatePatchDeployment(ctx context.Context, req *osconfigpb.Crea return resp, nil } -// GetPatchDeployment get an OS Config patch deployment. -func (c *Client) GetPatchDeployment(ctx context.Context, req *osconfigpb.GetPatchDeploymentRequest, opts ...gax.CallOption) (*osconfigpb.PatchDeployment, error) { +func (c *gRPCClient) GetPatchDeployment(ctx context.Context, req *osconfigpb.GetPatchDeploymentRequest, opts ...gax.CallOption) (*osconfigpb.PatchDeployment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -427,7 +521,7 @@ func (c *Client) GetPatchDeployment(ctx context.Context, req *osconfigpb.GetPatc } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetPatchDeployment[0:len(c.CallOptions.GetPatchDeployment):len(c.CallOptions.GetPatchDeployment)], opts...) + opts = append((*c.CallOptions).GetPatchDeployment[0:len((*c.CallOptions).GetPatchDeployment):len((*c.CallOptions).GetPatchDeployment)], opts...) var resp *osconfigpb.PatchDeployment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -440,11 +534,10 @@ func (c *Client) GetPatchDeployment(ctx context.Context, req *osconfigpb.GetPatc return resp, nil } -// ListPatchDeployments get a page of OS Config patch deployments. -func (c *Client) ListPatchDeployments(ctx context.Context, req *osconfigpb.ListPatchDeploymentsRequest, opts ...gax.CallOption) *PatchDeploymentIterator { +func (c *gRPCClient) ListPatchDeployments(ctx context.Context, req *osconfigpb.ListPatchDeploymentsRequest, opts ...gax.CallOption) *PatchDeploymentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListPatchDeployments[0:len(c.CallOptions.ListPatchDeployments):len(c.CallOptions.ListPatchDeployments)], opts...) + opts = append((*c.CallOptions).ListPatchDeployments[0:len((*c.CallOptions).ListPatchDeployments):len((*c.CallOptions).ListPatchDeployments)], opts...) it := &PatchDeploymentIterator{} req = proto.Clone(req).(*osconfigpb.ListPatchDeploymentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.PatchDeployment, string, error) { @@ -481,8 +574,7 @@ func (c *Client) ListPatchDeployments(ctx context.Context, req *osconfigpb.ListP return it } -// DeletePatchDeployment delete an OS Config patch deployment. -func (c *Client) DeletePatchDeployment(ctx context.Context, req *osconfigpb.DeletePatchDeploymentRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeletePatchDeployment(ctx context.Context, req *osconfigpb.DeletePatchDeploymentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -490,7 +582,7 @@ func (c *Client) DeletePatchDeployment(ctx context.Context, req *osconfigpb.Dele } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeletePatchDeployment[0:len(c.CallOptions.DeletePatchDeployment):len(c.CallOptions.DeletePatchDeployment)], opts...) + opts = append((*c.CallOptions).DeletePatchDeployment[0:len((*c.CallOptions).DeletePatchDeployment):len((*c.CallOptions).DeletePatchDeployment)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeletePatchDeployment(ctx, req, settings.GRPC...) diff --git a/osconfig/apiv1/os_config_client_example_test.go b/osconfig/apiv1/os_config_client_example_test.go index 61988b35e7cb..98f24edea6fa 100644 --- a/osconfig/apiv1/os_config_client_example_test.go +++ b/osconfig/apiv1/os_config_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ExecutePatchJob() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ExecutePatchJobRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleClient_ExecutePatchJob() { } func ExampleClient_GetPatchJob() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.GetPatchJobRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleClient_GetPatchJob() { } func ExampleClient_CancelPatchJob() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.CancelPatchJobRequest{ // TODO: Fill request struct fields. @@ -95,14 +94,12 @@ func ExampleClient_CancelPatchJob() { } func ExampleClient_ListPatchJobs() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListPatchJobsRequest{ // TODO: Fill request struct fields. @@ -122,14 +119,12 @@ func ExampleClient_ListPatchJobs() { } func ExampleClient_ListPatchJobInstanceDetails() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListPatchJobInstanceDetailsRequest{ // TODO: Fill request struct fields. @@ -149,13 +144,12 @@ func ExampleClient_ListPatchJobInstanceDetails() { } func ExampleClient_CreatePatchDeployment() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.CreatePatchDeploymentRequest{ // TODO: Fill request struct fields. @@ -169,13 +163,12 @@ func ExampleClient_CreatePatchDeployment() { } func ExampleClient_GetPatchDeployment() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.GetPatchDeploymentRequest{ // TODO: Fill request struct fields. @@ -189,14 +182,12 @@ func ExampleClient_GetPatchDeployment() { } func ExampleClient_ListPatchDeployments() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListPatchDeploymentsRequest{ // TODO: Fill request struct fields. @@ -221,6 +212,7 @@ func ExampleClient_DeletePatchDeployment() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.DeletePatchDeploymentRequest{ // TODO: Fill request struct fields. diff --git a/osconfig/apiv1alpha/doc.go b/osconfig/apiv1alpha/doc.go index ed40c29ec4a0..44f26c689515 100644 --- a/osconfig/apiv1alpha/doc.go +++ b/osconfig/apiv1alpha/doc.go @@ -20,6 +20,8 @@ // OS management tools that can be used for patch management, patch // compliance, and configuration management on VM instances. // +// NOTE: This package is in alpha. It is not stable, and is likely to change. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package osconfig // import "cloud.google.com/go/osconfig/apiv1alpha" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/osconfig/apiv1alpha/gapic_metadata.json b/osconfig/apiv1alpha/gapic_metadata.json index 68645256d0c3..7a423634f9b5 100644 --- a/osconfig/apiv1alpha/gapic_metadata.json +++ b/osconfig/apiv1alpha/gapic_metadata.json @@ -1,72 +1,72 @@ { - "schema": "1.0", - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods.", - "language": "go", - "protoPackage": "google.cloud.osconfig.v1alpha", - "libraryPackage": "cloud.google.com/go/osconfig/apiv1alpha", - "services": { - "OsConfigZonalService": { - "clients": { - "grpc": { - "libraryClient": "OsConfigZonalClient", - "rpcs": { - "CreateOSPolicyAssignment": { - "methods": [ + "schema": "1.0", + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods.", + "language": "go", + "protoPackage": "google.cloud.osconfig.v1alpha", + "libraryPackage": "cloud.google.com/go/osconfig/apiv1alpha", + "services": { + "OsConfigZonalService": { + "clients": { + "grpc": { + "libraryClient": "OsConfigZonalClient", + "rpcs": { + "CreateOSPolicyAssignment": { + "methods": [ "CreateOSPolicyAssignment" ] }, - "DeleteOSPolicyAssignment": { - "methods": [ + "DeleteOSPolicyAssignment": { + "methods": [ "DeleteOSPolicyAssignment" ] }, - "GetInstanceOSPoliciesCompliance": { - "methods": [ + "GetInstanceOSPoliciesCompliance": { + "methods": [ "GetInstanceOSPoliciesCompliance" ] }, - "GetInventory": { - "methods": [ + "GetInventory": { + "methods": [ "GetInventory" ] }, - "GetOSPolicyAssignment": { - "methods": [ + "GetOSPolicyAssignment": { + "methods": [ "GetOSPolicyAssignment" ] }, - "GetVulnerabilityReport": { - "methods": [ + "GetVulnerabilityReport": { + "methods": [ "GetVulnerabilityReport" ] }, - "ListInstanceOSPoliciesCompliances": { - "methods": [ + "ListInstanceOSPoliciesCompliances": { + "methods": [ "ListInstanceOSPoliciesCompliances" ] }, - "ListInventories": { - "methods": [ + "ListInventories": { + "methods": [ "ListInventories" ] }, - "ListOSPolicyAssignmentRevisions": { - "methods": [ + "ListOSPolicyAssignmentRevisions": { + "methods": [ "ListOSPolicyAssignmentRevisions" ] }, - "ListOSPolicyAssignments": { - "methods": [ + "ListOSPolicyAssignments": { + "methods": [ "ListOSPolicyAssignments" ] }, - "ListVulnerabilityReports": { - "methods": [ + "ListVulnerabilityReports": { + "methods": [ "ListVulnerabilityReports" ] }, - "UpdateOSPolicyAssignment": { - "methods": [ + "UpdateOSPolicyAssignment": { + "methods": [ "UpdateOSPolicyAssignment" ] } diff --git a/osconfig/apiv1alpha/os_config_zonal_client.go b/osconfig/apiv1alpha/os_config_zonal_client.go index 8974653f396d..b60fda5e324a 100644 --- a/osconfig/apiv1alpha/os_config_zonal_client.go +++ b/osconfig/apiv1alpha/os_config_zonal_client.go @@ -56,7 +56,7 @@ type OsConfigZonalCallOptions struct { ListVulnerabilityReports []gax.CallOption } -func defaultOsConfigZonalClientOptions() []option.ClientOption { +func defaultOsConfigZonalGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("osconfig.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("osconfig.mtls.googleapis.com:443"), @@ -205,40 +205,219 @@ func defaultOsConfigZonalCallOptions() *OsConfigZonalCallOptions { } } +// internalOsConfigZonalClient is an interface that defines the methods availaible from OS Config API. +type internalOsConfigZonalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateOSPolicyAssignment(context.Context, *osconfigpb.CreateOSPolicyAssignmentRequest, ...gax.CallOption) (*CreateOSPolicyAssignmentOperation, error) + CreateOSPolicyAssignmentOperation(name string) *CreateOSPolicyAssignmentOperation + UpdateOSPolicyAssignment(context.Context, *osconfigpb.UpdateOSPolicyAssignmentRequest, ...gax.CallOption) (*UpdateOSPolicyAssignmentOperation, error) + UpdateOSPolicyAssignmentOperation(name string) *UpdateOSPolicyAssignmentOperation + GetOSPolicyAssignment(context.Context, *osconfigpb.GetOSPolicyAssignmentRequest, ...gax.CallOption) (*osconfigpb.OSPolicyAssignment, error) + ListOSPolicyAssignments(context.Context, *osconfigpb.ListOSPolicyAssignmentsRequest, ...gax.CallOption) *OSPolicyAssignmentIterator + ListOSPolicyAssignmentRevisions(context.Context, *osconfigpb.ListOSPolicyAssignmentRevisionsRequest, ...gax.CallOption) *OSPolicyAssignmentIterator + DeleteOSPolicyAssignment(context.Context, *osconfigpb.DeleteOSPolicyAssignmentRequest, ...gax.CallOption) (*DeleteOSPolicyAssignmentOperation, error) + DeleteOSPolicyAssignmentOperation(name string) *DeleteOSPolicyAssignmentOperation + GetInstanceOSPoliciesCompliance(context.Context, *osconfigpb.GetInstanceOSPoliciesComplianceRequest, ...gax.CallOption) (*osconfigpb.InstanceOSPoliciesCompliance, error) + ListInstanceOSPoliciesCompliances(context.Context, *osconfigpb.ListInstanceOSPoliciesCompliancesRequest, ...gax.CallOption) *InstanceOSPoliciesComplianceIterator + GetInventory(context.Context, *osconfigpb.GetInventoryRequest, ...gax.CallOption) (*osconfigpb.Inventory, error) + ListInventories(context.Context, *osconfigpb.ListInventoriesRequest, ...gax.CallOption) *InventoryIterator + GetVulnerabilityReport(context.Context, *osconfigpb.GetVulnerabilityReportRequest, ...gax.CallOption) (*osconfigpb.VulnerabilityReport, error) + ListVulnerabilityReports(context.Context, *osconfigpb.ListVulnerabilityReportsRequest, ...gax.CallOption) *VulnerabilityReportIterator +} + // OsConfigZonalClient is a client for interacting with OS Config API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Zonal OS Config API +// +// The OS Config service is the server-side component that allows users to +// manage package installations and patch jobs for Compute Engine VM instances. type OsConfigZonalClient struct { + // The internal transport-dependent client. + internalClient internalOsConfigZonalClient + + // The call options for this service. + CallOptions *OsConfigZonalCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *OsConfigZonalClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *OsConfigZonalClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *OsConfigZonalClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateOSPolicyAssignment create an OS policy assignment. +// +// This method also creates the first revision of the OS policy assignment. +// +// This method returns a long running operation (LRO) that contains the +// rollout details. The rollout can be cancelled by cancelling the LRO. +// +// For more information, see Method: +// projects.locations.osPolicyAssignments.operations.cancel (at https://cloud.google.com/compute/docs/osconfig/rest/v1alpha/projects.locations.osPolicyAssignments.operations/cancel). +func (c *OsConfigZonalClient) CreateOSPolicyAssignment(ctx context.Context, req *osconfigpb.CreateOSPolicyAssignmentRequest, opts ...gax.CallOption) (*CreateOSPolicyAssignmentOperation, error) { + return c.internalClient.CreateOSPolicyAssignment(ctx, req, opts...) +} + +// CreateOSPolicyAssignmentOperation returns a new CreateOSPolicyAssignmentOperation from a given name. +// The name must be that of a previously created CreateOSPolicyAssignmentOperation, possibly from a different process. +func (c *OsConfigZonalClient) CreateOSPolicyAssignmentOperation(name string) *CreateOSPolicyAssignmentOperation { + return c.internalClient.CreateOSPolicyAssignmentOperation(name) +} + +// UpdateOSPolicyAssignment update an existing OS policy assignment. +// +// This method creates a new revision of the OS policy assignment. +// +// This method returns a long running operation (LRO) that contains the +// rollout details. The rollout can be cancelled by cancelling the LRO. +// +// For more information, see Method: +// projects.locations.osPolicyAssignments.operations.cancel (at https://cloud.google.com/compute/docs/osconfig/rest/v1alpha/projects.locations.osPolicyAssignments.operations/cancel). +func (c *OsConfigZonalClient) UpdateOSPolicyAssignment(ctx context.Context, req *osconfigpb.UpdateOSPolicyAssignmentRequest, opts ...gax.CallOption) (*UpdateOSPolicyAssignmentOperation, error) { + return c.internalClient.UpdateOSPolicyAssignment(ctx, req, opts...) +} + +// UpdateOSPolicyAssignmentOperation returns a new UpdateOSPolicyAssignmentOperation from a given name. +// The name must be that of a previously created UpdateOSPolicyAssignmentOperation, possibly from a different process. +func (c *OsConfigZonalClient) UpdateOSPolicyAssignmentOperation(name string) *UpdateOSPolicyAssignmentOperation { + return c.internalClient.UpdateOSPolicyAssignmentOperation(name) +} + +// GetOSPolicyAssignment retrieve an existing OS policy assignment. +// +// This method always returns the latest revision. In order to retrieve a +// previous revision of the assignment, also provide the revision ID in the +// name parameter. +func (c *OsConfigZonalClient) GetOSPolicyAssignment(ctx context.Context, req *osconfigpb.GetOSPolicyAssignmentRequest, opts ...gax.CallOption) (*osconfigpb.OSPolicyAssignment, error) { + return c.internalClient.GetOSPolicyAssignment(ctx, req, opts...) +} + +// ListOSPolicyAssignments list the OS policy assignments under the parent resource. +// +// For each OS policy assignment, the latest revision is returned. +func (c *OsConfigZonalClient) ListOSPolicyAssignments(ctx context.Context, req *osconfigpb.ListOSPolicyAssignmentsRequest, opts ...gax.CallOption) *OSPolicyAssignmentIterator { + return c.internalClient.ListOSPolicyAssignments(ctx, req, opts...) +} + +// ListOSPolicyAssignmentRevisions list the OS policy assignment revisions for a given OS policy assignment. +func (c *OsConfigZonalClient) ListOSPolicyAssignmentRevisions(ctx context.Context, req *osconfigpb.ListOSPolicyAssignmentRevisionsRequest, opts ...gax.CallOption) *OSPolicyAssignmentIterator { + return c.internalClient.ListOSPolicyAssignmentRevisions(ctx, req, opts...) +} + +// DeleteOSPolicyAssignment delete the OS policy assignment. +// +// This method creates a new revision of the OS policy assignment. +// +// This method returns a long running operation (LRO) that contains the +// rollout details. The rollout can be cancelled by cancelling the LRO. +// +// If the LRO completes and is not cancelled, all revisions associated with +// the OS policy assignment are deleted. +// +// For more information, see Method: +// projects.locations.osPolicyAssignments.operations.cancel (at https://cloud.google.com/compute/docs/osconfig/rest/v1alpha/projects.locations.osPolicyAssignments.operations/cancel). +func (c *OsConfigZonalClient) DeleteOSPolicyAssignment(ctx context.Context, req *osconfigpb.DeleteOSPolicyAssignmentRequest, opts ...gax.CallOption) (*DeleteOSPolicyAssignmentOperation, error) { + return c.internalClient.DeleteOSPolicyAssignment(ctx, req, opts...) +} + +// DeleteOSPolicyAssignmentOperation returns a new DeleteOSPolicyAssignmentOperation from a given name. +// The name must be that of a previously created DeleteOSPolicyAssignmentOperation, possibly from a different process. +func (c *OsConfigZonalClient) DeleteOSPolicyAssignmentOperation(name string) *DeleteOSPolicyAssignmentOperation { + return c.internalClient.DeleteOSPolicyAssignmentOperation(name) +} + +// GetInstanceOSPoliciesCompliance get OS policies compliance data for the specified Compute Engine VM +// instance. +func (c *OsConfigZonalClient) GetInstanceOSPoliciesCompliance(ctx context.Context, req *osconfigpb.GetInstanceOSPoliciesComplianceRequest, opts ...gax.CallOption) (*osconfigpb.InstanceOSPoliciesCompliance, error) { + return c.internalClient.GetInstanceOSPoliciesCompliance(ctx, req, opts...) +} + +// ListInstanceOSPoliciesCompliances list OS policies compliance data for all Compute Engine VM instances in the +// specified zone. +func (c *OsConfigZonalClient) ListInstanceOSPoliciesCompliances(ctx context.Context, req *osconfigpb.ListInstanceOSPoliciesCompliancesRequest, opts ...gax.CallOption) *InstanceOSPoliciesComplianceIterator { + return c.internalClient.ListInstanceOSPoliciesCompliances(ctx, req, opts...) +} + +// GetInventory get inventory data for the specified VM instance. If the VM has no +// associated inventory, the message NOT_FOUND is returned. +func (c *OsConfigZonalClient) GetInventory(ctx context.Context, req *osconfigpb.GetInventoryRequest, opts ...gax.CallOption) (*osconfigpb.Inventory, error) { + return c.internalClient.GetInventory(ctx, req, opts...) +} + +// ListInventories list inventory data for all VM instances in the specified zone. +func (c *OsConfigZonalClient) ListInventories(ctx context.Context, req *osconfigpb.ListInventoriesRequest, opts ...gax.CallOption) *InventoryIterator { + return c.internalClient.ListInventories(ctx, req, opts...) +} + +// GetVulnerabilityReport gets the vulnerability report for the specified VM instance. Only VMs with +// inventory data have vulnerability reports associated with them. +func (c *OsConfigZonalClient) GetVulnerabilityReport(ctx context.Context, req *osconfigpb.GetVulnerabilityReportRequest, opts ...gax.CallOption) (*osconfigpb.VulnerabilityReport, error) { + return c.internalClient.GetVulnerabilityReport(ctx, req, opts...) +} + +// ListVulnerabilityReports list vulnerability reports for all VM instances in the specified zone. +func (c *OsConfigZonalClient) ListVulnerabilityReports(ctx context.Context, req *osconfigpb.ListVulnerabilityReportsRequest, opts ...gax.CallOption) *VulnerabilityReportIterator { + return c.internalClient.ListVulnerabilityReports(ctx, req, opts...) +} + +// osConfigZonalGRPCClient is a client for interacting with OS Config API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type osConfigZonalGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing OsConfigZonalClient + CallOptions **OsConfigZonalCallOptions + // The gRPC API client. osConfigZonalClient osconfigpb.OsConfigZonalServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *OsConfigZonalCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewOsConfigZonalClient creates a new os config zonal service client. +// NewOsConfigZonalClient creates a new os config zonal service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Zonal OS Config API // // The OS Config service is the server-side component that allows users to // manage package installations and patch jobs for Compute Engine VM instances. func NewOsConfigZonalClient(ctx context.Context, opts ...option.ClientOption) (*OsConfigZonalClient, error) { - clientOpts := defaultOsConfigZonalClientOptions() - + clientOpts := defaultOsConfigZonalGRPCClientOptions() if newOsConfigZonalClientHook != nil { hookOpts, err := newOsConfigZonalClientHook(ctx, clientHookParams{}) if err != nil { @@ -256,16 +435,19 @@ func NewOsConfigZonalClient(ctx context.Context, opts ...option.ClientOption) (* if err != nil { return nil, err } - c := &OsConfigZonalClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultOsConfigZonalCallOptions(), + client := OsConfigZonalClient{CallOptions: defaultOsConfigZonalCallOptions()} + c := &osConfigZonalGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, osConfigZonalClient: osconfigpb.NewOsConfigZonalServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -275,41 +457,33 @@ func NewOsConfigZonalClient(ctx context.Context, opts ...option.ClientOption) (* // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *OsConfigZonalClient) Connection() *grpc.ClientConn { +func (c *osConfigZonalGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *OsConfigZonalClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *OsConfigZonalClient) setGoogleClientInfo(keyval ...string) { +func (c *osConfigZonalGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateOSPolicyAssignment create an OS policy assignment. -// -// This method also creates the first revision of the OS policy assignment. -// -// This method returns a long running operation (LRO) that contains the -// rollout details. The rollout can be cancelled by cancelling the LRO. -// -// For more information, see Method: -// projects.locations.osPolicyAssignments.operations.cancel (at https://cloud.google.com/compute/docs/osconfig/rest/v1alpha/projects.locations.osPolicyAssignments.operations/cancel). -func (c *OsConfigZonalClient) CreateOSPolicyAssignment(ctx context.Context, req *osconfigpb.CreateOSPolicyAssignmentRequest, opts ...gax.CallOption) (*CreateOSPolicyAssignmentOperation, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *osConfigZonalGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *osConfigZonalGRPCClient) CreateOSPolicyAssignment(ctx context.Context, req *osconfigpb.CreateOSPolicyAssignmentRequest, opts ...gax.CallOption) (*CreateOSPolicyAssignmentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -317,7 +491,7 @@ func (c *OsConfigZonalClient) CreateOSPolicyAssignment(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateOSPolicyAssignment[0:len(c.CallOptions.CreateOSPolicyAssignment):len(c.CallOptions.CreateOSPolicyAssignment)], opts...) + opts = append((*c.CallOptions).CreateOSPolicyAssignment[0:len((*c.CallOptions).CreateOSPolicyAssignment):len((*c.CallOptions).CreateOSPolicyAssignment)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -328,20 +502,11 @@ func (c *OsConfigZonalClient) CreateOSPolicyAssignment(ctx context.Context, req return nil, err } return &CreateOSPolicyAssignmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateOSPolicyAssignment update an existing OS policy assignment. -// -// This method creates a new revision of the OS policy assignment. -// -// This method returns a long running operation (LRO) that contains the -// rollout details. The rollout can be cancelled by cancelling the LRO. -// -// For more information, see Method: -// projects.locations.osPolicyAssignments.operations.cancel (at https://cloud.google.com/compute/docs/osconfig/rest/v1alpha/projects.locations.osPolicyAssignments.operations/cancel). -func (c *OsConfigZonalClient) UpdateOSPolicyAssignment(ctx context.Context, req *osconfigpb.UpdateOSPolicyAssignmentRequest, opts ...gax.CallOption) (*UpdateOSPolicyAssignmentOperation, error) { +func (c *osConfigZonalGRPCClient) UpdateOSPolicyAssignment(ctx context.Context, req *osconfigpb.UpdateOSPolicyAssignmentRequest, opts ...gax.CallOption) (*UpdateOSPolicyAssignmentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -349,7 +514,7 @@ func (c *OsConfigZonalClient) UpdateOSPolicyAssignment(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "os_policy_assignment.name", url.QueryEscape(req.GetOsPolicyAssignment().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateOSPolicyAssignment[0:len(c.CallOptions.UpdateOSPolicyAssignment):len(c.CallOptions.UpdateOSPolicyAssignment)], opts...) + opts = append((*c.CallOptions).UpdateOSPolicyAssignment[0:len((*c.CallOptions).UpdateOSPolicyAssignment):len((*c.CallOptions).UpdateOSPolicyAssignment)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -360,16 +525,11 @@ func (c *OsConfigZonalClient) UpdateOSPolicyAssignment(ctx context.Context, req return nil, err } return &UpdateOSPolicyAssignmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetOSPolicyAssignment retrieve an existing OS policy assignment. -// -// This method always returns the latest revision. In order to retrieve a -// previous revision of the assignment, also provide the revision ID in the -// name parameter. -func (c *OsConfigZonalClient) GetOSPolicyAssignment(ctx context.Context, req *osconfigpb.GetOSPolicyAssignmentRequest, opts ...gax.CallOption) (*osconfigpb.OSPolicyAssignment, error) { +func (c *osConfigZonalGRPCClient) GetOSPolicyAssignment(ctx context.Context, req *osconfigpb.GetOSPolicyAssignmentRequest, opts ...gax.CallOption) (*osconfigpb.OSPolicyAssignment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -377,7 +537,7 @@ func (c *OsConfigZonalClient) GetOSPolicyAssignment(ctx context.Context, req *os } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetOSPolicyAssignment[0:len(c.CallOptions.GetOSPolicyAssignment):len(c.CallOptions.GetOSPolicyAssignment)], opts...) + opts = append((*c.CallOptions).GetOSPolicyAssignment[0:len((*c.CallOptions).GetOSPolicyAssignment):len((*c.CallOptions).GetOSPolicyAssignment)], opts...) var resp *osconfigpb.OSPolicyAssignment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -390,13 +550,10 @@ func (c *OsConfigZonalClient) GetOSPolicyAssignment(ctx context.Context, req *os return resp, nil } -// ListOSPolicyAssignments list the OS policy assignments under the parent resource. -// -// For each OS policy assignment, the latest revision is returned. -func (c *OsConfigZonalClient) ListOSPolicyAssignments(ctx context.Context, req *osconfigpb.ListOSPolicyAssignmentsRequest, opts ...gax.CallOption) *OSPolicyAssignmentIterator { +func (c *osConfigZonalGRPCClient) ListOSPolicyAssignments(ctx context.Context, req *osconfigpb.ListOSPolicyAssignmentsRequest, opts ...gax.CallOption) *OSPolicyAssignmentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListOSPolicyAssignments[0:len(c.CallOptions.ListOSPolicyAssignments):len(c.CallOptions.ListOSPolicyAssignments)], opts...) + opts = append((*c.CallOptions).ListOSPolicyAssignments[0:len((*c.CallOptions).ListOSPolicyAssignments):len((*c.CallOptions).ListOSPolicyAssignments)], opts...) it := &OSPolicyAssignmentIterator{} req = proto.Clone(req).(*osconfigpb.ListOSPolicyAssignmentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.OSPolicyAssignment, string, error) { @@ -433,11 +590,10 @@ func (c *OsConfigZonalClient) ListOSPolicyAssignments(ctx context.Context, req * return it } -// ListOSPolicyAssignmentRevisions list the OS policy assignment revisions for a given OS policy assignment. -func (c *OsConfigZonalClient) ListOSPolicyAssignmentRevisions(ctx context.Context, req *osconfigpb.ListOSPolicyAssignmentRevisionsRequest, opts ...gax.CallOption) *OSPolicyAssignmentIterator { +func (c *osConfigZonalGRPCClient) ListOSPolicyAssignmentRevisions(ctx context.Context, req *osconfigpb.ListOSPolicyAssignmentRevisionsRequest, opts ...gax.CallOption) *OSPolicyAssignmentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListOSPolicyAssignmentRevisions[0:len(c.CallOptions.ListOSPolicyAssignmentRevisions):len(c.CallOptions.ListOSPolicyAssignmentRevisions)], opts...) + opts = append((*c.CallOptions).ListOSPolicyAssignmentRevisions[0:len((*c.CallOptions).ListOSPolicyAssignmentRevisions):len((*c.CallOptions).ListOSPolicyAssignmentRevisions)], opts...) it := &OSPolicyAssignmentIterator{} req = proto.Clone(req).(*osconfigpb.ListOSPolicyAssignmentRevisionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.OSPolicyAssignment, string, error) { @@ -474,19 +630,7 @@ func (c *OsConfigZonalClient) ListOSPolicyAssignmentRevisions(ctx context.Contex return it } -// DeleteOSPolicyAssignment delete the OS policy assignment. -// -// This method creates a new revision of the OS policy assignment. -// -// This method returns a long running operation (LRO) that contains the -// rollout details. The rollout can be cancelled by cancelling the LRO. -// -// If the LRO completes and is not cancelled, all revisions associated with -// the OS policy assignment are deleted. -// -// For more information, see Method: -// projects.locations.osPolicyAssignments.operations.cancel (at https://cloud.google.com/compute/docs/osconfig/rest/v1alpha/projects.locations.osPolicyAssignments.operations/cancel). -func (c *OsConfigZonalClient) DeleteOSPolicyAssignment(ctx context.Context, req *osconfigpb.DeleteOSPolicyAssignmentRequest, opts ...gax.CallOption) (*DeleteOSPolicyAssignmentOperation, error) { +func (c *osConfigZonalGRPCClient) DeleteOSPolicyAssignment(ctx context.Context, req *osconfigpb.DeleteOSPolicyAssignmentRequest, opts ...gax.CallOption) (*DeleteOSPolicyAssignmentOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -494,7 +638,7 @@ func (c *OsConfigZonalClient) DeleteOSPolicyAssignment(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteOSPolicyAssignment[0:len(c.CallOptions.DeleteOSPolicyAssignment):len(c.CallOptions.DeleteOSPolicyAssignment)], opts...) + opts = append((*c.CallOptions).DeleteOSPolicyAssignment[0:len((*c.CallOptions).DeleteOSPolicyAssignment):len((*c.CallOptions).DeleteOSPolicyAssignment)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -505,13 +649,11 @@ func (c *OsConfigZonalClient) DeleteOSPolicyAssignment(ctx context.Context, req return nil, err } return &DeleteOSPolicyAssignmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetInstanceOSPoliciesCompliance get OS policies compliance data for the specified Compute Engine VM -// instance. -func (c *OsConfigZonalClient) GetInstanceOSPoliciesCompliance(ctx context.Context, req *osconfigpb.GetInstanceOSPoliciesComplianceRequest, opts ...gax.CallOption) (*osconfigpb.InstanceOSPoliciesCompliance, error) { +func (c *osConfigZonalGRPCClient) GetInstanceOSPoliciesCompliance(ctx context.Context, req *osconfigpb.GetInstanceOSPoliciesComplianceRequest, opts ...gax.CallOption) (*osconfigpb.InstanceOSPoliciesCompliance, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -519,7 +661,7 @@ func (c *OsConfigZonalClient) GetInstanceOSPoliciesCompliance(ctx context.Contex } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetInstanceOSPoliciesCompliance[0:len(c.CallOptions.GetInstanceOSPoliciesCompliance):len(c.CallOptions.GetInstanceOSPoliciesCompliance)], opts...) + opts = append((*c.CallOptions).GetInstanceOSPoliciesCompliance[0:len((*c.CallOptions).GetInstanceOSPoliciesCompliance):len((*c.CallOptions).GetInstanceOSPoliciesCompliance)], opts...) var resp *osconfigpb.InstanceOSPoliciesCompliance err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -532,12 +674,10 @@ func (c *OsConfigZonalClient) GetInstanceOSPoliciesCompliance(ctx context.Contex return resp, nil } -// ListInstanceOSPoliciesCompliances list OS policies compliance data for all Compute Engine VM instances in the -// specified zone. -func (c *OsConfigZonalClient) ListInstanceOSPoliciesCompliances(ctx context.Context, req *osconfigpb.ListInstanceOSPoliciesCompliancesRequest, opts ...gax.CallOption) *InstanceOSPoliciesComplianceIterator { +func (c *osConfigZonalGRPCClient) ListInstanceOSPoliciesCompliances(ctx context.Context, req *osconfigpb.ListInstanceOSPoliciesCompliancesRequest, opts ...gax.CallOption) *InstanceOSPoliciesComplianceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListInstanceOSPoliciesCompliances[0:len(c.CallOptions.ListInstanceOSPoliciesCompliances):len(c.CallOptions.ListInstanceOSPoliciesCompliances)], opts...) + opts = append((*c.CallOptions).ListInstanceOSPoliciesCompliances[0:len((*c.CallOptions).ListInstanceOSPoliciesCompliances):len((*c.CallOptions).ListInstanceOSPoliciesCompliances)], opts...) it := &InstanceOSPoliciesComplianceIterator{} req = proto.Clone(req).(*osconfigpb.ListInstanceOSPoliciesCompliancesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.InstanceOSPoliciesCompliance, string, error) { @@ -574,9 +714,7 @@ func (c *OsConfigZonalClient) ListInstanceOSPoliciesCompliances(ctx context.Cont return it } -// GetInventory get inventory data for the specified VM instance. If the VM has no -// associated inventory, the message NOT_FOUND is returned. -func (c *OsConfigZonalClient) GetInventory(ctx context.Context, req *osconfigpb.GetInventoryRequest, opts ...gax.CallOption) (*osconfigpb.Inventory, error) { +func (c *osConfigZonalGRPCClient) GetInventory(ctx context.Context, req *osconfigpb.GetInventoryRequest, opts ...gax.CallOption) (*osconfigpb.Inventory, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -584,7 +722,7 @@ func (c *OsConfigZonalClient) GetInventory(ctx context.Context, req *osconfigpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetInventory[0:len(c.CallOptions.GetInventory):len(c.CallOptions.GetInventory)], opts...) + opts = append((*c.CallOptions).GetInventory[0:len((*c.CallOptions).GetInventory):len((*c.CallOptions).GetInventory)], opts...) var resp *osconfigpb.Inventory err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -597,11 +735,10 @@ func (c *OsConfigZonalClient) GetInventory(ctx context.Context, req *osconfigpb. return resp, nil } -// ListInventories list inventory data for all VM instances in the specified zone. -func (c *OsConfigZonalClient) ListInventories(ctx context.Context, req *osconfigpb.ListInventoriesRequest, opts ...gax.CallOption) *InventoryIterator { +func (c *osConfigZonalGRPCClient) ListInventories(ctx context.Context, req *osconfigpb.ListInventoriesRequest, opts ...gax.CallOption) *InventoryIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListInventories[0:len(c.CallOptions.ListInventories):len(c.CallOptions.ListInventories)], opts...) + opts = append((*c.CallOptions).ListInventories[0:len((*c.CallOptions).ListInventories):len((*c.CallOptions).ListInventories)], opts...) it := &InventoryIterator{} req = proto.Clone(req).(*osconfigpb.ListInventoriesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.Inventory, string, error) { @@ -638,9 +775,7 @@ func (c *OsConfigZonalClient) ListInventories(ctx context.Context, req *osconfig return it } -// GetVulnerabilityReport gets the vulnerability report for the specified VM instance. Only VMs with -// inventory data have vulnerability reports associated with them. -func (c *OsConfigZonalClient) GetVulnerabilityReport(ctx context.Context, req *osconfigpb.GetVulnerabilityReportRequest, opts ...gax.CallOption) (*osconfigpb.VulnerabilityReport, error) { +func (c *osConfigZonalGRPCClient) GetVulnerabilityReport(ctx context.Context, req *osconfigpb.GetVulnerabilityReportRequest, opts ...gax.CallOption) (*osconfigpb.VulnerabilityReport, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -648,7 +783,7 @@ func (c *OsConfigZonalClient) GetVulnerabilityReport(ctx context.Context, req *o } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetVulnerabilityReport[0:len(c.CallOptions.GetVulnerabilityReport):len(c.CallOptions.GetVulnerabilityReport)], opts...) + opts = append((*c.CallOptions).GetVulnerabilityReport[0:len((*c.CallOptions).GetVulnerabilityReport):len((*c.CallOptions).GetVulnerabilityReport)], opts...) var resp *osconfigpb.VulnerabilityReport err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -661,11 +796,10 @@ func (c *OsConfigZonalClient) GetVulnerabilityReport(ctx context.Context, req *o return resp, nil } -// ListVulnerabilityReports list vulnerability reports for all VM instances in the specified zone. -func (c *OsConfigZonalClient) ListVulnerabilityReports(ctx context.Context, req *osconfigpb.ListVulnerabilityReportsRequest, opts ...gax.CallOption) *VulnerabilityReportIterator { +func (c *osConfigZonalGRPCClient) ListVulnerabilityReports(ctx context.Context, req *osconfigpb.ListVulnerabilityReportsRequest, opts ...gax.CallOption) *VulnerabilityReportIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListVulnerabilityReports[0:len(c.CallOptions.ListVulnerabilityReports):len(c.CallOptions.ListVulnerabilityReports)], opts...) + opts = append((*c.CallOptions).ListVulnerabilityReports[0:len((*c.CallOptions).ListVulnerabilityReports):len((*c.CallOptions).ListVulnerabilityReports)], opts...) it := &VulnerabilityReportIterator{} req = proto.Clone(req).(*osconfigpb.ListVulnerabilityReportsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.VulnerabilityReport, string, error) { @@ -709,9 +843,9 @@ type CreateOSPolicyAssignmentOperation struct { // CreateOSPolicyAssignmentOperation returns a new CreateOSPolicyAssignmentOperation from a given name. // The name must be that of a previously created CreateOSPolicyAssignmentOperation, possibly from a different process. -func (c *OsConfigZonalClient) CreateOSPolicyAssignmentOperation(name string) *CreateOSPolicyAssignmentOperation { +func (c *osConfigZonalGRPCClient) CreateOSPolicyAssignmentOperation(name string) *CreateOSPolicyAssignmentOperation { return &CreateOSPolicyAssignmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -778,9 +912,9 @@ type DeleteOSPolicyAssignmentOperation struct { // DeleteOSPolicyAssignmentOperation returns a new DeleteOSPolicyAssignmentOperation from a given name. // The name must be that of a previously created DeleteOSPolicyAssignmentOperation, possibly from a different process. -func (c *OsConfigZonalClient) DeleteOSPolicyAssignmentOperation(name string) *DeleteOSPolicyAssignmentOperation { +func (c *osConfigZonalGRPCClient) DeleteOSPolicyAssignmentOperation(name string) *DeleteOSPolicyAssignmentOperation { return &DeleteOSPolicyAssignmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -836,9 +970,9 @@ type UpdateOSPolicyAssignmentOperation struct { // UpdateOSPolicyAssignmentOperation returns a new UpdateOSPolicyAssignmentOperation from a given name. // The name must be that of a previously created UpdateOSPolicyAssignmentOperation, possibly from a different process. -func (c *OsConfigZonalClient) UpdateOSPolicyAssignmentOperation(name string) *UpdateOSPolicyAssignmentOperation { +func (c *osConfigZonalGRPCClient) UpdateOSPolicyAssignmentOperation(name string) *UpdateOSPolicyAssignmentOperation { return &UpdateOSPolicyAssignmentOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/osconfig/apiv1alpha/os_config_zonal_client_example_test.go b/osconfig/apiv1alpha/os_config_zonal_client_example_test.go index c3b09c166959..dd34d21177c5 100644 --- a/osconfig/apiv1alpha/os_config_zonal_client_example_test.go +++ b/osconfig/apiv1alpha/os_config_zonal_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewOsConfigZonalClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleOsConfigZonalClient_CreateOSPolicyAssignment() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" - ctx := context.Background() c, err := osconfig.NewOsConfigZonalClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.CreateOSPolicyAssignmentRequest{ // TODO: Fill request struct fields. @@ -60,13 +61,12 @@ func ExampleOsConfigZonalClient_CreateOSPolicyAssignment() { } func ExampleOsConfigZonalClient_UpdateOSPolicyAssignment() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" - ctx := context.Background() c, err := osconfig.NewOsConfigZonalClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.UpdateOSPolicyAssignmentRequest{ // TODO: Fill request struct fields. @@ -85,13 +85,12 @@ func ExampleOsConfigZonalClient_UpdateOSPolicyAssignment() { } func ExampleOsConfigZonalClient_GetOSPolicyAssignment() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" - ctx := context.Background() c, err := osconfig.NewOsConfigZonalClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.GetOSPolicyAssignmentRequest{ // TODO: Fill request struct fields. @@ -105,14 +104,12 @@ func ExampleOsConfigZonalClient_GetOSPolicyAssignment() { } func ExampleOsConfigZonalClient_ListOSPolicyAssignments() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewOsConfigZonalClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListOSPolicyAssignmentsRequest{ // TODO: Fill request struct fields. @@ -132,14 +129,12 @@ func ExampleOsConfigZonalClient_ListOSPolicyAssignments() { } func ExampleOsConfigZonalClient_ListOSPolicyAssignmentRevisions() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewOsConfigZonalClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListOSPolicyAssignmentRevisionsRequest{ // TODO: Fill request struct fields. @@ -159,13 +154,12 @@ func ExampleOsConfigZonalClient_ListOSPolicyAssignmentRevisions() { } func ExampleOsConfigZonalClient_DeleteOSPolicyAssignment() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" - ctx := context.Background() c, err := osconfig.NewOsConfigZonalClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.DeleteOSPolicyAssignmentRequest{ // TODO: Fill request struct fields. @@ -182,13 +176,12 @@ func ExampleOsConfigZonalClient_DeleteOSPolicyAssignment() { } func ExampleOsConfigZonalClient_GetInstanceOSPoliciesCompliance() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" - ctx := context.Background() c, err := osconfig.NewOsConfigZonalClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.GetInstanceOSPoliciesComplianceRequest{ // TODO: Fill request struct fields. @@ -202,14 +195,12 @@ func ExampleOsConfigZonalClient_GetInstanceOSPoliciesCompliance() { } func ExampleOsConfigZonalClient_ListInstanceOSPoliciesCompliances() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewOsConfigZonalClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListInstanceOSPoliciesCompliancesRequest{ // TODO: Fill request struct fields. @@ -229,13 +220,12 @@ func ExampleOsConfigZonalClient_ListInstanceOSPoliciesCompliances() { } func ExampleOsConfigZonalClient_GetInventory() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" - ctx := context.Background() c, err := osconfig.NewOsConfigZonalClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.GetInventoryRequest{ // TODO: Fill request struct fields. @@ -249,14 +239,12 @@ func ExampleOsConfigZonalClient_GetInventory() { } func ExampleOsConfigZonalClient_ListInventories() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewOsConfigZonalClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListInventoriesRequest{ // TODO: Fill request struct fields. @@ -276,13 +264,12 @@ func ExampleOsConfigZonalClient_ListInventories() { } func ExampleOsConfigZonalClient_GetVulnerabilityReport() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" - ctx := context.Background() c, err := osconfig.NewOsConfigZonalClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.GetVulnerabilityReportRequest{ // TODO: Fill request struct fields. @@ -296,14 +283,12 @@ func ExampleOsConfigZonalClient_GetVulnerabilityReport() { } func ExampleOsConfigZonalClient_ListVulnerabilityReports() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1alpha" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewOsConfigZonalClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListVulnerabilityReportsRequest{ // TODO: Fill request struct fields. diff --git a/osconfig/apiv1beta/doc.go b/osconfig/apiv1beta/doc.go index 0dfc9181be20..582cceb0d6d0 100644 --- a/osconfig/apiv1beta/doc.go +++ b/osconfig/apiv1beta/doc.go @@ -20,6 +20,8 @@ // OS management tools that can be used for patch management, patch // compliance, and configuration management on VM instances. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package osconfig // import "cloud.google.com/go/osconfig/apiv1beta" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/osconfig/apiv1beta/os_config_client.go b/osconfig/apiv1beta/os_config_client.go index ba80b9806a0a..b2d9c981973a 100644 --- a/osconfig/apiv1beta/os_config_client.go +++ b/osconfig/apiv1beta/os_config_client.go @@ -56,7 +56,7 @@ type CallOptions struct { LookupEffectiveGuestPolicy []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("osconfig.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("osconfig.mtls.googleapis.com:443"), @@ -238,35 +238,172 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud OS Config API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ExecutePatchJob(context.Context, *osconfigpb.ExecutePatchJobRequest, ...gax.CallOption) (*osconfigpb.PatchJob, error) + GetPatchJob(context.Context, *osconfigpb.GetPatchJobRequest, ...gax.CallOption) (*osconfigpb.PatchJob, error) + CancelPatchJob(context.Context, *osconfigpb.CancelPatchJobRequest, ...gax.CallOption) (*osconfigpb.PatchJob, error) + ListPatchJobs(context.Context, *osconfigpb.ListPatchJobsRequest, ...gax.CallOption) *PatchJobIterator + ListPatchJobInstanceDetails(context.Context, *osconfigpb.ListPatchJobInstanceDetailsRequest, ...gax.CallOption) *PatchJobInstanceDetailsIterator + CreatePatchDeployment(context.Context, *osconfigpb.CreatePatchDeploymentRequest, ...gax.CallOption) (*osconfigpb.PatchDeployment, error) + GetPatchDeployment(context.Context, *osconfigpb.GetPatchDeploymentRequest, ...gax.CallOption) (*osconfigpb.PatchDeployment, error) + ListPatchDeployments(context.Context, *osconfigpb.ListPatchDeploymentsRequest, ...gax.CallOption) *PatchDeploymentIterator + DeletePatchDeployment(context.Context, *osconfigpb.DeletePatchDeploymentRequest, ...gax.CallOption) error + CreateGuestPolicy(context.Context, *osconfigpb.CreateGuestPolicyRequest, ...gax.CallOption) (*osconfigpb.GuestPolicy, error) + GetGuestPolicy(context.Context, *osconfigpb.GetGuestPolicyRequest, ...gax.CallOption) (*osconfigpb.GuestPolicy, error) + ListGuestPolicies(context.Context, *osconfigpb.ListGuestPoliciesRequest, ...gax.CallOption) *GuestPolicyIterator + UpdateGuestPolicy(context.Context, *osconfigpb.UpdateGuestPolicyRequest, ...gax.CallOption) (*osconfigpb.GuestPolicy, error) + DeleteGuestPolicy(context.Context, *osconfigpb.DeleteGuestPolicyRequest, ...gax.CallOption) error + LookupEffectiveGuestPolicy(context.Context, *osconfigpb.LookupEffectiveGuestPolicyRequest, ...gax.CallOption) (*osconfigpb.EffectiveGuestPolicy, error) +} + // Client is a client for interacting with Cloud OS Config API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// OS Config API +// +// The OS Config service is a server-side component that you can use to +// manage package installations and patch jobs for virtual machine instances. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ExecutePatchJob patch VM instances by creating and running a patch job. +func (c *Client) ExecutePatchJob(ctx context.Context, req *osconfigpb.ExecutePatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { + return c.internalClient.ExecutePatchJob(ctx, req, opts...) +} + +// GetPatchJob get the patch job. This can be used to track the progress of an +// ongoing patch job or review the details of completed jobs. +func (c *Client) GetPatchJob(ctx context.Context, req *osconfigpb.GetPatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { + return c.internalClient.GetPatchJob(ctx, req, opts...) +} + +// CancelPatchJob cancel a patch job. The patch job must be active. Canceled patch jobs +// cannot be restarted. +func (c *Client) CancelPatchJob(ctx context.Context, req *osconfigpb.CancelPatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { + return c.internalClient.CancelPatchJob(ctx, req, opts...) +} + +// ListPatchJobs get a list of patch jobs. +func (c *Client) ListPatchJobs(ctx context.Context, req *osconfigpb.ListPatchJobsRequest, opts ...gax.CallOption) *PatchJobIterator { + return c.internalClient.ListPatchJobs(ctx, req, opts...) +} + +// ListPatchJobInstanceDetails get a list of instance details for a given patch job. +func (c *Client) ListPatchJobInstanceDetails(ctx context.Context, req *osconfigpb.ListPatchJobInstanceDetailsRequest, opts ...gax.CallOption) *PatchJobInstanceDetailsIterator { + return c.internalClient.ListPatchJobInstanceDetails(ctx, req, opts...) +} + +// CreatePatchDeployment create an OS Config patch deployment. +func (c *Client) CreatePatchDeployment(ctx context.Context, req *osconfigpb.CreatePatchDeploymentRequest, opts ...gax.CallOption) (*osconfigpb.PatchDeployment, error) { + return c.internalClient.CreatePatchDeployment(ctx, req, opts...) +} + +// GetPatchDeployment get an OS Config patch deployment. +func (c *Client) GetPatchDeployment(ctx context.Context, req *osconfigpb.GetPatchDeploymentRequest, opts ...gax.CallOption) (*osconfigpb.PatchDeployment, error) { + return c.internalClient.GetPatchDeployment(ctx, req, opts...) +} + +// ListPatchDeployments get a page of OS Config patch deployments. +func (c *Client) ListPatchDeployments(ctx context.Context, req *osconfigpb.ListPatchDeploymentsRequest, opts ...gax.CallOption) *PatchDeploymentIterator { + return c.internalClient.ListPatchDeployments(ctx, req, opts...) +} + +// DeletePatchDeployment delete an OS Config patch deployment. +func (c *Client) DeletePatchDeployment(ctx context.Context, req *osconfigpb.DeletePatchDeploymentRequest, opts ...gax.CallOption) error { + return c.internalClient.DeletePatchDeployment(ctx, req, opts...) +} + +// CreateGuestPolicy create an OS Config guest policy. +func (c *Client) CreateGuestPolicy(ctx context.Context, req *osconfigpb.CreateGuestPolicyRequest, opts ...gax.CallOption) (*osconfigpb.GuestPolicy, error) { + return c.internalClient.CreateGuestPolicy(ctx, req, opts...) +} + +// GetGuestPolicy get an OS Config guest policy. +func (c *Client) GetGuestPolicy(ctx context.Context, req *osconfigpb.GetGuestPolicyRequest, opts ...gax.CallOption) (*osconfigpb.GuestPolicy, error) { + return c.internalClient.GetGuestPolicy(ctx, req, opts...) +} + +// ListGuestPolicies get a page of OS Config guest policies. +func (c *Client) ListGuestPolicies(ctx context.Context, req *osconfigpb.ListGuestPoliciesRequest, opts ...gax.CallOption) *GuestPolicyIterator { + return c.internalClient.ListGuestPolicies(ctx, req, opts...) +} + +// UpdateGuestPolicy update an OS Config guest policy. +func (c *Client) UpdateGuestPolicy(ctx context.Context, req *osconfigpb.UpdateGuestPolicyRequest, opts ...gax.CallOption) (*osconfigpb.GuestPolicy, error) { + return c.internalClient.UpdateGuestPolicy(ctx, req, opts...) +} + +// DeleteGuestPolicy delete an OS Config guest policy. +func (c *Client) DeleteGuestPolicy(ctx context.Context, req *osconfigpb.DeleteGuestPolicyRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteGuestPolicy(ctx, req, opts...) +} + +// LookupEffectiveGuestPolicy lookup the effective guest policy that applies to a VM instance. This +// lookup merges all policies that are assigned to the instance ancestry. +func (c *Client) LookupEffectiveGuestPolicy(ctx context.Context, req *osconfigpb.LookupEffectiveGuestPolicyRequest, opts ...gax.CallOption) (*osconfigpb.EffectiveGuestPolicy, error) { + return c.internalClient.LookupEffectiveGuestPolicy(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud OS Config API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client osconfigpb.OsConfigServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new os config service client. +// NewClient creates a new os config service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // OS Config API // // The OS Config service is a server-side component that you can use to // manage package installations and patch jobs for virtual machine instances. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -284,42 +421,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: osconfigpb.NewOsConfigServiceClient(connPool), + client: osconfigpb.NewOsConfigServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ExecutePatchJob patch VM instances by creating and running a patch job. -func (c *Client) ExecutePatchJob(ctx context.Context, req *osconfigpb.ExecutePatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ExecutePatchJob(ctx context.Context, req *osconfigpb.ExecutePatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -327,7 +466,7 @@ func (c *Client) ExecutePatchJob(ctx context.Context, req *osconfigpb.ExecutePat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExecutePatchJob[0:len(c.CallOptions.ExecutePatchJob):len(c.CallOptions.ExecutePatchJob)], opts...) + opts = append((*c.CallOptions).ExecutePatchJob[0:len((*c.CallOptions).ExecutePatchJob):len((*c.CallOptions).ExecutePatchJob)], opts...) var resp *osconfigpb.PatchJob err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -340,9 +479,7 @@ func (c *Client) ExecutePatchJob(ctx context.Context, req *osconfigpb.ExecutePat return resp, nil } -// GetPatchJob get the patch job. This can be used to track the progress of an -// ongoing patch job or review the details of completed jobs. -func (c *Client) GetPatchJob(ctx context.Context, req *osconfigpb.GetPatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { +func (c *gRPCClient) GetPatchJob(ctx context.Context, req *osconfigpb.GetPatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -350,7 +487,7 @@ func (c *Client) GetPatchJob(ctx context.Context, req *osconfigpb.GetPatchJobReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetPatchJob[0:len(c.CallOptions.GetPatchJob):len(c.CallOptions.GetPatchJob)], opts...) + opts = append((*c.CallOptions).GetPatchJob[0:len((*c.CallOptions).GetPatchJob):len((*c.CallOptions).GetPatchJob)], opts...) var resp *osconfigpb.PatchJob err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -363,9 +500,7 @@ func (c *Client) GetPatchJob(ctx context.Context, req *osconfigpb.GetPatchJobReq return resp, nil } -// CancelPatchJob cancel a patch job. The patch job must be active. Canceled patch jobs -// cannot be restarted. -func (c *Client) CancelPatchJob(ctx context.Context, req *osconfigpb.CancelPatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { +func (c *gRPCClient) CancelPatchJob(ctx context.Context, req *osconfigpb.CancelPatchJobRequest, opts ...gax.CallOption) (*osconfigpb.PatchJob, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -373,7 +508,7 @@ func (c *Client) CancelPatchJob(ctx context.Context, req *osconfigpb.CancelPatch } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CancelPatchJob[0:len(c.CallOptions.CancelPatchJob):len(c.CallOptions.CancelPatchJob)], opts...) + opts = append((*c.CallOptions).CancelPatchJob[0:len((*c.CallOptions).CancelPatchJob):len((*c.CallOptions).CancelPatchJob)], opts...) var resp *osconfigpb.PatchJob err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -386,11 +521,10 @@ func (c *Client) CancelPatchJob(ctx context.Context, req *osconfigpb.CancelPatch return resp, nil } -// ListPatchJobs get a list of patch jobs. -func (c *Client) ListPatchJobs(ctx context.Context, req *osconfigpb.ListPatchJobsRequest, opts ...gax.CallOption) *PatchJobIterator { +func (c *gRPCClient) ListPatchJobs(ctx context.Context, req *osconfigpb.ListPatchJobsRequest, opts ...gax.CallOption) *PatchJobIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListPatchJobs[0:len(c.CallOptions.ListPatchJobs):len(c.CallOptions.ListPatchJobs)], opts...) + opts = append((*c.CallOptions).ListPatchJobs[0:len((*c.CallOptions).ListPatchJobs):len((*c.CallOptions).ListPatchJobs)], opts...) it := &PatchJobIterator{} req = proto.Clone(req).(*osconfigpb.ListPatchJobsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.PatchJob, string, error) { @@ -427,11 +561,10 @@ func (c *Client) ListPatchJobs(ctx context.Context, req *osconfigpb.ListPatchJob return it } -// ListPatchJobInstanceDetails get a list of instance details for a given patch job. -func (c *Client) ListPatchJobInstanceDetails(ctx context.Context, req *osconfigpb.ListPatchJobInstanceDetailsRequest, opts ...gax.CallOption) *PatchJobInstanceDetailsIterator { +func (c *gRPCClient) ListPatchJobInstanceDetails(ctx context.Context, req *osconfigpb.ListPatchJobInstanceDetailsRequest, opts ...gax.CallOption) *PatchJobInstanceDetailsIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListPatchJobInstanceDetails[0:len(c.CallOptions.ListPatchJobInstanceDetails):len(c.CallOptions.ListPatchJobInstanceDetails)], opts...) + opts = append((*c.CallOptions).ListPatchJobInstanceDetails[0:len((*c.CallOptions).ListPatchJobInstanceDetails):len((*c.CallOptions).ListPatchJobInstanceDetails)], opts...) it := &PatchJobInstanceDetailsIterator{} req = proto.Clone(req).(*osconfigpb.ListPatchJobInstanceDetailsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.PatchJobInstanceDetails, string, error) { @@ -468,8 +601,7 @@ func (c *Client) ListPatchJobInstanceDetails(ctx context.Context, req *osconfigp return it } -// CreatePatchDeployment create an OS Config patch deployment. -func (c *Client) CreatePatchDeployment(ctx context.Context, req *osconfigpb.CreatePatchDeploymentRequest, opts ...gax.CallOption) (*osconfigpb.PatchDeployment, error) { +func (c *gRPCClient) CreatePatchDeployment(ctx context.Context, req *osconfigpb.CreatePatchDeploymentRequest, opts ...gax.CallOption) (*osconfigpb.PatchDeployment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -477,7 +609,7 @@ func (c *Client) CreatePatchDeployment(ctx context.Context, req *osconfigpb.Crea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreatePatchDeployment[0:len(c.CallOptions.CreatePatchDeployment):len(c.CallOptions.CreatePatchDeployment)], opts...) + opts = append((*c.CallOptions).CreatePatchDeployment[0:len((*c.CallOptions).CreatePatchDeployment):len((*c.CallOptions).CreatePatchDeployment)], opts...) var resp *osconfigpb.PatchDeployment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -490,8 +622,7 @@ func (c *Client) CreatePatchDeployment(ctx context.Context, req *osconfigpb.Crea return resp, nil } -// GetPatchDeployment get an OS Config patch deployment. -func (c *Client) GetPatchDeployment(ctx context.Context, req *osconfigpb.GetPatchDeploymentRequest, opts ...gax.CallOption) (*osconfigpb.PatchDeployment, error) { +func (c *gRPCClient) GetPatchDeployment(ctx context.Context, req *osconfigpb.GetPatchDeploymentRequest, opts ...gax.CallOption) (*osconfigpb.PatchDeployment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -499,7 +630,7 @@ func (c *Client) GetPatchDeployment(ctx context.Context, req *osconfigpb.GetPatc } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetPatchDeployment[0:len(c.CallOptions.GetPatchDeployment):len(c.CallOptions.GetPatchDeployment)], opts...) + opts = append((*c.CallOptions).GetPatchDeployment[0:len((*c.CallOptions).GetPatchDeployment):len((*c.CallOptions).GetPatchDeployment)], opts...) var resp *osconfigpb.PatchDeployment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -512,11 +643,10 @@ func (c *Client) GetPatchDeployment(ctx context.Context, req *osconfigpb.GetPatc return resp, nil } -// ListPatchDeployments get a page of OS Config patch deployments. -func (c *Client) ListPatchDeployments(ctx context.Context, req *osconfigpb.ListPatchDeploymentsRequest, opts ...gax.CallOption) *PatchDeploymentIterator { +func (c *gRPCClient) ListPatchDeployments(ctx context.Context, req *osconfigpb.ListPatchDeploymentsRequest, opts ...gax.CallOption) *PatchDeploymentIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListPatchDeployments[0:len(c.CallOptions.ListPatchDeployments):len(c.CallOptions.ListPatchDeployments)], opts...) + opts = append((*c.CallOptions).ListPatchDeployments[0:len((*c.CallOptions).ListPatchDeployments):len((*c.CallOptions).ListPatchDeployments)], opts...) it := &PatchDeploymentIterator{} req = proto.Clone(req).(*osconfigpb.ListPatchDeploymentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.PatchDeployment, string, error) { @@ -553,8 +683,7 @@ func (c *Client) ListPatchDeployments(ctx context.Context, req *osconfigpb.ListP return it } -// DeletePatchDeployment delete an OS Config patch deployment. -func (c *Client) DeletePatchDeployment(ctx context.Context, req *osconfigpb.DeletePatchDeploymentRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeletePatchDeployment(ctx context.Context, req *osconfigpb.DeletePatchDeploymentRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -562,7 +691,7 @@ func (c *Client) DeletePatchDeployment(ctx context.Context, req *osconfigpb.Dele } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeletePatchDeployment[0:len(c.CallOptions.DeletePatchDeployment):len(c.CallOptions.DeletePatchDeployment)], opts...) + opts = append((*c.CallOptions).DeletePatchDeployment[0:len((*c.CallOptions).DeletePatchDeployment):len((*c.CallOptions).DeletePatchDeployment)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeletePatchDeployment(ctx, req, settings.GRPC...) @@ -571,8 +700,7 @@ func (c *Client) DeletePatchDeployment(ctx context.Context, req *osconfigpb.Dele return err } -// CreateGuestPolicy create an OS Config guest policy. -func (c *Client) CreateGuestPolicy(ctx context.Context, req *osconfigpb.CreateGuestPolicyRequest, opts ...gax.CallOption) (*osconfigpb.GuestPolicy, error) { +func (c *gRPCClient) CreateGuestPolicy(ctx context.Context, req *osconfigpb.CreateGuestPolicyRequest, opts ...gax.CallOption) (*osconfigpb.GuestPolicy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -580,7 +708,7 @@ func (c *Client) CreateGuestPolicy(ctx context.Context, req *osconfigpb.CreateGu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateGuestPolicy[0:len(c.CallOptions.CreateGuestPolicy):len(c.CallOptions.CreateGuestPolicy)], opts...) + opts = append((*c.CallOptions).CreateGuestPolicy[0:len((*c.CallOptions).CreateGuestPolicy):len((*c.CallOptions).CreateGuestPolicy)], opts...) var resp *osconfigpb.GuestPolicy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -593,8 +721,7 @@ func (c *Client) CreateGuestPolicy(ctx context.Context, req *osconfigpb.CreateGu return resp, nil } -// GetGuestPolicy get an OS Config guest policy. -func (c *Client) GetGuestPolicy(ctx context.Context, req *osconfigpb.GetGuestPolicyRequest, opts ...gax.CallOption) (*osconfigpb.GuestPolicy, error) { +func (c *gRPCClient) GetGuestPolicy(ctx context.Context, req *osconfigpb.GetGuestPolicyRequest, opts ...gax.CallOption) (*osconfigpb.GuestPolicy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -602,7 +729,7 @@ func (c *Client) GetGuestPolicy(ctx context.Context, req *osconfigpb.GetGuestPol } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetGuestPolicy[0:len(c.CallOptions.GetGuestPolicy):len(c.CallOptions.GetGuestPolicy)], opts...) + opts = append((*c.CallOptions).GetGuestPolicy[0:len((*c.CallOptions).GetGuestPolicy):len((*c.CallOptions).GetGuestPolicy)], opts...) var resp *osconfigpb.GuestPolicy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -615,11 +742,10 @@ func (c *Client) GetGuestPolicy(ctx context.Context, req *osconfigpb.GetGuestPol return resp, nil } -// ListGuestPolicies get a page of OS Config guest policies. -func (c *Client) ListGuestPolicies(ctx context.Context, req *osconfigpb.ListGuestPoliciesRequest, opts ...gax.CallOption) *GuestPolicyIterator { +func (c *gRPCClient) ListGuestPolicies(ctx context.Context, req *osconfigpb.ListGuestPoliciesRequest, opts ...gax.CallOption) *GuestPolicyIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListGuestPolicies[0:len(c.CallOptions.ListGuestPolicies):len(c.CallOptions.ListGuestPolicies)], opts...) + opts = append((*c.CallOptions).ListGuestPolicies[0:len((*c.CallOptions).ListGuestPolicies):len((*c.CallOptions).ListGuestPolicies)], opts...) it := &GuestPolicyIterator{} req = proto.Clone(req).(*osconfigpb.ListGuestPoliciesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*osconfigpb.GuestPolicy, string, error) { @@ -656,8 +782,7 @@ func (c *Client) ListGuestPolicies(ctx context.Context, req *osconfigpb.ListGues return it } -// UpdateGuestPolicy update an OS Config guest policy. -func (c *Client) UpdateGuestPolicy(ctx context.Context, req *osconfigpb.UpdateGuestPolicyRequest, opts ...gax.CallOption) (*osconfigpb.GuestPolicy, error) { +func (c *gRPCClient) UpdateGuestPolicy(ctx context.Context, req *osconfigpb.UpdateGuestPolicyRequest, opts ...gax.CallOption) (*osconfigpb.GuestPolicy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -665,7 +790,7 @@ func (c *Client) UpdateGuestPolicy(ctx context.Context, req *osconfigpb.UpdateGu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "guest_policy.name", url.QueryEscape(req.GetGuestPolicy().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateGuestPolicy[0:len(c.CallOptions.UpdateGuestPolicy):len(c.CallOptions.UpdateGuestPolicy)], opts...) + opts = append((*c.CallOptions).UpdateGuestPolicy[0:len((*c.CallOptions).UpdateGuestPolicy):len((*c.CallOptions).UpdateGuestPolicy)], opts...) var resp *osconfigpb.GuestPolicy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -678,8 +803,7 @@ func (c *Client) UpdateGuestPolicy(ctx context.Context, req *osconfigpb.UpdateGu return resp, nil } -// DeleteGuestPolicy delete an OS Config guest policy. -func (c *Client) DeleteGuestPolicy(ctx context.Context, req *osconfigpb.DeleteGuestPolicyRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteGuestPolicy(ctx context.Context, req *osconfigpb.DeleteGuestPolicyRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -687,7 +811,7 @@ func (c *Client) DeleteGuestPolicy(ctx context.Context, req *osconfigpb.DeleteGu } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteGuestPolicy[0:len(c.CallOptions.DeleteGuestPolicy):len(c.CallOptions.DeleteGuestPolicy)], opts...) + opts = append((*c.CallOptions).DeleteGuestPolicy[0:len((*c.CallOptions).DeleteGuestPolicy):len((*c.CallOptions).DeleteGuestPolicy)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteGuestPolicy(ctx, req, settings.GRPC...) @@ -696,9 +820,7 @@ func (c *Client) DeleteGuestPolicy(ctx context.Context, req *osconfigpb.DeleteGu return err } -// LookupEffectiveGuestPolicy lookup the effective guest policy that applies to a VM instance. This -// lookup merges all policies that are assigned to the instance ancestry. -func (c *Client) LookupEffectiveGuestPolicy(ctx context.Context, req *osconfigpb.LookupEffectiveGuestPolicyRequest, opts ...gax.CallOption) (*osconfigpb.EffectiveGuestPolicy, error) { +func (c *gRPCClient) LookupEffectiveGuestPolicy(ctx context.Context, req *osconfigpb.LookupEffectiveGuestPolicyRequest, opts ...gax.CallOption) (*osconfigpb.EffectiveGuestPolicy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -706,7 +828,7 @@ func (c *Client) LookupEffectiveGuestPolicy(ctx context.Context, req *osconfigpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance", url.QueryEscape(req.GetInstance()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.LookupEffectiveGuestPolicy[0:len(c.CallOptions.LookupEffectiveGuestPolicy):len(c.CallOptions.LookupEffectiveGuestPolicy)], opts...) + opts = append((*c.CallOptions).LookupEffectiveGuestPolicy[0:len((*c.CallOptions).LookupEffectiveGuestPolicy):len((*c.CallOptions).LookupEffectiveGuestPolicy)], opts...) var resp *osconfigpb.EffectiveGuestPolicy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/osconfig/apiv1beta/os_config_client_example_test.go b/osconfig/apiv1beta/os_config_client_example_test.go index 5af8d16e3f1b..a810c57efd42 100644 --- a/osconfig/apiv1beta/os_config_client_example_test.go +++ b/osconfig/apiv1beta/os_config_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ExecutePatchJob() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ExecutePatchJobRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleClient_ExecutePatchJob() { } func ExampleClient_GetPatchJob() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.GetPatchJobRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleClient_GetPatchJob() { } func ExampleClient_CancelPatchJob() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.CancelPatchJobRequest{ // TODO: Fill request struct fields. @@ -95,14 +94,12 @@ func ExampleClient_CancelPatchJob() { } func ExampleClient_ListPatchJobs() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListPatchJobsRequest{ // TODO: Fill request struct fields. @@ -122,14 +119,12 @@ func ExampleClient_ListPatchJobs() { } func ExampleClient_ListPatchJobInstanceDetails() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListPatchJobInstanceDetailsRequest{ // TODO: Fill request struct fields. @@ -149,13 +144,12 @@ func ExampleClient_ListPatchJobInstanceDetails() { } func ExampleClient_CreatePatchDeployment() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.CreatePatchDeploymentRequest{ // TODO: Fill request struct fields. @@ -169,13 +163,12 @@ func ExampleClient_CreatePatchDeployment() { } func ExampleClient_GetPatchDeployment() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.GetPatchDeploymentRequest{ // TODO: Fill request struct fields. @@ -189,14 +182,12 @@ func ExampleClient_GetPatchDeployment() { } func ExampleClient_ListPatchDeployments() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListPatchDeploymentsRequest{ // TODO: Fill request struct fields. @@ -221,6 +212,7 @@ func ExampleClient_DeletePatchDeployment() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.DeletePatchDeploymentRequest{ // TODO: Fill request struct fields. @@ -232,13 +224,12 @@ func ExampleClient_DeletePatchDeployment() { } func ExampleClient_CreateGuestPolicy() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.CreateGuestPolicyRequest{ // TODO: Fill request struct fields. @@ -252,13 +243,12 @@ func ExampleClient_CreateGuestPolicy() { } func ExampleClient_GetGuestPolicy() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.GetGuestPolicyRequest{ // TODO: Fill request struct fields. @@ -272,14 +262,12 @@ func ExampleClient_GetGuestPolicy() { } func ExampleClient_ListGuestPolicies() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.ListGuestPoliciesRequest{ // TODO: Fill request struct fields. @@ -299,13 +287,12 @@ func ExampleClient_ListGuestPolicies() { } func ExampleClient_UpdateGuestPolicy() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.UpdateGuestPolicyRequest{ // TODO: Fill request struct fields. @@ -324,6 +311,7 @@ func ExampleClient_DeleteGuestPolicy() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.DeleteGuestPolicyRequest{ // TODO: Fill request struct fields. @@ -335,13 +323,12 @@ func ExampleClient_DeleteGuestPolicy() { } func ExampleClient_LookupEffectiveGuestPolicy() { - // import osconfigpb "google.golang.org/genproto/googleapis/cloud/osconfig/v1beta" - ctx := context.Background() c, err := osconfig.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osconfigpb.LookupEffectiveGuestPolicyRequest{ // TODO: Fill request struct fields. diff --git a/oslogin/apiv1/doc.go b/oslogin/apiv1/doc.go index c7ba6d5cb830..d6a3b71a9138 100644 --- a/oslogin/apiv1/doc.go +++ b/oslogin/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package oslogin // import "cloud.google.com/go/oslogin/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/oslogin/apiv1/os_login_client.go b/oslogin/apiv1/os_login_client.go index 632d665232c1..e80893db6075 100644 --- a/oslogin/apiv1/os_login_client.go +++ b/oslogin/apiv1/os_login_client.go @@ -46,7 +46,7 @@ type CallOptions struct { UpdateSshPublicKey []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("oslogin.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("oslogin.mtls.googleapis.com:443"), @@ -135,35 +135,119 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud OS Login API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + DeletePosixAccount(context.Context, *osloginpb.DeletePosixAccountRequest, ...gax.CallOption) error + DeleteSshPublicKey(context.Context, *osloginpb.DeleteSshPublicKeyRequest, ...gax.CallOption) error + GetLoginProfile(context.Context, *osloginpb.GetLoginProfileRequest, ...gax.CallOption) (*osloginpb.LoginProfile, error) + GetSshPublicKey(context.Context, *osloginpb.GetSshPublicKeyRequest, ...gax.CallOption) (*commonpb.SshPublicKey, error) + ImportSshPublicKey(context.Context, *osloginpb.ImportSshPublicKeyRequest, ...gax.CallOption) (*osloginpb.ImportSshPublicKeyResponse, error) + UpdateSshPublicKey(context.Context, *osloginpb.UpdateSshPublicKeyRequest, ...gax.CallOption) (*commonpb.SshPublicKey, error) +} + // Client is a client for interacting with Cloud OS Login API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Cloud OS Login API +// +// The Cloud OS Login API allows you to manage users and their associated SSH +// public keys for logging into virtual machines on Google Cloud Platform. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// DeletePosixAccount deletes a POSIX account. +func (c *Client) DeletePosixAccount(ctx context.Context, req *osloginpb.DeletePosixAccountRequest, opts ...gax.CallOption) error { + return c.internalClient.DeletePosixAccount(ctx, req, opts...) +} + +// DeleteSshPublicKey deletes an SSH public key. +func (c *Client) DeleteSshPublicKey(ctx context.Context, req *osloginpb.DeleteSshPublicKeyRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteSshPublicKey(ctx, req, opts...) +} + +// GetLoginProfile retrieves the profile information used for logging in to a virtual machine +// on Google Compute Engine. +func (c *Client) GetLoginProfile(ctx context.Context, req *osloginpb.GetLoginProfileRequest, opts ...gax.CallOption) (*osloginpb.LoginProfile, error) { + return c.internalClient.GetLoginProfile(ctx, req, opts...) +} + +// GetSshPublicKey retrieves an SSH public key. +func (c *Client) GetSshPublicKey(ctx context.Context, req *osloginpb.GetSshPublicKeyRequest, opts ...gax.CallOption) (*commonpb.SshPublicKey, error) { + return c.internalClient.GetSshPublicKey(ctx, req, opts...) +} + +// ImportSshPublicKey adds an SSH public key and returns the profile information. Default POSIX +// account information is set when no username and UID exist as part of the +// login profile. +func (c *Client) ImportSshPublicKey(ctx context.Context, req *osloginpb.ImportSshPublicKeyRequest, opts ...gax.CallOption) (*osloginpb.ImportSshPublicKeyResponse, error) { + return c.internalClient.ImportSshPublicKey(ctx, req, opts...) +} + +// UpdateSshPublicKey updates an SSH public key and returns the profile information. This method +// supports patch semantics. +func (c *Client) UpdateSshPublicKey(ctx context.Context, req *osloginpb.UpdateSshPublicKeyRequest, opts ...gax.CallOption) (*commonpb.SshPublicKey, error) { + return c.internalClient.UpdateSshPublicKey(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud OS Login API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client osloginpb.OsLoginServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new os login service client. +// NewClient creates a new os login service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Cloud OS Login API // // The Cloud OS Login API allows you to manage users and their associated SSH // public keys for logging into virtual machines on Google Cloud Platform. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -181,42 +265,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: osloginpb.NewOsLoginServiceClient(connPool), + client: osloginpb.NewOsLoginServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// DeletePosixAccount deletes a POSIX account. -func (c *Client) DeletePosixAccount(ctx context.Context, req *osloginpb.DeletePosixAccountRequest, opts ...gax.CallOption) error { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) DeletePosixAccount(ctx context.Context, req *osloginpb.DeletePosixAccountRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -224,7 +310,7 @@ func (c *Client) DeletePosixAccount(ctx context.Context, req *osloginpb.DeletePo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeletePosixAccount[0:len(c.CallOptions.DeletePosixAccount):len(c.CallOptions.DeletePosixAccount)], opts...) + opts = append((*c.CallOptions).DeletePosixAccount[0:len((*c.CallOptions).DeletePosixAccount):len((*c.CallOptions).DeletePosixAccount)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeletePosixAccount(ctx, req, settings.GRPC...) @@ -233,8 +319,7 @@ func (c *Client) DeletePosixAccount(ctx context.Context, req *osloginpb.DeletePo return err } -// DeleteSshPublicKey deletes an SSH public key. -func (c *Client) DeleteSshPublicKey(ctx context.Context, req *osloginpb.DeleteSshPublicKeyRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteSshPublicKey(ctx context.Context, req *osloginpb.DeleteSshPublicKeyRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -242,7 +327,7 @@ func (c *Client) DeleteSshPublicKey(ctx context.Context, req *osloginpb.DeleteSs } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteSshPublicKey[0:len(c.CallOptions.DeleteSshPublicKey):len(c.CallOptions.DeleteSshPublicKey)], opts...) + opts = append((*c.CallOptions).DeleteSshPublicKey[0:len((*c.CallOptions).DeleteSshPublicKey):len((*c.CallOptions).DeleteSshPublicKey)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteSshPublicKey(ctx, req, settings.GRPC...) @@ -251,9 +336,7 @@ func (c *Client) DeleteSshPublicKey(ctx context.Context, req *osloginpb.DeleteSs return err } -// GetLoginProfile retrieves the profile information used for logging in to a virtual machine -// on Google Compute Engine. -func (c *Client) GetLoginProfile(ctx context.Context, req *osloginpb.GetLoginProfileRequest, opts ...gax.CallOption) (*osloginpb.LoginProfile, error) { +func (c *gRPCClient) GetLoginProfile(ctx context.Context, req *osloginpb.GetLoginProfileRequest, opts ...gax.CallOption) (*osloginpb.LoginProfile, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -261,7 +344,7 @@ func (c *Client) GetLoginProfile(ctx context.Context, req *osloginpb.GetLoginPro } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetLoginProfile[0:len(c.CallOptions.GetLoginProfile):len(c.CallOptions.GetLoginProfile)], opts...) + opts = append((*c.CallOptions).GetLoginProfile[0:len((*c.CallOptions).GetLoginProfile):len((*c.CallOptions).GetLoginProfile)], opts...) var resp *osloginpb.LoginProfile err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -274,8 +357,7 @@ func (c *Client) GetLoginProfile(ctx context.Context, req *osloginpb.GetLoginPro return resp, nil } -// GetSshPublicKey retrieves an SSH public key. -func (c *Client) GetSshPublicKey(ctx context.Context, req *osloginpb.GetSshPublicKeyRequest, opts ...gax.CallOption) (*commonpb.SshPublicKey, error) { +func (c *gRPCClient) GetSshPublicKey(ctx context.Context, req *osloginpb.GetSshPublicKeyRequest, opts ...gax.CallOption) (*commonpb.SshPublicKey, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -283,7 +365,7 @@ func (c *Client) GetSshPublicKey(ctx context.Context, req *osloginpb.GetSshPubli } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSshPublicKey[0:len(c.CallOptions.GetSshPublicKey):len(c.CallOptions.GetSshPublicKey)], opts...) + opts = append((*c.CallOptions).GetSshPublicKey[0:len((*c.CallOptions).GetSshPublicKey):len((*c.CallOptions).GetSshPublicKey)], opts...) var resp *commonpb.SshPublicKey err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -296,10 +378,7 @@ func (c *Client) GetSshPublicKey(ctx context.Context, req *osloginpb.GetSshPubli return resp, nil } -// ImportSshPublicKey adds an SSH public key and returns the profile information. Default POSIX -// account information is set when no username and UID exist as part of the -// login profile. -func (c *Client) ImportSshPublicKey(ctx context.Context, req *osloginpb.ImportSshPublicKeyRequest, opts ...gax.CallOption) (*osloginpb.ImportSshPublicKeyResponse, error) { +func (c *gRPCClient) ImportSshPublicKey(ctx context.Context, req *osloginpb.ImportSshPublicKeyRequest, opts ...gax.CallOption) (*osloginpb.ImportSshPublicKeyResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -307,7 +386,7 @@ func (c *Client) ImportSshPublicKey(ctx context.Context, req *osloginpb.ImportSs } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportSshPublicKey[0:len(c.CallOptions.ImportSshPublicKey):len(c.CallOptions.ImportSshPublicKey)], opts...) + opts = append((*c.CallOptions).ImportSshPublicKey[0:len((*c.CallOptions).ImportSshPublicKey):len((*c.CallOptions).ImportSshPublicKey)], opts...) var resp *osloginpb.ImportSshPublicKeyResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -320,9 +399,7 @@ func (c *Client) ImportSshPublicKey(ctx context.Context, req *osloginpb.ImportSs return resp, nil } -// UpdateSshPublicKey updates an SSH public key and returns the profile information. This method -// supports patch semantics. -func (c *Client) UpdateSshPublicKey(ctx context.Context, req *osloginpb.UpdateSshPublicKeyRequest, opts ...gax.CallOption) (*commonpb.SshPublicKey, error) { +func (c *gRPCClient) UpdateSshPublicKey(ctx context.Context, req *osloginpb.UpdateSshPublicKeyRequest, opts ...gax.CallOption) (*commonpb.SshPublicKey, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -330,7 +407,7 @@ func (c *Client) UpdateSshPublicKey(ctx context.Context, req *osloginpb.UpdateSs } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSshPublicKey[0:len(c.CallOptions.UpdateSshPublicKey):len(c.CallOptions.UpdateSshPublicKey)], opts...) + opts = append((*c.CallOptions).UpdateSshPublicKey[0:len((*c.CallOptions).UpdateSshPublicKey):len((*c.CallOptions).UpdateSshPublicKey)], opts...) var resp *commonpb.SshPublicKey err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/oslogin/apiv1/os_login_client_example_test.go b/oslogin/apiv1/os_login_client_example_test.go index 6c534a1dbacc..ceccbe9d7a3d 100644 --- a/oslogin/apiv1/os_login_client_example_test.go +++ b/oslogin/apiv1/os_login_client_example_test.go @@ -29,6 +29,8 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } @@ -39,6 +41,7 @@ func ExampleClient_DeletePosixAccount() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.DeletePosixAccountRequest{ // TODO: Fill request struct fields. @@ -55,6 +58,7 @@ func ExampleClient_DeleteSshPublicKey() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.DeleteSshPublicKeyRequest{ // TODO: Fill request struct fields. @@ -66,13 +70,12 @@ func ExampleClient_DeleteSshPublicKey() { } func ExampleClient_GetLoginProfile() { - // import osloginpb "google.golang.org/genproto/googleapis/cloud/oslogin/v1" - ctx := context.Background() c, err := oslogin.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.GetLoginProfileRequest{ // TODO: Fill request struct fields. @@ -86,13 +89,12 @@ func ExampleClient_GetLoginProfile() { } func ExampleClient_GetSshPublicKey() { - // import osloginpb "google.golang.org/genproto/googleapis/cloud/oslogin/v1" - ctx := context.Background() c, err := oslogin.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.GetSshPublicKeyRequest{ // TODO: Fill request struct fields. @@ -106,13 +108,12 @@ func ExampleClient_GetSshPublicKey() { } func ExampleClient_ImportSshPublicKey() { - // import osloginpb "google.golang.org/genproto/googleapis/cloud/oslogin/v1" - ctx := context.Background() c, err := oslogin.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.ImportSshPublicKeyRequest{ // TODO: Fill request struct fields. @@ -126,13 +127,12 @@ func ExampleClient_ImportSshPublicKey() { } func ExampleClient_UpdateSshPublicKey() { - // import osloginpb "google.golang.org/genproto/googleapis/cloud/oslogin/v1" - ctx := context.Background() c, err := oslogin.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.UpdateSshPublicKeyRequest{ // TODO: Fill request struct fields. diff --git a/oslogin/apiv1beta/doc.go b/oslogin/apiv1beta/doc.go index d46f3d20d779..db4803fc3720 100644 --- a/oslogin/apiv1beta/doc.go +++ b/oslogin/apiv1beta/doc.go @@ -20,6 +20,8 @@ // You can use OS Login to manage access to your VM instances using IAM // roles. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package oslogin // import "cloud.google.com/go/oslogin/apiv1beta" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/oslogin/apiv1beta/os_login_client.go b/oslogin/apiv1beta/os_login_client.go index 4842240b1d5c..d160b6804083 100644 --- a/oslogin/apiv1beta/os_login_client.go +++ b/oslogin/apiv1beta/os_login_client.go @@ -46,7 +46,7 @@ type CallOptions struct { UpdateSshPublicKey []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("oslogin.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("oslogin.mtls.googleapis.com:443"), @@ -135,35 +135,119 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud OS Login API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + DeletePosixAccount(context.Context, *osloginpb.DeletePosixAccountRequest, ...gax.CallOption) error + DeleteSshPublicKey(context.Context, *osloginpb.DeleteSshPublicKeyRequest, ...gax.CallOption) error + GetLoginProfile(context.Context, *osloginpb.GetLoginProfileRequest, ...gax.CallOption) (*osloginpb.LoginProfile, error) + GetSshPublicKey(context.Context, *osloginpb.GetSshPublicKeyRequest, ...gax.CallOption) (*commonpb.SshPublicKey, error) + ImportSshPublicKey(context.Context, *osloginpb.ImportSshPublicKeyRequest, ...gax.CallOption) (*osloginpb.ImportSshPublicKeyResponse, error) + UpdateSshPublicKey(context.Context, *osloginpb.UpdateSshPublicKeyRequest, ...gax.CallOption) (*commonpb.SshPublicKey, error) +} + // Client is a client for interacting with Cloud OS Login API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Cloud OS Login API +// +// The Cloud OS Login API allows you to manage users and their associated SSH +// public keys for logging into virtual machines on Google Cloud Platform. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// DeletePosixAccount deletes a POSIX account. +func (c *Client) DeletePosixAccount(ctx context.Context, req *osloginpb.DeletePosixAccountRequest, opts ...gax.CallOption) error { + return c.internalClient.DeletePosixAccount(ctx, req, opts...) +} + +// DeleteSshPublicKey deletes an SSH public key. +func (c *Client) DeleteSshPublicKey(ctx context.Context, req *osloginpb.DeleteSshPublicKeyRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteSshPublicKey(ctx, req, opts...) +} + +// GetLoginProfile retrieves the profile information used for logging in to a virtual machine +// on Google Compute Engine. +func (c *Client) GetLoginProfile(ctx context.Context, req *osloginpb.GetLoginProfileRequest, opts ...gax.CallOption) (*osloginpb.LoginProfile, error) { + return c.internalClient.GetLoginProfile(ctx, req, opts...) +} + +// GetSshPublicKey retrieves an SSH public key. +func (c *Client) GetSshPublicKey(ctx context.Context, req *osloginpb.GetSshPublicKeyRequest, opts ...gax.CallOption) (*commonpb.SshPublicKey, error) { + return c.internalClient.GetSshPublicKey(ctx, req, opts...) +} + +// ImportSshPublicKey adds an SSH public key and returns the profile information. Default POSIX +// account information is set when no username and UID exist as part of the +// login profile. +func (c *Client) ImportSshPublicKey(ctx context.Context, req *osloginpb.ImportSshPublicKeyRequest, opts ...gax.CallOption) (*osloginpb.ImportSshPublicKeyResponse, error) { + return c.internalClient.ImportSshPublicKey(ctx, req, opts...) +} + +// UpdateSshPublicKey updates an SSH public key and returns the profile information. This method +// supports patch semantics. +func (c *Client) UpdateSshPublicKey(ctx context.Context, req *osloginpb.UpdateSshPublicKeyRequest, opts ...gax.CallOption) (*commonpb.SshPublicKey, error) { + return c.internalClient.UpdateSshPublicKey(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud OS Login API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client osloginpb.OsLoginServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new os login service client. +// NewClient creates a new os login service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Cloud OS Login API // // The Cloud OS Login API allows you to manage users and their associated SSH // public keys for logging into virtual machines on Google Cloud Platform. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -181,42 +265,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: osloginpb.NewOsLoginServiceClient(connPool), + client: osloginpb.NewOsLoginServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// DeletePosixAccount deletes a POSIX account. -func (c *Client) DeletePosixAccount(ctx context.Context, req *osloginpb.DeletePosixAccountRequest, opts ...gax.CallOption) error { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) DeletePosixAccount(ctx context.Context, req *osloginpb.DeletePosixAccountRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -224,7 +310,7 @@ func (c *Client) DeletePosixAccount(ctx context.Context, req *osloginpb.DeletePo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeletePosixAccount[0:len(c.CallOptions.DeletePosixAccount):len(c.CallOptions.DeletePosixAccount)], opts...) + opts = append((*c.CallOptions).DeletePosixAccount[0:len((*c.CallOptions).DeletePosixAccount):len((*c.CallOptions).DeletePosixAccount)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeletePosixAccount(ctx, req, settings.GRPC...) @@ -233,8 +319,7 @@ func (c *Client) DeletePosixAccount(ctx context.Context, req *osloginpb.DeletePo return err } -// DeleteSshPublicKey deletes an SSH public key. -func (c *Client) DeleteSshPublicKey(ctx context.Context, req *osloginpb.DeleteSshPublicKeyRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteSshPublicKey(ctx context.Context, req *osloginpb.DeleteSshPublicKeyRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -242,7 +327,7 @@ func (c *Client) DeleteSshPublicKey(ctx context.Context, req *osloginpb.DeleteSs } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteSshPublicKey[0:len(c.CallOptions.DeleteSshPublicKey):len(c.CallOptions.DeleteSshPublicKey)], opts...) + opts = append((*c.CallOptions).DeleteSshPublicKey[0:len((*c.CallOptions).DeleteSshPublicKey):len((*c.CallOptions).DeleteSshPublicKey)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteSshPublicKey(ctx, req, settings.GRPC...) @@ -251,9 +336,7 @@ func (c *Client) DeleteSshPublicKey(ctx context.Context, req *osloginpb.DeleteSs return err } -// GetLoginProfile retrieves the profile information used for logging in to a virtual machine -// on Google Compute Engine. -func (c *Client) GetLoginProfile(ctx context.Context, req *osloginpb.GetLoginProfileRequest, opts ...gax.CallOption) (*osloginpb.LoginProfile, error) { +func (c *gRPCClient) GetLoginProfile(ctx context.Context, req *osloginpb.GetLoginProfileRequest, opts ...gax.CallOption) (*osloginpb.LoginProfile, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -261,7 +344,7 @@ func (c *Client) GetLoginProfile(ctx context.Context, req *osloginpb.GetLoginPro } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetLoginProfile[0:len(c.CallOptions.GetLoginProfile):len(c.CallOptions.GetLoginProfile)], opts...) + opts = append((*c.CallOptions).GetLoginProfile[0:len((*c.CallOptions).GetLoginProfile):len((*c.CallOptions).GetLoginProfile)], opts...) var resp *osloginpb.LoginProfile err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -274,8 +357,7 @@ func (c *Client) GetLoginProfile(ctx context.Context, req *osloginpb.GetLoginPro return resp, nil } -// GetSshPublicKey retrieves an SSH public key. -func (c *Client) GetSshPublicKey(ctx context.Context, req *osloginpb.GetSshPublicKeyRequest, opts ...gax.CallOption) (*commonpb.SshPublicKey, error) { +func (c *gRPCClient) GetSshPublicKey(ctx context.Context, req *osloginpb.GetSshPublicKeyRequest, opts ...gax.CallOption) (*commonpb.SshPublicKey, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -283,7 +365,7 @@ func (c *Client) GetSshPublicKey(ctx context.Context, req *osloginpb.GetSshPubli } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSshPublicKey[0:len(c.CallOptions.GetSshPublicKey):len(c.CallOptions.GetSshPublicKey)], opts...) + opts = append((*c.CallOptions).GetSshPublicKey[0:len((*c.CallOptions).GetSshPublicKey):len((*c.CallOptions).GetSshPublicKey)], opts...) var resp *commonpb.SshPublicKey err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -296,10 +378,7 @@ func (c *Client) GetSshPublicKey(ctx context.Context, req *osloginpb.GetSshPubli return resp, nil } -// ImportSshPublicKey adds an SSH public key and returns the profile information. Default POSIX -// account information is set when no username and UID exist as part of the -// login profile. -func (c *Client) ImportSshPublicKey(ctx context.Context, req *osloginpb.ImportSshPublicKeyRequest, opts ...gax.CallOption) (*osloginpb.ImportSshPublicKeyResponse, error) { +func (c *gRPCClient) ImportSshPublicKey(ctx context.Context, req *osloginpb.ImportSshPublicKeyRequest, opts ...gax.CallOption) (*osloginpb.ImportSshPublicKeyResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -307,7 +386,7 @@ func (c *Client) ImportSshPublicKey(ctx context.Context, req *osloginpb.ImportSs } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportSshPublicKey[0:len(c.CallOptions.ImportSshPublicKey):len(c.CallOptions.ImportSshPublicKey)], opts...) + opts = append((*c.CallOptions).ImportSshPublicKey[0:len((*c.CallOptions).ImportSshPublicKey):len((*c.CallOptions).ImportSshPublicKey)], opts...) var resp *osloginpb.ImportSshPublicKeyResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -320,9 +399,7 @@ func (c *Client) ImportSshPublicKey(ctx context.Context, req *osloginpb.ImportSs return resp, nil } -// UpdateSshPublicKey updates an SSH public key and returns the profile information. This method -// supports patch semantics. -func (c *Client) UpdateSshPublicKey(ctx context.Context, req *osloginpb.UpdateSshPublicKeyRequest, opts ...gax.CallOption) (*commonpb.SshPublicKey, error) { +func (c *gRPCClient) UpdateSshPublicKey(ctx context.Context, req *osloginpb.UpdateSshPublicKeyRequest, opts ...gax.CallOption) (*commonpb.SshPublicKey, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -330,7 +407,7 @@ func (c *Client) UpdateSshPublicKey(ctx context.Context, req *osloginpb.UpdateSs } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSshPublicKey[0:len(c.CallOptions.UpdateSshPublicKey):len(c.CallOptions.UpdateSshPublicKey)], opts...) + opts = append((*c.CallOptions).UpdateSshPublicKey[0:len((*c.CallOptions).UpdateSshPublicKey):len((*c.CallOptions).UpdateSshPublicKey)], opts...) var resp *commonpb.SshPublicKey err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/oslogin/apiv1beta/os_login_client_example_test.go b/oslogin/apiv1beta/os_login_client_example_test.go index e7c06470a871..8a9168efe2c9 100644 --- a/oslogin/apiv1beta/os_login_client_example_test.go +++ b/oslogin/apiv1beta/os_login_client_example_test.go @@ -29,6 +29,8 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } @@ -39,6 +41,7 @@ func ExampleClient_DeletePosixAccount() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.DeletePosixAccountRequest{ // TODO: Fill request struct fields. @@ -55,6 +58,7 @@ func ExampleClient_DeleteSshPublicKey() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.DeleteSshPublicKeyRequest{ // TODO: Fill request struct fields. @@ -66,13 +70,12 @@ func ExampleClient_DeleteSshPublicKey() { } func ExampleClient_GetLoginProfile() { - // import osloginpb "google.golang.org/genproto/googleapis/cloud/oslogin/v1beta" - ctx := context.Background() c, err := oslogin.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.GetLoginProfileRequest{ // TODO: Fill request struct fields. @@ -86,13 +89,12 @@ func ExampleClient_GetLoginProfile() { } func ExampleClient_GetSshPublicKey() { - // import osloginpb "google.golang.org/genproto/googleapis/cloud/oslogin/v1beta" - ctx := context.Background() c, err := oslogin.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.GetSshPublicKeyRequest{ // TODO: Fill request struct fields. @@ -106,13 +108,12 @@ func ExampleClient_GetSshPublicKey() { } func ExampleClient_ImportSshPublicKey() { - // import osloginpb "google.golang.org/genproto/googleapis/cloud/oslogin/v1beta" - ctx := context.Background() c, err := oslogin.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.ImportSshPublicKeyRequest{ // TODO: Fill request struct fields. @@ -126,13 +127,12 @@ func ExampleClient_ImportSshPublicKey() { } func ExampleClient_UpdateSshPublicKey() { - // import osloginpb "google.golang.org/genproto/googleapis/cloud/oslogin/v1beta" - ctx := context.Background() c, err := oslogin.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &osloginpb.UpdateSshPublicKeyRequest{ // TODO: Fill request struct fields. diff --git a/phishingprotection/apiv1beta1/doc.go b/phishingprotection/apiv1beta1/doc.go index e1ee2ff2d8fa..d00a36ab1630 100644 --- a/phishingprotection/apiv1beta1/doc.go +++ b/phishingprotection/apiv1beta1/doc.go @@ -17,6 +17,8 @@ // Package phishingprotection is an auto-generated package for the // Phishing Protection API. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -26,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package phishingprotection // import "cloud.google.com/go/phishingprotection/apiv1beta1" import ( @@ -46,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/phishingprotection/apiv1beta1/phishing_protection_service_v1_beta1_client.go b/phishingprotection/apiv1beta1/phishing_protection_service_v1_beta1_client.go index 879e5881adba..905f7f0468ec 100644 --- a/phishingprotection/apiv1beta1/phishing_protection_service_v1_beta1_client.go +++ b/phishingprotection/apiv1beta1/phishing_protection_service_v1_beta1_client.go @@ -39,7 +39,7 @@ type PhishingProtectionServiceV1Beta1CallOptions struct { ReportPhishing []gax.CallOption } -func defaultPhishingProtectionServiceV1Beta1ClientOptions() []option.ClientOption { +func defaultPhishingProtectionServiceV1Beta1GRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("phishingprotection.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("phishingprotection.mtls.googleapis.com:443"), @@ -57,32 +57,85 @@ func defaultPhishingProtectionServiceV1Beta1CallOptions() *PhishingProtectionSer } } +// internalPhishingProtectionServiceV1Beta1Client is an interface that defines the methods availaible from Phishing Protection API. +type internalPhishingProtectionServiceV1Beta1Client interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ReportPhishing(context.Context, *phishingprotectionpb.ReportPhishingRequest, ...gax.CallOption) (*phishingprotectionpb.ReportPhishingResponse, error) +} + // PhishingProtectionServiceV1Beta1Client is a client for interacting with Phishing Protection API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service to report phishing URIs. type PhishingProtectionServiceV1Beta1Client struct { + // The internal transport-dependent client. + internalClient internalPhishingProtectionServiceV1Beta1Client + + // The call options for this service. + CallOptions *PhishingProtectionServiceV1Beta1CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *PhishingProtectionServiceV1Beta1Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *PhishingProtectionServiceV1Beta1Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *PhishingProtectionServiceV1Beta1Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ReportPhishing reports a URI suspected of containing phishing content to be reviewed. Once +// the report review is complete, its result can be found in the Cloud +// Security Command Center findings dashboard for Phishing Protection. If the +// result verifies the existence of malicious phishing content, the site will +// be added the to Google’s Social Engineering +// lists (at https://support.google.com/webmasters/answer/6350487/) in order to +// protect users that could get exposed to this threat in the future. +func (c *PhishingProtectionServiceV1Beta1Client) ReportPhishing(ctx context.Context, req *phishingprotectionpb.ReportPhishingRequest, opts ...gax.CallOption) (*phishingprotectionpb.ReportPhishingResponse, error) { + return c.internalClient.ReportPhishing(ctx, req, opts...) +} + +// phishingProtectionServiceV1Beta1GRPCClient is a client for interacting with Phishing Protection API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type phishingProtectionServiceV1Beta1GRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing PhishingProtectionServiceV1Beta1Client + CallOptions **PhishingProtectionServiceV1Beta1CallOptions + // The gRPC API client. phishingProtectionServiceV1Beta1Client phishingprotectionpb.PhishingProtectionServiceV1Beta1Client - // The call options for this service. - CallOptions *PhishingProtectionServiceV1Beta1CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewPhishingProtectionServiceV1Beta1Client creates a new phishing protection service v1 beta1 client. +// NewPhishingProtectionServiceV1Beta1Client creates a new phishing protection service v1 beta1 client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service to report phishing URIs. func NewPhishingProtectionServiceV1Beta1Client(ctx context.Context, opts ...option.ClientOption) (*PhishingProtectionServiceV1Beta1Client, error) { - clientOpts := defaultPhishingProtectionServiceV1Beta1ClientOptions() - + clientOpts := defaultPhishingProtectionServiceV1Beta1GRPCClientOptions() if newPhishingProtectionServiceV1Beta1ClientHook != nil { hookOpts, err := newPhishingProtectionServiceV1Beta1ClientHook(ctx, clientHookParams{}) if err != nil { @@ -100,48 +153,44 @@ func NewPhishingProtectionServiceV1Beta1Client(ctx context.Context, opts ...opti if err != nil { return nil, err } - c := &PhishingProtectionServiceV1Beta1Client{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultPhishingProtectionServiceV1Beta1CallOptions(), + client := PhishingProtectionServiceV1Beta1Client{CallOptions: defaultPhishingProtectionServiceV1Beta1CallOptions()} + c := &phishingProtectionServiceV1Beta1GRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, phishingProtectionServiceV1Beta1Client: phishingprotectionpb.NewPhishingProtectionServiceV1Beta1Client(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *PhishingProtectionServiceV1Beta1Client) Connection() *grpc.ClientConn { +func (c *phishingProtectionServiceV1Beta1GRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *PhishingProtectionServiceV1Beta1Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *PhishingProtectionServiceV1Beta1Client) setGoogleClientInfo(keyval ...string) { +func (c *phishingProtectionServiceV1Beta1GRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ReportPhishing reports a URI suspected of containing phishing content to be reviewed. Once -// the report review is complete, its result can be found in the Cloud -// Security Command Center findings dashboard for Phishing Protection. If the -// result verifies the existence of malicious phishing content, the site will -// be added the to Google’s Social Engineering -// lists (at https://support.google.com/webmasters/answer/6350487/) in order to -// protect users that could get exposed to this threat in the future. -func (c *PhishingProtectionServiceV1Beta1Client) ReportPhishing(ctx context.Context, req *phishingprotectionpb.ReportPhishingRequest, opts ...gax.CallOption) (*phishingprotectionpb.ReportPhishingResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *phishingProtectionServiceV1Beta1GRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *phishingProtectionServiceV1Beta1GRPCClient) ReportPhishing(ctx context.Context, req *phishingprotectionpb.ReportPhishingRequest, opts ...gax.CallOption) (*phishingprotectionpb.ReportPhishingResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -149,7 +198,7 @@ func (c *PhishingProtectionServiceV1Beta1Client) ReportPhishing(ctx context.Cont } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ReportPhishing[0:len(c.CallOptions.ReportPhishing):len(c.CallOptions.ReportPhishing)], opts...) + opts = append((*c.CallOptions).ReportPhishing[0:len((*c.CallOptions).ReportPhishing):len((*c.CallOptions).ReportPhishing)], opts...) var resp *phishingprotectionpb.ReportPhishingResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/phishingprotection/apiv1beta1/phishing_protection_service_v1_beta1_client_example_test.go b/phishingprotection/apiv1beta1/phishing_protection_service_v1_beta1_client_example_test.go index 3a9a60dea78b..e7bedc6f36ee 100644 --- a/phishingprotection/apiv1beta1/phishing_protection_service_v1_beta1_client_example_test.go +++ b/phishingprotection/apiv1beta1/phishing_protection_service_v1_beta1_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewPhishingProtectionServiceV1Beta1Client() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExamplePhishingProtectionServiceV1Beta1Client_ReportPhishing() { - // import phishingprotectionpb "google.golang.org/genproto/googleapis/cloud/phishingprotection/v1beta1" - ctx := context.Background() c, err := phishingprotection.NewPhishingProtectionServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &phishingprotectionpb.ReportPhishingRequest{ // TODO: Fill request struct fields. diff --git a/policytroubleshooter/apiv1/doc.go b/policytroubleshooter/apiv1/doc.go index 13f0d30424e8..deceead17c48 100644 --- a/policytroubleshooter/apiv1/doc.go +++ b/policytroubleshooter/apiv1/doc.go @@ -26,7 +26,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package policytroubleshooter // import "cloud.google.com/go/policytroubleshooter/apiv1" import ( @@ -46,7 +46,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/policytroubleshooter/apiv1/iam_checker_client.go b/policytroubleshooter/apiv1/iam_checker_client.go index 520050434219..ce17882c28d3 100644 --- a/policytroubleshooter/apiv1/iam_checker_client.go +++ b/policytroubleshooter/apiv1/iam_checker_client.go @@ -37,7 +37,7 @@ type IamCheckerCallOptions struct { TroubleshootIamPolicy []gax.CallOption } -func defaultIamCheckerClientOptions() []option.ClientOption { +func defaultIamCheckerGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("policytroubleshooter.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("policytroubleshooter.mtls.googleapis.com:443"), @@ -55,34 +55,84 @@ func defaultIamCheckerCallOptions() *IamCheckerCallOptions { } } +// internalIamCheckerClient is an interface that defines the methods availaible from Policy Troubleshooter API. +type internalIamCheckerClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + TroubleshootIamPolicy(context.Context, *policytroubleshooterpb.TroubleshootIamPolicyRequest, ...gax.CallOption) (*policytroubleshooterpb.TroubleshootIamPolicyResponse, error) +} + // IamCheckerClient is a client for interacting with Policy Troubleshooter API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// IAM Policy Troubleshooter service. +// +// This service helps you troubleshoot access issues for Google Cloud resources. type IamCheckerClient struct { + // The internal transport-dependent client. + internalClient internalIamCheckerClient + + // The call options for this service. + CallOptions *IamCheckerCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *IamCheckerClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *IamCheckerClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *IamCheckerClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// TroubleshootIamPolicy checks whether a member has a specific permission for a specific resource, +// and explains why the member does or does not have that permission. +func (c *IamCheckerClient) TroubleshootIamPolicy(ctx context.Context, req *policytroubleshooterpb.TroubleshootIamPolicyRequest, opts ...gax.CallOption) (*policytroubleshooterpb.TroubleshootIamPolicyResponse, error) { + return c.internalClient.TroubleshootIamPolicy(ctx, req, opts...) +} + +// iamCheckerGRPCClient is a client for interacting with Policy Troubleshooter API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type iamCheckerGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing IamCheckerClient + CallOptions **IamCheckerCallOptions + // The gRPC API client. iamCheckerClient policytroubleshooterpb.IamCheckerClient - // The call options for this service. - CallOptions *IamCheckerCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewIamCheckerClient creates a new iam checker client. +// NewIamCheckerClient creates a new iam checker client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // IAM Policy Troubleshooter service. // // This service helps you troubleshoot access issues for Google Cloud resources. func NewIamCheckerClient(ctx context.Context, opts ...option.ClientOption) (*IamCheckerClient, error) { - clientOpts := defaultIamCheckerClientOptions() - + clientOpts := defaultIamCheckerGRPCClientOptions() if newIamCheckerClientHook != nil { hookOpts, err := newIamCheckerClientHook(ctx, clientHookParams{}) if err != nil { @@ -100,50 +150,51 @@ func NewIamCheckerClient(ctx context.Context, opts ...option.ClientOption) (*Iam if err != nil { return nil, err } - c := &IamCheckerClient{ + client := IamCheckerClient{CallOptions: defaultIamCheckerCallOptions()} + + c := &iamCheckerGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultIamCheckerCallOptions(), - iamCheckerClient: policytroubleshooterpb.NewIamCheckerClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *IamCheckerClient) Connection() *grpc.ClientConn { +func (c *iamCheckerGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *IamCheckerClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *IamCheckerClient) setGoogleClientInfo(keyval ...string) { +func (c *iamCheckerGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// TroubleshootIamPolicy checks whether a member has a specific permission for a specific resource, -// and explains why the member does or does not have that permission. -func (c *IamCheckerClient) TroubleshootIamPolicy(ctx context.Context, req *policytroubleshooterpb.TroubleshootIamPolicyRequest, opts ...gax.CallOption) (*policytroubleshooterpb.TroubleshootIamPolicyResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *iamCheckerGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *iamCheckerGRPCClient) TroubleshootIamPolicy(ctx context.Context, req *policytroubleshooterpb.TroubleshootIamPolicyRequest, opts ...gax.CallOption) (*policytroubleshooterpb.TroubleshootIamPolicyResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.TroubleshootIamPolicy[0:len(c.CallOptions.TroubleshootIamPolicy):len(c.CallOptions.TroubleshootIamPolicy)], opts...) + opts = append((*c.CallOptions).TroubleshootIamPolicy[0:len((*c.CallOptions).TroubleshootIamPolicy):len((*c.CallOptions).TroubleshootIamPolicy)], opts...) var resp *policytroubleshooterpb.TroubleshootIamPolicyResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/policytroubleshooter/apiv1/iam_checker_client_example_test.go b/policytroubleshooter/apiv1/iam_checker_client_example_test.go index ebacec7b2c58..a914da36d394 100644 --- a/policytroubleshooter/apiv1/iam_checker_client_example_test.go +++ b/policytroubleshooter/apiv1/iam_checker_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewIamCheckerClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleIamCheckerClient_TroubleshootIamPolicy() { - // import policytroubleshooterpb "google.golang.org/genproto/googleapis/cloud/policytroubleshooter/v1" - ctx := context.Background() c, err := policytroubleshooter.NewIamCheckerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &policytroubleshooterpb.TroubleshootIamPolicyRequest{ // TODO: Fill request struct fields. diff --git a/pubsub/apiv1/doc.go b/pubsub/apiv1/doc.go index fa83b184dd3a..ec863d251a6f 100644 --- a/pubsub/apiv1/doc.go +++ b/pubsub/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package pubsub // import "cloud.google.com/go/pubsub/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/pubsub/apiv1/publisher_client.go b/pubsub/apiv1/publisher_client.go index 927ad8612dc3..e21c0cd1e44c 100644 --- a/pubsub/apiv1/publisher_client.go +++ b/pubsub/apiv1/publisher_client.go @@ -50,7 +50,7 @@ type PublisherCallOptions struct { DetachSubscription []gax.CallOption } -func defaultPublisherClientOptions() []option.ClientOption { +func defaultPublisherGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("pubsub.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("pubsub.mtls.googleapis.com:443"), @@ -180,33 +180,143 @@ func defaultPublisherCallOptions() *PublisherCallOptions { } } +// internalPublisherClient is an interface that defines the methods availaible from Cloud Pub/Sub API. +type internalPublisherClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateTopic(context.Context, *pubsubpb.Topic, ...gax.CallOption) (*pubsubpb.Topic, error) + UpdateTopic(context.Context, *pubsubpb.UpdateTopicRequest, ...gax.CallOption) (*pubsubpb.Topic, error) + Publish(context.Context, *pubsubpb.PublishRequest, ...gax.CallOption) (*pubsubpb.PublishResponse, error) + GetTopic(context.Context, *pubsubpb.GetTopicRequest, ...gax.CallOption) (*pubsubpb.Topic, error) + ListTopics(context.Context, *pubsubpb.ListTopicsRequest, ...gax.CallOption) *TopicIterator + ListTopicSubscriptions(context.Context, *pubsubpb.ListTopicSubscriptionsRequest, ...gax.CallOption) *StringIterator + ListTopicSnapshots(context.Context, *pubsubpb.ListTopicSnapshotsRequest, ...gax.CallOption) *StringIterator + DeleteTopic(context.Context, *pubsubpb.DeleteTopicRequest, ...gax.CallOption) error + DetachSubscription(context.Context, *pubsubpb.DetachSubscriptionRequest, ...gax.CallOption) (*pubsubpb.DetachSubscriptionResponse, error) +} + // PublisherClient is a client for interacting with Cloud Pub/Sub API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The service that an application uses to manipulate topics, and to send +// messages to a topic. type PublisherClient struct { + // The internal transport-dependent client. + internalClient internalPublisherClient + + // The call options for this service. + CallOptions *PublisherCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *PublisherClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *PublisherClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *PublisherClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateTopic creates the given topic with the given name. See the [resource name rules] +// (https://cloud.google.com/pubsub/docs/admin#resource_names (at https://cloud.google.com/pubsub/docs/admin#resource_names)). +func (c *PublisherClient) CreateTopic(ctx context.Context, req *pubsubpb.Topic, opts ...gax.CallOption) (*pubsubpb.Topic, error) { + return c.internalClient.CreateTopic(ctx, req, opts...) +} + +// UpdateTopic updates an existing topic. Note that certain properties of a +// topic are not modifiable. +func (c *PublisherClient) UpdateTopic(ctx context.Context, req *pubsubpb.UpdateTopicRequest, opts ...gax.CallOption) (*pubsubpb.Topic, error) { + return c.internalClient.UpdateTopic(ctx, req, opts...) +} + +// Publish adds one or more messages to the topic. Returns NOT_FOUND if the topic +// does not exist. +func (c *PublisherClient) Publish(ctx context.Context, req *pubsubpb.PublishRequest, opts ...gax.CallOption) (*pubsubpb.PublishResponse, error) { + return c.internalClient.Publish(ctx, req, opts...) +} + +// GetTopic gets the configuration of a topic. +func (c *PublisherClient) GetTopic(ctx context.Context, req *pubsubpb.GetTopicRequest, opts ...gax.CallOption) (*pubsubpb.Topic, error) { + return c.internalClient.GetTopic(ctx, req, opts...) +} + +// ListTopics lists matching topics. +func (c *PublisherClient) ListTopics(ctx context.Context, req *pubsubpb.ListTopicsRequest, opts ...gax.CallOption) *TopicIterator { + return c.internalClient.ListTopics(ctx, req, opts...) +} + +// ListTopicSubscriptions lists the names of the attached subscriptions on this topic. +func (c *PublisherClient) ListTopicSubscriptions(ctx context.Context, req *pubsubpb.ListTopicSubscriptionsRequest, opts ...gax.CallOption) *StringIterator { + return c.internalClient.ListTopicSubscriptions(ctx, req, opts...) +} + +// ListTopicSnapshots lists the names of the snapshots on this topic. Snapshots are used in +// Seek (at https://cloud.google.com/pubsub/docs/replay-overview) operations, +// which allow you to manage message acknowledgments in bulk. That is, you can +// set the acknowledgment state of messages in an existing subscription to the +// state captured by a snapshot. +func (c *PublisherClient) ListTopicSnapshots(ctx context.Context, req *pubsubpb.ListTopicSnapshotsRequest, opts ...gax.CallOption) *StringIterator { + return c.internalClient.ListTopicSnapshots(ctx, req, opts...) +} + +// DeleteTopic deletes the topic with the given name. Returns NOT_FOUND if the topic +// does not exist. After a topic is deleted, a new topic may be created with +// the same name; this is an entirely new topic with none of the old +// configuration or subscriptions. Existing subscriptions to this topic are +// not deleted, but their topic field is set to _deleted-topic_. +func (c *PublisherClient) DeleteTopic(ctx context.Context, req *pubsubpb.DeleteTopicRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTopic(ctx, req, opts...) +} + +// DetachSubscription detaches a subscription from this topic. All messages retained in the +// subscription are dropped. Subsequent Pull and StreamingPull requests +// will return FAILED_PRECONDITION. If the subscription is a push +// subscription, pushes to the endpoint will stop. +func (c *PublisherClient) DetachSubscription(ctx context.Context, req *pubsubpb.DetachSubscriptionRequest, opts ...gax.CallOption) (*pubsubpb.DetachSubscriptionResponse, error) { + return c.internalClient.DetachSubscription(ctx, req, opts...) +} + +// publisherGRPCClient is a client for interacting with Cloud Pub/Sub API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type publisherGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing PublisherClient + CallOptions **PublisherCallOptions + // The gRPC API client. publisherClient pubsubpb.PublisherClient - // The call options for this service. - CallOptions *PublisherCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewPublisherClient creates a new publisher client. +// NewPublisherClient creates a new publisher client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The service that an application uses to manipulate topics, and to send // messages to a topic. func NewPublisherClient(ctx context.Context, opts ...option.ClientOption) (*PublisherClient, error) { - clientOpts := defaultPublisherClientOptions() - + clientOpts := defaultPublisherGRPCClientOptions() if newPublisherClientHook != nil { hookOpts, err := newPublisherClientHook(ctx, clientHookParams{}) if err != nil { @@ -224,43 +334,44 @@ func NewPublisherClient(ctx context.Context, opts ...option.ClientOption) (*Publ if err != nil { return nil, err } - c := &PublisherClient{ + client := PublisherClient{CallOptions: defaultPublisherCallOptions()} + + c := &publisherGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultPublisherCallOptions(), - - publisherClient: pubsubpb.NewPublisherClient(connPool), + publisherClient: pubsubpb.NewPublisherClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *PublisherClient) Connection() *grpc.ClientConn { +func (c *publisherGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *PublisherClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *PublisherClient) setGoogleClientInfo(keyval ...string) { +func (c *publisherGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateTopic creates the given topic with the given name. See the [resource name rules] -// (https://cloud.google.com/pubsub/docs/admin#resource_names (at https://cloud.google.com/pubsub/docs/admin#resource_names)). -func (c *PublisherClient) CreateTopic(ctx context.Context, req *pubsubpb.Topic, opts ...gax.CallOption) (*pubsubpb.Topic, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *publisherGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *publisherGRPCClient) CreateTopic(ctx context.Context, req *pubsubpb.Topic, opts ...gax.CallOption) (*pubsubpb.Topic, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -268,7 +379,7 @@ func (c *PublisherClient) CreateTopic(ctx context.Context, req *pubsubpb.Topic, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTopic[0:len(c.CallOptions.CreateTopic):len(c.CallOptions.CreateTopic)], opts...) + opts = append((*c.CallOptions).CreateTopic[0:len((*c.CallOptions).CreateTopic):len((*c.CallOptions).CreateTopic)], opts...) var resp *pubsubpb.Topic err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -281,9 +392,7 @@ func (c *PublisherClient) CreateTopic(ctx context.Context, req *pubsubpb.Topic, return resp, nil } -// UpdateTopic updates an existing topic. Note that certain properties of a -// topic are not modifiable. -func (c *PublisherClient) UpdateTopic(ctx context.Context, req *pubsubpb.UpdateTopicRequest, opts ...gax.CallOption) (*pubsubpb.Topic, error) { +func (c *publisherGRPCClient) UpdateTopic(ctx context.Context, req *pubsubpb.UpdateTopicRequest, opts ...gax.CallOption) (*pubsubpb.Topic, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -291,7 +400,7 @@ func (c *PublisherClient) UpdateTopic(ctx context.Context, req *pubsubpb.UpdateT } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "topic.name", url.QueryEscape(req.GetTopic().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTopic[0:len(c.CallOptions.UpdateTopic):len(c.CallOptions.UpdateTopic)], opts...) + opts = append((*c.CallOptions).UpdateTopic[0:len((*c.CallOptions).UpdateTopic):len((*c.CallOptions).UpdateTopic)], opts...) var resp *pubsubpb.Topic err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -304,9 +413,7 @@ func (c *PublisherClient) UpdateTopic(ctx context.Context, req *pubsubpb.UpdateT return resp, nil } -// Publish adds one or more messages to the topic. Returns NOT_FOUND if the topic -// does not exist. -func (c *PublisherClient) Publish(ctx context.Context, req *pubsubpb.PublishRequest, opts ...gax.CallOption) (*pubsubpb.PublishResponse, error) { +func (c *publisherGRPCClient) Publish(ctx context.Context, req *pubsubpb.PublishRequest, opts ...gax.CallOption) (*pubsubpb.PublishResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -314,7 +421,7 @@ func (c *PublisherClient) Publish(ctx context.Context, req *pubsubpb.PublishRequ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "topic", url.QueryEscape(req.GetTopic()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.Publish[0:len(c.CallOptions.Publish):len(c.CallOptions.Publish)], opts...) + opts = append((*c.CallOptions).Publish[0:len((*c.CallOptions).Publish):len((*c.CallOptions).Publish)], opts...) var resp *pubsubpb.PublishResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -327,8 +434,7 @@ func (c *PublisherClient) Publish(ctx context.Context, req *pubsubpb.PublishRequ return resp, nil } -// GetTopic gets the configuration of a topic. -func (c *PublisherClient) GetTopic(ctx context.Context, req *pubsubpb.GetTopicRequest, opts ...gax.CallOption) (*pubsubpb.Topic, error) { +func (c *publisherGRPCClient) GetTopic(ctx context.Context, req *pubsubpb.GetTopicRequest, opts ...gax.CallOption) (*pubsubpb.Topic, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -336,7 +442,7 @@ func (c *PublisherClient) GetTopic(ctx context.Context, req *pubsubpb.GetTopicRe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "topic", url.QueryEscape(req.GetTopic()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTopic[0:len(c.CallOptions.GetTopic):len(c.CallOptions.GetTopic)], opts...) + opts = append((*c.CallOptions).GetTopic[0:len((*c.CallOptions).GetTopic):len((*c.CallOptions).GetTopic)], opts...) var resp *pubsubpb.Topic err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -349,11 +455,10 @@ func (c *PublisherClient) GetTopic(ctx context.Context, req *pubsubpb.GetTopicRe return resp, nil } -// ListTopics lists matching topics. -func (c *PublisherClient) ListTopics(ctx context.Context, req *pubsubpb.ListTopicsRequest, opts ...gax.CallOption) *TopicIterator { +func (c *publisherGRPCClient) ListTopics(ctx context.Context, req *pubsubpb.ListTopicsRequest, opts ...gax.CallOption) *TopicIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project", url.QueryEscape(req.GetProject()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTopics[0:len(c.CallOptions.ListTopics):len(c.CallOptions.ListTopics)], opts...) + opts = append((*c.CallOptions).ListTopics[0:len((*c.CallOptions).ListTopics):len((*c.CallOptions).ListTopics)], opts...) it := &TopicIterator{} req = proto.Clone(req).(*pubsubpb.ListTopicsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*pubsubpb.Topic, string, error) { @@ -390,11 +495,10 @@ func (c *PublisherClient) ListTopics(ctx context.Context, req *pubsubpb.ListTopi return it } -// ListTopicSubscriptions lists the names of the attached subscriptions on this topic. -func (c *PublisherClient) ListTopicSubscriptions(ctx context.Context, req *pubsubpb.ListTopicSubscriptionsRequest, opts ...gax.CallOption) *StringIterator { +func (c *publisherGRPCClient) ListTopicSubscriptions(ctx context.Context, req *pubsubpb.ListTopicSubscriptionsRequest, opts ...gax.CallOption) *StringIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "topic", url.QueryEscape(req.GetTopic()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTopicSubscriptions[0:len(c.CallOptions.ListTopicSubscriptions):len(c.CallOptions.ListTopicSubscriptions)], opts...) + opts = append((*c.CallOptions).ListTopicSubscriptions[0:len((*c.CallOptions).ListTopicSubscriptions):len((*c.CallOptions).ListTopicSubscriptions)], opts...) it := &StringIterator{} req = proto.Clone(req).(*pubsubpb.ListTopicSubscriptionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]string, string, error) { @@ -431,15 +535,10 @@ func (c *PublisherClient) ListTopicSubscriptions(ctx context.Context, req *pubsu return it } -// ListTopicSnapshots lists the names of the snapshots on this topic. Snapshots are used in -// Seek (at https://cloud.google.com/pubsub/docs/replay-overview) operations, -// which allow you to manage message acknowledgments in bulk. That is, you can -// set the acknowledgment state of messages in an existing subscription to the -// state captured by a snapshot. -func (c *PublisherClient) ListTopicSnapshots(ctx context.Context, req *pubsubpb.ListTopicSnapshotsRequest, opts ...gax.CallOption) *StringIterator { +func (c *publisherGRPCClient) ListTopicSnapshots(ctx context.Context, req *pubsubpb.ListTopicSnapshotsRequest, opts ...gax.CallOption) *StringIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "topic", url.QueryEscape(req.GetTopic()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTopicSnapshots[0:len(c.CallOptions.ListTopicSnapshots):len(c.CallOptions.ListTopicSnapshots)], opts...) + opts = append((*c.CallOptions).ListTopicSnapshots[0:len((*c.CallOptions).ListTopicSnapshots):len((*c.CallOptions).ListTopicSnapshots)], opts...) it := &StringIterator{} req = proto.Clone(req).(*pubsubpb.ListTopicSnapshotsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]string, string, error) { @@ -476,12 +575,7 @@ func (c *PublisherClient) ListTopicSnapshots(ctx context.Context, req *pubsubpb. return it } -// DeleteTopic deletes the topic with the given name. Returns NOT_FOUND if the topic -// does not exist. After a topic is deleted, a new topic may be created with -// the same name; this is an entirely new topic with none of the old -// configuration or subscriptions. Existing subscriptions to this topic are -// not deleted, but their topic field is set to _deleted-topic_. -func (c *PublisherClient) DeleteTopic(ctx context.Context, req *pubsubpb.DeleteTopicRequest, opts ...gax.CallOption) error { +func (c *publisherGRPCClient) DeleteTopic(ctx context.Context, req *pubsubpb.DeleteTopicRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -489,7 +583,7 @@ func (c *PublisherClient) DeleteTopic(ctx context.Context, req *pubsubpb.DeleteT } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "topic", url.QueryEscape(req.GetTopic()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTopic[0:len(c.CallOptions.DeleteTopic):len(c.CallOptions.DeleteTopic)], opts...) + opts = append((*c.CallOptions).DeleteTopic[0:len((*c.CallOptions).DeleteTopic):len((*c.CallOptions).DeleteTopic)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.publisherClient.DeleteTopic(ctx, req, settings.GRPC...) @@ -498,11 +592,7 @@ func (c *PublisherClient) DeleteTopic(ctx context.Context, req *pubsubpb.DeleteT return err } -// DetachSubscription detaches a subscription from this topic. All messages retained in the -// subscription are dropped. Subsequent Pull and StreamingPull requests -// will return FAILED_PRECONDITION. If the subscription is a push -// subscription, pushes to the endpoint will stop. -func (c *PublisherClient) DetachSubscription(ctx context.Context, req *pubsubpb.DetachSubscriptionRequest, opts ...gax.CallOption) (*pubsubpb.DetachSubscriptionResponse, error) { +func (c *publisherGRPCClient) DetachSubscription(ctx context.Context, req *pubsubpb.DetachSubscriptionRequest, opts ...gax.CallOption) (*pubsubpb.DetachSubscriptionResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -510,7 +600,7 @@ func (c *PublisherClient) DetachSubscription(ctx context.Context, req *pubsubpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription", url.QueryEscape(req.GetSubscription()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DetachSubscription[0:len(c.CallOptions.DetachSubscription):len(c.CallOptions.DetachSubscription)], opts...) + opts = append((*c.CallOptions).DetachSubscription[0:len((*c.CallOptions).DetachSubscription):len((*c.CallOptions).DetachSubscription)], opts...) var resp *pubsubpb.DetachSubscriptionResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/pubsub/apiv1/publisher_client_example_test.go b/pubsub/apiv1/publisher_client_example_test.go index af176b47730a..edd64d79a3e8 100644 --- a/pubsub/apiv1/publisher_client_example_test.go +++ b/pubsub/apiv1/publisher_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewPublisherClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExamplePublisherClient_CreateTopic() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.Topic{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExamplePublisherClient_CreateTopic() { } func ExamplePublisherClient_UpdateTopic() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.UpdateTopicRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExamplePublisherClient_UpdateTopic() { } func ExamplePublisherClient_Publish() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.PublishRequest{ // TODO: Fill request struct fields. @@ -95,13 +94,12 @@ func ExamplePublisherClient_Publish() { } func ExamplePublisherClient_GetTopic() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.GetTopicRequest{ // TODO: Fill request struct fields. @@ -115,14 +113,12 @@ func ExamplePublisherClient_GetTopic() { } func ExamplePublisherClient_ListTopics() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsub.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ListTopicsRequest{ // TODO: Fill request struct fields. @@ -142,14 +138,12 @@ func ExamplePublisherClient_ListTopics() { } func ExamplePublisherClient_ListTopicSubscriptions() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsub.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ListTopicSubscriptionsRequest{ // TODO: Fill request struct fields. @@ -169,14 +163,12 @@ func ExamplePublisherClient_ListTopicSubscriptions() { } func ExamplePublisherClient_ListTopicSnapshots() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsub.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ListTopicSnapshotsRequest{ // TODO: Fill request struct fields. @@ -201,6 +193,7 @@ func ExamplePublisherClient_DeleteTopic() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.DeleteTopicRequest{ // TODO: Fill request struct fields. @@ -212,13 +205,12 @@ func ExamplePublisherClient_DeleteTopic() { } func ExamplePublisherClient_DetachSubscription() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.DetachSubscriptionRequest{ // TODO: Fill request struct fields. diff --git a/pubsub/apiv1/schema_client.go b/pubsub/apiv1/schema_client.go index 20dc3fb1931e..25c3ae1d779e 100644 --- a/pubsub/apiv1/schema_client.go +++ b/pubsub/apiv1/schema_client.go @@ -45,7 +45,7 @@ type SchemaCallOptions struct { ValidateMessage []gax.CallOption } -func defaultSchemaClientOptions() []option.ClientOption { +func defaultSchemaGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("pubsub.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("pubsub.mtls.googleapis.com:443"), @@ -68,32 +68,109 @@ func defaultSchemaCallOptions() *SchemaCallOptions { } } +// internalSchemaClient is an interface that defines the methods availaible from Cloud Pub/Sub API. +type internalSchemaClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateSchema(context.Context, *pubsubpb.CreateSchemaRequest, ...gax.CallOption) (*pubsubpb.Schema, error) + GetSchema(context.Context, *pubsubpb.GetSchemaRequest, ...gax.CallOption) (*pubsubpb.Schema, error) + ListSchemas(context.Context, *pubsubpb.ListSchemasRequest, ...gax.CallOption) *SchemaIterator + DeleteSchema(context.Context, *pubsubpb.DeleteSchemaRequest, ...gax.CallOption) error + ValidateSchema(context.Context, *pubsubpb.ValidateSchemaRequest, ...gax.CallOption) (*pubsubpb.ValidateSchemaResponse, error) + ValidateMessage(context.Context, *pubsubpb.ValidateMessageRequest, ...gax.CallOption) (*pubsubpb.ValidateMessageResponse, error) +} + // SchemaClient is a client for interacting with Cloud Pub/Sub API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for doing schema-related operations. type SchemaClient struct { + // The internal transport-dependent client. + internalClient internalSchemaClient + + // The call options for this service. + CallOptions *SchemaCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *SchemaClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *SchemaClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *SchemaClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateSchema creates a schema. +func (c *SchemaClient) CreateSchema(ctx context.Context, req *pubsubpb.CreateSchemaRequest, opts ...gax.CallOption) (*pubsubpb.Schema, error) { + return c.internalClient.CreateSchema(ctx, req, opts...) +} + +// GetSchema gets a schema. +func (c *SchemaClient) GetSchema(ctx context.Context, req *pubsubpb.GetSchemaRequest, opts ...gax.CallOption) (*pubsubpb.Schema, error) { + return c.internalClient.GetSchema(ctx, req, opts...) +} + +// ListSchemas lists schemas in a project. +func (c *SchemaClient) ListSchemas(ctx context.Context, req *pubsubpb.ListSchemasRequest, opts ...gax.CallOption) *SchemaIterator { + return c.internalClient.ListSchemas(ctx, req, opts...) +} + +// DeleteSchema deletes a schema. +func (c *SchemaClient) DeleteSchema(ctx context.Context, req *pubsubpb.DeleteSchemaRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteSchema(ctx, req, opts...) +} + +// ValidateSchema validates a schema. +func (c *SchemaClient) ValidateSchema(ctx context.Context, req *pubsubpb.ValidateSchemaRequest, opts ...gax.CallOption) (*pubsubpb.ValidateSchemaResponse, error) { + return c.internalClient.ValidateSchema(ctx, req, opts...) +} + +// ValidateMessage validates a message against a schema. +func (c *SchemaClient) ValidateMessage(ctx context.Context, req *pubsubpb.ValidateMessageRequest, opts ...gax.CallOption) (*pubsubpb.ValidateMessageResponse, error) { + return c.internalClient.ValidateMessage(ctx, req, opts...) +} + +// schemaGRPCClient is a client for interacting with Cloud Pub/Sub API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type schemaGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing SchemaClient + CallOptions **SchemaCallOptions + // The gRPC API client. schemaClient pubsubpb.SchemaServiceClient - // The call options for this service. - CallOptions *SchemaCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewSchemaClient creates a new schema service client. +// NewSchemaClient creates a new schema service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for doing schema-related operations. func NewSchemaClient(ctx context.Context, opts ...option.ClientOption) (*SchemaClient, error) { - clientOpts := defaultSchemaClientOptions() - + clientOpts := defaultSchemaGRPCClientOptions() if newSchemaClientHook != nil { hookOpts, err := newSchemaClientHook(ctx, clientHookParams{}) if err != nil { @@ -111,45 +188,47 @@ func NewSchemaClient(ctx context.Context, opts ...option.ClientOption) (*SchemaC if err != nil { return nil, err } - c := &SchemaClient{ + client := SchemaClient{CallOptions: defaultSchemaCallOptions()} + + c := &schemaGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultSchemaCallOptions(), - - schemaClient: pubsubpb.NewSchemaServiceClient(connPool), + schemaClient: pubsubpb.NewSchemaServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *SchemaClient) Connection() *grpc.ClientConn { +func (c *schemaGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *SchemaClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *SchemaClient) setGoogleClientInfo(keyval ...string) { +func (c *schemaGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateSchema creates a schema. -func (c *SchemaClient) CreateSchema(ctx context.Context, req *pubsubpb.CreateSchemaRequest, opts ...gax.CallOption) (*pubsubpb.Schema, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *schemaGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *schemaGRPCClient) CreateSchema(ctx context.Context, req *pubsubpb.CreateSchemaRequest, opts ...gax.CallOption) (*pubsubpb.Schema, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSchema[0:len(c.CallOptions.CreateSchema):len(c.CallOptions.CreateSchema)], opts...) + opts = append((*c.CallOptions).CreateSchema[0:len((*c.CallOptions).CreateSchema):len((*c.CallOptions).CreateSchema)], opts...) var resp *pubsubpb.Schema err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -162,11 +241,10 @@ func (c *SchemaClient) CreateSchema(ctx context.Context, req *pubsubpb.CreateSch return resp, nil } -// GetSchema gets a schema. -func (c *SchemaClient) GetSchema(ctx context.Context, req *pubsubpb.GetSchemaRequest, opts ...gax.CallOption) (*pubsubpb.Schema, error) { +func (c *schemaGRPCClient) GetSchema(ctx context.Context, req *pubsubpb.GetSchemaRequest, opts ...gax.CallOption) (*pubsubpb.Schema, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSchema[0:len(c.CallOptions.GetSchema):len(c.CallOptions.GetSchema)], opts...) + opts = append((*c.CallOptions).GetSchema[0:len((*c.CallOptions).GetSchema):len((*c.CallOptions).GetSchema)], opts...) var resp *pubsubpb.Schema err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -179,11 +257,10 @@ func (c *SchemaClient) GetSchema(ctx context.Context, req *pubsubpb.GetSchemaReq return resp, nil } -// ListSchemas lists schemas in a project. -func (c *SchemaClient) ListSchemas(ctx context.Context, req *pubsubpb.ListSchemasRequest, opts ...gax.CallOption) *SchemaIterator { +func (c *schemaGRPCClient) ListSchemas(ctx context.Context, req *pubsubpb.ListSchemasRequest, opts ...gax.CallOption) *SchemaIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSchemas[0:len(c.CallOptions.ListSchemas):len(c.CallOptions.ListSchemas)], opts...) + opts = append((*c.CallOptions).ListSchemas[0:len((*c.CallOptions).ListSchemas):len((*c.CallOptions).ListSchemas)], opts...) it := &SchemaIterator{} req = proto.Clone(req).(*pubsubpb.ListSchemasRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*pubsubpb.Schema, string, error) { @@ -220,11 +297,10 @@ func (c *SchemaClient) ListSchemas(ctx context.Context, req *pubsubpb.ListSchema return it } -// DeleteSchema deletes a schema. -func (c *SchemaClient) DeleteSchema(ctx context.Context, req *pubsubpb.DeleteSchemaRequest, opts ...gax.CallOption) error { +func (c *schemaGRPCClient) DeleteSchema(ctx context.Context, req *pubsubpb.DeleteSchemaRequest, opts ...gax.CallOption) error { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteSchema[0:len(c.CallOptions.DeleteSchema):len(c.CallOptions.DeleteSchema)], opts...) + opts = append((*c.CallOptions).DeleteSchema[0:len((*c.CallOptions).DeleteSchema):len((*c.CallOptions).DeleteSchema)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.schemaClient.DeleteSchema(ctx, req, settings.GRPC...) @@ -233,11 +309,10 @@ func (c *SchemaClient) DeleteSchema(ctx context.Context, req *pubsubpb.DeleteSch return err } -// ValidateSchema validates a schema. -func (c *SchemaClient) ValidateSchema(ctx context.Context, req *pubsubpb.ValidateSchemaRequest, opts ...gax.CallOption) (*pubsubpb.ValidateSchemaResponse, error) { +func (c *schemaGRPCClient) ValidateSchema(ctx context.Context, req *pubsubpb.ValidateSchemaRequest, opts ...gax.CallOption) (*pubsubpb.ValidateSchemaResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ValidateSchema[0:len(c.CallOptions.ValidateSchema):len(c.CallOptions.ValidateSchema)], opts...) + opts = append((*c.CallOptions).ValidateSchema[0:len((*c.CallOptions).ValidateSchema):len((*c.CallOptions).ValidateSchema)], opts...) var resp *pubsubpb.ValidateSchemaResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -250,11 +325,10 @@ func (c *SchemaClient) ValidateSchema(ctx context.Context, req *pubsubpb.Validat return resp, nil } -// ValidateMessage validates a message against a schema. -func (c *SchemaClient) ValidateMessage(ctx context.Context, req *pubsubpb.ValidateMessageRequest, opts ...gax.CallOption) (*pubsubpb.ValidateMessageResponse, error) { +func (c *schemaGRPCClient) ValidateMessage(ctx context.Context, req *pubsubpb.ValidateMessageRequest, opts ...gax.CallOption) (*pubsubpb.ValidateMessageResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ValidateMessage[0:len(c.CallOptions.ValidateMessage):len(c.CallOptions.ValidateMessage)], opts...) + opts = append((*c.CallOptions).ValidateMessage[0:len((*c.CallOptions).ValidateMessage):len((*c.CallOptions).ValidateMessage)], opts...) var resp *pubsubpb.ValidateMessageResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/pubsub/apiv1/schema_client_example_test.go b/pubsub/apiv1/schema_client_example_test.go index 2160a6d181db..71fecd041af3 100644 --- a/pubsub/apiv1/schema_client_example_test.go +++ b/pubsub/apiv1/schema_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewSchemaClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleSchemaClient_CreateSchema() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSchemaClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.CreateSchemaRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleSchemaClient_CreateSchema() { } func ExampleSchemaClient_GetSchema() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSchemaClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.GetSchemaRequest{ // TODO: Fill request struct fields. @@ -75,14 +75,12 @@ func ExampleSchemaClient_GetSchema() { } func ExampleSchemaClient_ListSchemas() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsub.NewSchemaClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ListSchemasRequest{ // TODO: Fill request struct fields. @@ -107,6 +105,7 @@ func ExampleSchemaClient_DeleteSchema() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.DeleteSchemaRequest{ // TODO: Fill request struct fields. @@ -118,13 +117,12 @@ func ExampleSchemaClient_DeleteSchema() { } func ExampleSchemaClient_ValidateSchema() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSchemaClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ValidateSchemaRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleSchemaClient_ValidateSchema() { } func ExampleSchemaClient_ValidateMessage() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSchemaClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ValidateMessageRequest{ // TODO: Fill request struct fields. diff --git a/pubsub/apiv1/subscriber_client.go b/pubsub/apiv1/subscriber_client.go index 128f09b80074..7c0bc409cf3e 100644 --- a/pubsub/apiv1/subscriber_client.go +++ b/pubsub/apiv1/subscriber_client.go @@ -57,7 +57,7 @@ type SubscriberCallOptions struct { Seek []gax.CallOption } -func defaultSubscriberClientOptions() []option.ClientOption { +func defaultSubscriberGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("pubsub.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("pubsub.mtls.googleapis.com:443"), @@ -268,34 +268,252 @@ func defaultSubscriberCallOptions() *SubscriberCallOptions { } } +// internalSubscriberClient is an interface that defines the methods availaible from Cloud Pub/Sub API. +type internalSubscriberClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateSubscription(context.Context, *pubsubpb.Subscription, ...gax.CallOption) (*pubsubpb.Subscription, error) + GetSubscription(context.Context, *pubsubpb.GetSubscriptionRequest, ...gax.CallOption) (*pubsubpb.Subscription, error) + UpdateSubscription(context.Context, *pubsubpb.UpdateSubscriptionRequest, ...gax.CallOption) (*pubsubpb.Subscription, error) + ListSubscriptions(context.Context, *pubsubpb.ListSubscriptionsRequest, ...gax.CallOption) *SubscriptionIterator + DeleteSubscription(context.Context, *pubsubpb.DeleteSubscriptionRequest, ...gax.CallOption) error + ModifyAckDeadline(context.Context, *pubsubpb.ModifyAckDeadlineRequest, ...gax.CallOption) error + Acknowledge(context.Context, *pubsubpb.AcknowledgeRequest, ...gax.CallOption) error + Pull(context.Context, *pubsubpb.PullRequest, ...gax.CallOption) (*pubsubpb.PullResponse, error) + StreamingPull(context.Context, ...gax.CallOption) (pubsubpb.Subscriber_StreamingPullClient, error) + ModifyPushConfig(context.Context, *pubsubpb.ModifyPushConfigRequest, ...gax.CallOption) error + GetSnapshot(context.Context, *pubsubpb.GetSnapshotRequest, ...gax.CallOption) (*pubsubpb.Snapshot, error) + ListSnapshots(context.Context, *pubsubpb.ListSnapshotsRequest, ...gax.CallOption) *SnapshotIterator + CreateSnapshot(context.Context, *pubsubpb.CreateSnapshotRequest, ...gax.CallOption) (*pubsubpb.Snapshot, error) + UpdateSnapshot(context.Context, *pubsubpb.UpdateSnapshotRequest, ...gax.CallOption) (*pubsubpb.Snapshot, error) + DeleteSnapshot(context.Context, *pubsubpb.DeleteSnapshotRequest, ...gax.CallOption) error + Seek(context.Context, *pubsubpb.SeekRequest, ...gax.CallOption) (*pubsubpb.SeekResponse, error) +} + // SubscriberClient is a client for interacting with Cloud Pub/Sub API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The service that an application uses to manipulate subscriptions and to +// consume messages from a subscription via the Pull method or by +// establishing a bi-directional stream using the StreamingPull method. type SubscriberClient struct { + // The internal transport-dependent client. + internalClient internalSubscriberClient + + // The call options for this service. + CallOptions *SubscriberCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *SubscriberClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *SubscriberClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *SubscriberClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateSubscription creates a subscription to a given topic. See the [resource name rules] +// (https://cloud.google.com/pubsub/docs/admin#resource_names (at https://cloud.google.com/pubsub/docs/admin#resource_names)). +// If the subscription already exists, returns ALREADY_EXISTS. +// If the corresponding topic doesn’t exist, returns NOT_FOUND. +// +// If the name is not provided in the request, the server will assign a random +// name for this subscription on the same project as the topic, conforming +// to the [resource name format] +// (https://cloud.google.com/pubsub/docs/admin#resource_names (at https://cloud.google.com/pubsub/docs/admin#resource_names)). The generated +// name is populated in the returned Subscription object. Note that for REST +// API requests, you must specify a name in the request. +func (c *SubscriberClient) CreateSubscription(ctx context.Context, req *pubsubpb.Subscription, opts ...gax.CallOption) (*pubsubpb.Subscription, error) { + return c.internalClient.CreateSubscription(ctx, req, opts...) +} + +// GetSubscription gets the configuration details of a subscription. +func (c *SubscriberClient) GetSubscription(ctx context.Context, req *pubsubpb.GetSubscriptionRequest, opts ...gax.CallOption) (*pubsubpb.Subscription, error) { + return c.internalClient.GetSubscription(ctx, req, opts...) +} + +// UpdateSubscription updates an existing subscription. Note that certain properties of a +// subscription, such as its topic, are not modifiable. +func (c *SubscriberClient) UpdateSubscription(ctx context.Context, req *pubsubpb.UpdateSubscriptionRequest, opts ...gax.CallOption) (*pubsubpb.Subscription, error) { + return c.internalClient.UpdateSubscription(ctx, req, opts...) +} + +// ListSubscriptions lists matching subscriptions. +func (c *SubscriberClient) ListSubscriptions(ctx context.Context, req *pubsubpb.ListSubscriptionsRequest, opts ...gax.CallOption) *SubscriptionIterator { + return c.internalClient.ListSubscriptions(ctx, req, opts...) +} + +// DeleteSubscription deletes an existing subscription. All messages retained in the subscription +// are immediately dropped. Calls to Pull after deletion will return +// NOT_FOUND. After a subscription is deleted, a new one may be created with +// the same name, but the new one has no association with the old +// subscription or its topic unless the same topic is specified. +func (c *SubscriberClient) DeleteSubscription(ctx context.Context, req *pubsubpb.DeleteSubscriptionRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteSubscription(ctx, req, opts...) +} + +// ModifyAckDeadline modifies the ack deadline for a specific message. This method is useful +// to indicate that more time is needed to process a message by the +// subscriber, or to make the message available for redelivery if the +// processing was interrupted. Note that this does not modify the +// subscription-level ackDeadlineSeconds used for subsequent messages. +func (c *SubscriberClient) ModifyAckDeadline(ctx context.Context, req *pubsubpb.ModifyAckDeadlineRequest, opts ...gax.CallOption) error { + return c.internalClient.ModifyAckDeadline(ctx, req, opts...) +} + +// Acknowledge acknowledges the messages associated with the ack_ids in the +// AcknowledgeRequest. The Pub/Sub system can remove the relevant messages +// from the subscription. +// +// Acknowledging a message whose ack deadline has expired may succeed, +// but such a message may be redelivered later. Acknowledging a message more +// than once will not result in an error. +func (c *SubscriberClient) Acknowledge(ctx context.Context, req *pubsubpb.AcknowledgeRequest, opts ...gax.CallOption) error { + return c.internalClient.Acknowledge(ctx, req, opts...) +} + +// Pull pulls messages from the server. The server may return UNAVAILABLE if +// there are too many concurrent pull requests pending for the given +// subscription. +func (c *SubscriberClient) Pull(ctx context.Context, req *pubsubpb.PullRequest, opts ...gax.CallOption) (*pubsubpb.PullResponse, error) { + return c.internalClient.Pull(ctx, req, opts...) +} + +// StreamingPull establishes a stream with the server, which sends messages down to the +// client. The client streams acknowledgements and ack deadline modifications +// back to the server. The server will close the stream and return the status +// on any error. The server may close the stream with status UNAVAILABLE to +// reassign server-side resources, in which case, the client should +// re-establish the stream. Flow control can be achieved by configuring the +// underlying RPC channel. +func (c *SubscriberClient) StreamingPull(ctx context.Context, opts ...gax.CallOption) (pubsubpb.Subscriber_StreamingPullClient, error) { + return c.internalClient.StreamingPull(ctx, opts...) +} + +// ModifyPushConfig modifies the PushConfig for a specified subscription. +// +// This may be used to change a push subscription to a pull one (signified by +// an empty PushConfig) or vice versa, or change the endpoint URL and other +// attributes of a push subscription. Messages will accumulate for delivery +// continuously through the call regardless of changes to the PushConfig. +func (c *SubscriberClient) ModifyPushConfig(ctx context.Context, req *pubsubpb.ModifyPushConfigRequest, opts ...gax.CallOption) error { + return c.internalClient.ModifyPushConfig(ctx, req, opts...) +} + +// GetSnapshot gets the configuration details of a snapshot. Snapshots are used in +// Seek (at https://cloud.google.com/pubsub/docs/replay-overview) +// operations, which allow you to manage message acknowledgments in bulk. That +// is, you can set the acknowledgment state of messages in an existing +// subscription to the state captured by a snapshot. +func (c *SubscriberClient) GetSnapshot(ctx context.Context, req *pubsubpb.GetSnapshotRequest, opts ...gax.CallOption) (*pubsubpb.Snapshot, error) { + return c.internalClient.GetSnapshot(ctx, req, opts...) +} + +// ListSnapshots lists the existing snapshots. Snapshots are used in Seek (at https://cloud.google.com/pubsub/docs/replay-overview) operations, which +// allow you to manage message acknowledgments in bulk. That is, you can set +// the acknowledgment state of messages in an existing subscription to the +// state captured by a snapshot. +func (c *SubscriberClient) ListSnapshots(ctx context.Context, req *pubsubpb.ListSnapshotsRequest, opts ...gax.CallOption) *SnapshotIterator { + return c.internalClient.ListSnapshots(ctx, req, opts...) +} + +// CreateSnapshot creates a snapshot from the requested subscription. Snapshots are used in +// Seek (at https://cloud.google.com/pubsub/docs/replay-overview) operations, +// which allow you to manage message acknowledgments in bulk. That is, you can +// set the acknowledgment state of messages in an existing subscription to the +// state captured by a snapshot. +// If the snapshot already exists, returns ALREADY_EXISTS. +// If the requested subscription doesn’t exist, returns NOT_FOUND. +// If the backlog in the subscription is too old – and the resulting snapshot +// would expire in less than 1 hour – then FAILED_PRECONDITION is returned. +// See also the Snapshot.expire_time field. If the name is not provided in +// the request, the server will assign a random +// name for this snapshot on the same project as the subscription, conforming +// to the [resource name format] +// (https://cloud.google.com/pubsub/docs/admin#resource_names (at https://cloud.google.com/pubsub/docs/admin#resource_names)). The +// generated name is populated in the returned Snapshot object. Note that for +// REST API requests, you must specify a name in the request. +func (c *SubscriberClient) CreateSnapshot(ctx context.Context, req *pubsubpb.CreateSnapshotRequest, opts ...gax.CallOption) (*pubsubpb.Snapshot, error) { + return c.internalClient.CreateSnapshot(ctx, req, opts...) +} + +// UpdateSnapshot updates an existing snapshot. Snapshots are used in +// Seek (at https://cloud.google.com/pubsub/docs/replay-overview) +// operations, which allow +// you to manage message acknowledgments in bulk. That is, you can set the +// acknowledgment state of messages in an existing subscription to the state +// captured by a snapshot. +func (c *SubscriberClient) UpdateSnapshot(ctx context.Context, req *pubsubpb.UpdateSnapshotRequest, opts ...gax.CallOption) (*pubsubpb.Snapshot, error) { + return c.internalClient.UpdateSnapshot(ctx, req, opts...) +} + +// DeleteSnapshot removes an existing snapshot. Snapshots are used in [Seek] +// (https://cloud.google.com/pubsub/docs/replay-overview (at https://cloud.google.com/pubsub/docs/replay-overview)) operations, which +// allow you to manage message acknowledgments in bulk. That is, you can set +// the acknowledgment state of messages in an existing subscription to the +// state captured by a snapshot. +// When the snapshot is deleted, all messages retained in the snapshot +// are immediately dropped. After a snapshot is deleted, a new one may be +// created with the same name, but the new one has no association with the old +// snapshot or its subscription, unless the same subscription is specified. +func (c *SubscriberClient) DeleteSnapshot(ctx context.Context, req *pubsubpb.DeleteSnapshotRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteSnapshot(ctx, req, opts...) +} + +// Seek seeks an existing subscription to a point in time or to a given snapshot, +// whichever is provided in the request. Snapshots are used in [Seek] +// (https://cloud.google.com/pubsub/docs/replay-overview (at https://cloud.google.com/pubsub/docs/replay-overview)) operations, which +// allow you to manage message acknowledgments in bulk. That is, you can set +// the acknowledgment state of messages in an existing subscription to the +// state captured by a snapshot. Note that both the subscription and the +// snapshot must be on the same topic. +func (c *SubscriberClient) Seek(ctx context.Context, req *pubsubpb.SeekRequest, opts ...gax.CallOption) (*pubsubpb.SeekResponse, error) { + return c.internalClient.Seek(ctx, req, opts...) +} + +// subscriberGRPCClient is a client for interacting with Cloud Pub/Sub API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type subscriberGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing SubscriberClient + CallOptions **SubscriberCallOptions + // The gRPC API client. subscriberClient pubsubpb.SubscriberClient - // The call options for this service. - CallOptions *SubscriberCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewSubscriberClient creates a new subscriber client. +// NewSubscriberClient creates a new subscriber client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The service that an application uses to manipulate subscriptions and to // consume messages from a subscription via the Pull method or by // establishing a bi-directional stream using the StreamingPull method. func NewSubscriberClient(ctx context.Context, opts ...option.ClientOption) (*SubscriberClient, error) { - clientOpts := defaultSubscriberClientOptions() - + clientOpts := defaultSubscriberGRPCClientOptions() if newSubscriberClientHook != nil { hookOpts, err := newSubscriberClientHook(ctx, clientHookParams{}) if err != nil { @@ -313,52 +531,44 @@ func NewSubscriberClient(ctx context.Context, opts ...option.ClientOption) (*Sub if err != nil { return nil, err } - c := &SubscriberClient{ + client := SubscriberClient{CallOptions: defaultSubscriberCallOptions()} + + c := &subscriberGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultSubscriberCallOptions(), - subscriberClient: pubsubpb.NewSubscriberClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *SubscriberClient) Connection() *grpc.ClientConn { +func (c *subscriberGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *SubscriberClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *SubscriberClient) setGoogleClientInfo(keyval ...string) { +func (c *subscriberGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateSubscription creates a subscription to a given topic. See the [resource name rules] -// (https://cloud.google.com/pubsub/docs/admin#resource_names (at https://cloud.google.com/pubsub/docs/admin#resource_names)). -// If the subscription already exists, returns ALREADY_EXISTS. -// If the corresponding topic doesn’t exist, returns NOT_FOUND. -// -// If the name is not provided in the request, the server will assign a random -// name for this subscription on the same project as the topic, conforming -// to the [resource name format] -// (https://cloud.google.com/pubsub/docs/admin#resource_names (at https://cloud.google.com/pubsub/docs/admin#resource_names)). The generated -// name is populated in the returned Subscription object. Note that for REST -// API requests, you must specify a name in the request. -func (c *SubscriberClient) CreateSubscription(ctx context.Context, req *pubsubpb.Subscription, opts ...gax.CallOption) (*pubsubpb.Subscription, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *subscriberGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *subscriberGRPCClient) CreateSubscription(ctx context.Context, req *pubsubpb.Subscription, opts ...gax.CallOption) (*pubsubpb.Subscription, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -366,7 +576,7 @@ func (c *SubscriberClient) CreateSubscription(ctx context.Context, req *pubsubpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSubscription[0:len(c.CallOptions.CreateSubscription):len(c.CallOptions.CreateSubscription)], opts...) + opts = append((*c.CallOptions).CreateSubscription[0:len((*c.CallOptions).CreateSubscription):len((*c.CallOptions).CreateSubscription)], opts...) var resp *pubsubpb.Subscription err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -379,8 +589,7 @@ func (c *SubscriberClient) CreateSubscription(ctx context.Context, req *pubsubpb return resp, nil } -// GetSubscription gets the configuration details of a subscription. -func (c *SubscriberClient) GetSubscription(ctx context.Context, req *pubsubpb.GetSubscriptionRequest, opts ...gax.CallOption) (*pubsubpb.Subscription, error) { +func (c *subscriberGRPCClient) GetSubscription(ctx context.Context, req *pubsubpb.GetSubscriptionRequest, opts ...gax.CallOption) (*pubsubpb.Subscription, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -388,7 +597,7 @@ func (c *SubscriberClient) GetSubscription(ctx context.Context, req *pubsubpb.Ge } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription", url.QueryEscape(req.GetSubscription()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSubscription[0:len(c.CallOptions.GetSubscription):len(c.CallOptions.GetSubscription)], opts...) + opts = append((*c.CallOptions).GetSubscription[0:len((*c.CallOptions).GetSubscription):len((*c.CallOptions).GetSubscription)], opts...) var resp *pubsubpb.Subscription err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -401,9 +610,7 @@ func (c *SubscriberClient) GetSubscription(ctx context.Context, req *pubsubpb.Ge return resp, nil } -// UpdateSubscription updates an existing subscription. Note that certain properties of a -// subscription, such as its topic, are not modifiable. -func (c *SubscriberClient) UpdateSubscription(ctx context.Context, req *pubsubpb.UpdateSubscriptionRequest, opts ...gax.CallOption) (*pubsubpb.Subscription, error) { +func (c *subscriberGRPCClient) UpdateSubscription(ctx context.Context, req *pubsubpb.UpdateSubscriptionRequest, opts ...gax.CallOption) (*pubsubpb.Subscription, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -411,7 +618,7 @@ func (c *SubscriberClient) UpdateSubscription(ctx context.Context, req *pubsubpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription.name", url.QueryEscape(req.GetSubscription().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSubscription[0:len(c.CallOptions.UpdateSubscription):len(c.CallOptions.UpdateSubscription)], opts...) + opts = append((*c.CallOptions).UpdateSubscription[0:len((*c.CallOptions).UpdateSubscription):len((*c.CallOptions).UpdateSubscription)], opts...) var resp *pubsubpb.Subscription err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -424,11 +631,10 @@ func (c *SubscriberClient) UpdateSubscription(ctx context.Context, req *pubsubpb return resp, nil } -// ListSubscriptions lists matching subscriptions. -func (c *SubscriberClient) ListSubscriptions(ctx context.Context, req *pubsubpb.ListSubscriptionsRequest, opts ...gax.CallOption) *SubscriptionIterator { +func (c *subscriberGRPCClient) ListSubscriptions(ctx context.Context, req *pubsubpb.ListSubscriptionsRequest, opts ...gax.CallOption) *SubscriptionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project", url.QueryEscape(req.GetProject()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSubscriptions[0:len(c.CallOptions.ListSubscriptions):len(c.CallOptions.ListSubscriptions)], opts...) + opts = append((*c.CallOptions).ListSubscriptions[0:len((*c.CallOptions).ListSubscriptions):len((*c.CallOptions).ListSubscriptions)], opts...) it := &SubscriptionIterator{} req = proto.Clone(req).(*pubsubpb.ListSubscriptionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*pubsubpb.Subscription, string, error) { @@ -465,12 +671,7 @@ func (c *SubscriberClient) ListSubscriptions(ctx context.Context, req *pubsubpb. return it } -// DeleteSubscription deletes an existing subscription. All messages retained in the subscription -// are immediately dropped. Calls to Pull after deletion will return -// NOT_FOUND. After a subscription is deleted, a new one may be created with -// the same name, but the new one has no association with the old -// subscription or its topic unless the same topic is specified. -func (c *SubscriberClient) DeleteSubscription(ctx context.Context, req *pubsubpb.DeleteSubscriptionRequest, opts ...gax.CallOption) error { +func (c *subscriberGRPCClient) DeleteSubscription(ctx context.Context, req *pubsubpb.DeleteSubscriptionRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -478,7 +679,7 @@ func (c *SubscriberClient) DeleteSubscription(ctx context.Context, req *pubsubpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription", url.QueryEscape(req.GetSubscription()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteSubscription[0:len(c.CallOptions.DeleteSubscription):len(c.CallOptions.DeleteSubscription)], opts...) + opts = append((*c.CallOptions).DeleteSubscription[0:len((*c.CallOptions).DeleteSubscription):len((*c.CallOptions).DeleteSubscription)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.subscriberClient.DeleteSubscription(ctx, req, settings.GRPC...) @@ -487,12 +688,7 @@ func (c *SubscriberClient) DeleteSubscription(ctx context.Context, req *pubsubpb return err } -// ModifyAckDeadline modifies the ack deadline for a specific message. This method is useful -// to indicate that more time is needed to process a message by the -// subscriber, or to make the message available for redelivery if the -// processing was interrupted. Note that this does not modify the -// subscription-level ackDeadlineSeconds used for subsequent messages. -func (c *SubscriberClient) ModifyAckDeadline(ctx context.Context, req *pubsubpb.ModifyAckDeadlineRequest, opts ...gax.CallOption) error { +func (c *subscriberGRPCClient) ModifyAckDeadline(ctx context.Context, req *pubsubpb.ModifyAckDeadlineRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -500,7 +696,7 @@ func (c *SubscriberClient) ModifyAckDeadline(ctx context.Context, req *pubsubpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription", url.QueryEscape(req.GetSubscription()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ModifyAckDeadline[0:len(c.CallOptions.ModifyAckDeadline):len(c.CallOptions.ModifyAckDeadline)], opts...) + opts = append((*c.CallOptions).ModifyAckDeadline[0:len((*c.CallOptions).ModifyAckDeadline):len((*c.CallOptions).ModifyAckDeadline)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.subscriberClient.ModifyAckDeadline(ctx, req, settings.GRPC...) @@ -509,14 +705,7 @@ func (c *SubscriberClient) ModifyAckDeadline(ctx context.Context, req *pubsubpb. return err } -// Acknowledge acknowledges the messages associated with the ack_ids in the -// AcknowledgeRequest. The Pub/Sub system can remove the relevant messages -// from the subscription. -// -// Acknowledging a message whose ack deadline has expired may succeed, -// but such a message may be redelivered later. Acknowledging a message more -// than once will not result in an error. -func (c *SubscriberClient) Acknowledge(ctx context.Context, req *pubsubpb.AcknowledgeRequest, opts ...gax.CallOption) error { +func (c *subscriberGRPCClient) Acknowledge(ctx context.Context, req *pubsubpb.AcknowledgeRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -524,7 +713,7 @@ func (c *SubscriberClient) Acknowledge(ctx context.Context, req *pubsubpb.Acknow } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription", url.QueryEscape(req.GetSubscription()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.Acknowledge[0:len(c.CallOptions.Acknowledge):len(c.CallOptions.Acknowledge)], opts...) + opts = append((*c.CallOptions).Acknowledge[0:len((*c.CallOptions).Acknowledge):len((*c.CallOptions).Acknowledge)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.subscriberClient.Acknowledge(ctx, req, settings.GRPC...) @@ -533,10 +722,7 @@ func (c *SubscriberClient) Acknowledge(ctx context.Context, req *pubsubpb.Acknow return err } -// Pull pulls messages from the server. The server may return UNAVAILABLE if -// there are too many concurrent pull requests pending for the given -// subscription. -func (c *SubscriberClient) Pull(ctx context.Context, req *pubsubpb.PullRequest, opts ...gax.CallOption) (*pubsubpb.PullResponse, error) { +func (c *subscriberGRPCClient) Pull(ctx context.Context, req *pubsubpb.PullRequest, opts ...gax.CallOption) (*pubsubpb.PullResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -544,7 +730,7 @@ func (c *SubscriberClient) Pull(ctx context.Context, req *pubsubpb.PullRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription", url.QueryEscape(req.GetSubscription()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.Pull[0:len(c.CallOptions.Pull):len(c.CallOptions.Pull)], opts...) + opts = append((*c.CallOptions).Pull[0:len((*c.CallOptions).Pull):len((*c.CallOptions).Pull)], opts...) var resp *pubsubpb.PullResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -557,17 +743,10 @@ func (c *SubscriberClient) Pull(ctx context.Context, req *pubsubpb.PullRequest, return resp, nil } -// StreamingPull establishes a stream with the server, which sends messages down to the -// client. The client streams acknowledgements and ack deadline modifications -// back to the server. The server will close the stream and return the status -// on any error. The server may close the stream with status UNAVAILABLE to -// reassign server-side resources, in which case, the client should -// re-establish the stream. Flow control can be achieved by configuring the -// underlying RPC channel. -func (c *SubscriberClient) StreamingPull(ctx context.Context, opts ...gax.CallOption) (pubsubpb.Subscriber_StreamingPullClient, error) { +func (c *subscriberGRPCClient) StreamingPull(ctx context.Context, opts ...gax.CallOption) (pubsubpb.Subscriber_StreamingPullClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.StreamingPull[0:len(c.CallOptions.StreamingPull):len(c.CallOptions.StreamingPull)], opts...) var resp pubsubpb.Subscriber_StreamingPullClient + opts = append((*c.CallOptions).StreamingPull[0:len((*c.CallOptions).StreamingPull):len((*c.CallOptions).StreamingPull)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.subscriberClient.StreamingPull(ctx, settings.GRPC...) @@ -579,13 +758,7 @@ func (c *SubscriberClient) StreamingPull(ctx context.Context, opts ...gax.CallOp return resp, nil } -// ModifyPushConfig modifies the PushConfig for a specified subscription. -// -// This may be used to change a push subscription to a pull one (signified by -// an empty PushConfig) or vice versa, or change the endpoint URL and other -// attributes of a push subscription. Messages will accumulate for delivery -// continuously through the call regardless of changes to the PushConfig. -func (c *SubscriberClient) ModifyPushConfig(ctx context.Context, req *pubsubpb.ModifyPushConfigRequest, opts ...gax.CallOption) error { +func (c *subscriberGRPCClient) ModifyPushConfig(ctx context.Context, req *pubsubpb.ModifyPushConfigRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -593,7 +766,7 @@ func (c *SubscriberClient) ModifyPushConfig(ctx context.Context, req *pubsubpb.M } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription", url.QueryEscape(req.GetSubscription()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ModifyPushConfig[0:len(c.CallOptions.ModifyPushConfig):len(c.CallOptions.ModifyPushConfig)], opts...) + opts = append((*c.CallOptions).ModifyPushConfig[0:len((*c.CallOptions).ModifyPushConfig):len((*c.CallOptions).ModifyPushConfig)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.subscriberClient.ModifyPushConfig(ctx, req, settings.GRPC...) @@ -602,12 +775,7 @@ func (c *SubscriberClient) ModifyPushConfig(ctx context.Context, req *pubsubpb.M return err } -// GetSnapshot gets the configuration details of a snapshot. Snapshots are used in -// Seek (at https://cloud.google.com/pubsub/docs/replay-overview) -// operations, which allow you to manage message acknowledgments in bulk. That -// is, you can set the acknowledgment state of messages in an existing -// subscription to the state captured by a snapshot. -func (c *SubscriberClient) GetSnapshot(ctx context.Context, req *pubsubpb.GetSnapshotRequest, opts ...gax.CallOption) (*pubsubpb.Snapshot, error) { +func (c *subscriberGRPCClient) GetSnapshot(ctx context.Context, req *pubsubpb.GetSnapshotRequest, opts ...gax.CallOption) (*pubsubpb.Snapshot, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -615,7 +783,7 @@ func (c *SubscriberClient) GetSnapshot(ctx context.Context, req *pubsubpb.GetSna } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "snapshot", url.QueryEscape(req.GetSnapshot()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSnapshot[0:len(c.CallOptions.GetSnapshot):len(c.CallOptions.GetSnapshot)], opts...) + opts = append((*c.CallOptions).GetSnapshot[0:len((*c.CallOptions).GetSnapshot):len((*c.CallOptions).GetSnapshot)], opts...) var resp *pubsubpb.Snapshot err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -628,14 +796,10 @@ func (c *SubscriberClient) GetSnapshot(ctx context.Context, req *pubsubpb.GetSna return resp, nil } -// ListSnapshots lists the existing snapshots. Snapshots are used in Seek (at https://cloud.google.com/pubsub/docs/replay-overview) operations, which -// allow you to manage message acknowledgments in bulk. That is, you can set -// the acknowledgment state of messages in an existing subscription to the -// state captured by a snapshot. -func (c *SubscriberClient) ListSnapshots(ctx context.Context, req *pubsubpb.ListSnapshotsRequest, opts ...gax.CallOption) *SnapshotIterator { +func (c *subscriberGRPCClient) ListSnapshots(ctx context.Context, req *pubsubpb.ListSnapshotsRequest, opts ...gax.CallOption) *SnapshotIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project", url.QueryEscape(req.GetProject()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSnapshots[0:len(c.CallOptions.ListSnapshots):len(c.CallOptions.ListSnapshots)], opts...) + opts = append((*c.CallOptions).ListSnapshots[0:len((*c.CallOptions).ListSnapshots):len((*c.CallOptions).ListSnapshots)], opts...) it := &SnapshotIterator{} req = proto.Clone(req).(*pubsubpb.ListSnapshotsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*pubsubpb.Snapshot, string, error) { @@ -672,23 +836,7 @@ func (c *SubscriberClient) ListSnapshots(ctx context.Context, req *pubsubpb.List return it } -// CreateSnapshot creates a snapshot from the requested subscription. Snapshots are used in -// Seek (at https://cloud.google.com/pubsub/docs/replay-overview) operations, -// which allow you to manage message acknowledgments in bulk. That is, you can -// set the acknowledgment state of messages in an existing subscription to the -// state captured by a snapshot. -// If the snapshot already exists, returns ALREADY_EXISTS. -// If the requested subscription doesn’t exist, returns NOT_FOUND. -// If the backlog in the subscription is too old – and the resulting snapshot -// would expire in less than 1 hour – then FAILED_PRECONDITION is returned. -// See also the Snapshot.expire_time field. If the name is not provided in -// the request, the server will assign a random -// name for this snapshot on the same project as the subscription, conforming -// to the [resource name format] -// (https://cloud.google.com/pubsub/docs/admin#resource_names (at https://cloud.google.com/pubsub/docs/admin#resource_names)). The -// generated name is populated in the returned Snapshot object. Note that for -// REST API requests, you must specify a name in the request. -func (c *SubscriberClient) CreateSnapshot(ctx context.Context, req *pubsubpb.CreateSnapshotRequest, opts ...gax.CallOption) (*pubsubpb.Snapshot, error) { +func (c *subscriberGRPCClient) CreateSnapshot(ctx context.Context, req *pubsubpb.CreateSnapshotRequest, opts ...gax.CallOption) (*pubsubpb.Snapshot, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -696,7 +844,7 @@ func (c *SubscriberClient) CreateSnapshot(ctx context.Context, req *pubsubpb.Cre } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSnapshot[0:len(c.CallOptions.CreateSnapshot):len(c.CallOptions.CreateSnapshot)], opts...) + opts = append((*c.CallOptions).CreateSnapshot[0:len((*c.CallOptions).CreateSnapshot):len((*c.CallOptions).CreateSnapshot)], opts...) var resp *pubsubpb.Snapshot err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -709,13 +857,7 @@ func (c *SubscriberClient) CreateSnapshot(ctx context.Context, req *pubsubpb.Cre return resp, nil } -// UpdateSnapshot updates an existing snapshot. Snapshots are used in -// Seek (at https://cloud.google.com/pubsub/docs/replay-overview) -// operations, which allow -// you to manage message acknowledgments in bulk. That is, you can set the -// acknowledgment state of messages in an existing subscription to the state -// captured by a snapshot. -func (c *SubscriberClient) UpdateSnapshot(ctx context.Context, req *pubsubpb.UpdateSnapshotRequest, opts ...gax.CallOption) (*pubsubpb.Snapshot, error) { +func (c *subscriberGRPCClient) UpdateSnapshot(ctx context.Context, req *pubsubpb.UpdateSnapshotRequest, opts ...gax.CallOption) (*pubsubpb.Snapshot, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -723,7 +865,7 @@ func (c *SubscriberClient) UpdateSnapshot(ctx context.Context, req *pubsubpb.Upd } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "snapshot.name", url.QueryEscape(req.GetSnapshot().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSnapshot[0:len(c.CallOptions.UpdateSnapshot):len(c.CallOptions.UpdateSnapshot)], opts...) + opts = append((*c.CallOptions).UpdateSnapshot[0:len((*c.CallOptions).UpdateSnapshot):len((*c.CallOptions).UpdateSnapshot)], opts...) var resp *pubsubpb.Snapshot err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -736,16 +878,7 @@ func (c *SubscriberClient) UpdateSnapshot(ctx context.Context, req *pubsubpb.Upd return resp, nil } -// DeleteSnapshot removes an existing snapshot. Snapshots are used in [Seek] -// (https://cloud.google.com/pubsub/docs/replay-overview (at https://cloud.google.com/pubsub/docs/replay-overview)) operations, which -// allow you to manage message acknowledgments in bulk. That is, you can set -// the acknowledgment state of messages in an existing subscription to the -// state captured by a snapshot. -// When the snapshot is deleted, all messages retained in the snapshot -// are immediately dropped. After a snapshot is deleted, a new one may be -// created with the same name, but the new one has no association with the old -// snapshot or its subscription, unless the same subscription is specified. -func (c *SubscriberClient) DeleteSnapshot(ctx context.Context, req *pubsubpb.DeleteSnapshotRequest, opts ...gax.CallOption) error { +func (c *subscriberGRPCClient) DeleteSnapshot(ctx context.Context, req *pubsubpb.DeleteSnapshotRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -753,7 +886,7 @@ func (c *SubscriberClient) DeleteSnapshot(ctx context.Context, req *pubsubpb.Del } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "snapshot", url.QueryEscape(req.GetSnapshot()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteSnapshot[0:len(c.CallOptions.DeleteSnapshot):len(c.CallOptions.DeleteSnapshot)], opts...) + opts = append((*c.CallOptions).DeleteSnapshot[0:len((*c.CallOptions).DeleteSnapshot):len((*c.CallOptions).DeleteSnapshot)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.subscriberClient.DeleteSnapshot(ctx, req, settings.GRPC...) @@ -762,14 +895,7 @@ func (c *SubscriberClient) DeleteSnapshot(ctx context.Context, req *pubsubpb.Del return err } -// Seek seeks an existing subscription to a point in time or to a given snapshot, -// whichever is provided in the request. Snapshots are used in [Seek] -// (https://cloud.google.com/pubsub/docs/replay-overview (at https://cloud.google.com/pubsub/docs/replay-overview)) operations, which -// allow you to manage message acknowledgments in bulk. That is, you can set -// the acknowledgment state of messages in an existing subscription to the -// state captured by a snapshot. Note that both the subscription and the -// snapshot must be on the same topic. -func (c *SubscriberClient) Seek(ctx context.Context, req *pubsubpb.SeekRequest, opts ...gax.CallOption) (*pubsubpb.SeekResponse, error) { +func (c *subscriberGRPCClient) Seek(ctx context.Context, req *pubsubpb.SeekRequest, opts ...gax.CallOption) (*pubsubpb.SeekResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -777,7 +903,7 @@ func (c *SubscriberClient) Seek(ctx context.Context, req *pubsubpb.SeekRequest, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription", url.QueryEscape(req.GetSubscription()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.Seek[0:len(c.CallOptions.Seek):len(c.CallOptions.Seek)], opts...) + opts = append((*c.CallOptions).Seek[0:len((*c.CallOptions).Seek):len((*c.CallOptions).Seek)], opts...) var resp *pubsubpb.SeekResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/pubsub/apiv1/subscriber_client_example_test.go b/pubsub/apiv1/subscriber_client_example_test.go index cff234460534..878f14019f21 100644 --- a/pubsub/apiv1/subscriber_client_example_test.go +++ b/pubsub/apiv1/subscriber_client_example_test.go @@ -31,18 +31,19 @@ func ExampleNewSubscriberClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleSubscriberClient_CreateSubscription() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.Subscription{ // TODO: Fill request struct fields. @@ -56,13 +57,12 @@ func ExampleSubscriberClient_CreateSubscription() { } func ExampleSubscriberClient_GetSubscription() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.GetSubscriptionRequest{ // TODO: Fill request struct fields. @@ -76,13 +76,12 @@ func ExampleSubscriberClient_GetSubscription() { } func ExampleSubscriberClient_UpdateSubscription() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.UpdateSubscriptionRequest{ // TODO: Fill request struct fields. @@ -96,14 +95,12 @@ func ExampleSubscriberClient_UpdateSubscription() { } func ExampleSubscriberClient_ListSubscriptions() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ListSubscriptionsRequest{ // TODO: Fill request struct fields. @@ -128,6 +125,7 @@ func ExampleSubscriberClient_DeleteSubscription() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.DeleteSubscriptionRequest{ // TODO: Fill request struct fields. @@ -144,6 +142,7 @@ func ExampleSubscriberClient_ModifyAckDeadline() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ModifyAckDeadlineRequest{ // TODO: Fill request struct fields. @@ -160,6 +159,7 @@ func ExampleSubscriberClient_Acknowledge() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.AcknowledgeRequest{ // TODO: Fill request struct fields. @@ -171,13 +171,12 @@ func ExampleSubscriberClient_Acknowledge() { } func ExampleSubscriberClient_Pull() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.PullRequest{ // TODO: Fill request struct fields. @@ -191,13 +190,12 @@ func ExampleSubscriberClient_Pull() { } func ExampleSubscriberClient_StreamingPull() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.StreamingPull(ctx) if err != nil { // TODO: Handle error. @@ -232,6 +230,7 @@ func ExampleSubscriberClient_ModifyPushConfig() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ModifyPushConfigRequest{ // TODO: Fill request struct fields. @@ -243,13 +242,12 @@ func ExampleSubscriberClient_ModifyPushConfig() { } func ExampleSubscriberClient_GetSnapshot() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.GetSnapshotRequest{ // TODO: Fill request struct fields. @@ -263,14 +261,12 @@ func ExampleSubscriberClient_GetSnapshot() { } func ExampleSubscriberClient_ListSnapshots() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.ListSnapshotsRequest{ // TODO: Fill request struct fields. @@ -290,13 +286,12 @@ func ExampleSubscriberClient_ListSnapshots() { } func ExampleSubscriberClient_CreateSnapshot() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.CreateSnapshotRequest{ // TODO: Fill request struct fields. @@ -310,13 +305,12 @@ func ExampleSubscriberClient_CreateSnapshot() { } func ExampleSubscriberClient_UpdateSnapshot() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.UpdateSnapshotRequest{ // TODO: Fill request struct fields. @@ -335,6 +329,7 @@ func ExampleSubscriberClient_DeleteSnapshot() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.DeleteSnapshotRequest{ // TODO: Fill request struct fields. @@ -346,13 +341,12 @@ func ExampleSubscriberClient_DeleteSnapshot() { } func ExampleSubscriberClient_Seek() { - // import pubsubpb "google.golang.org/genproto/googleapis/pubsub/v1" - ctx := context.Background() c, err := pubsub.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsubpb.SeekRequest{ // TODO: Fill request struct fields. diff --git a/pubsub/go.mod b/pubsub/go.mod index 38b11c5b66ab..0ace4199342c 100644 --- a/pubsub/go.mod +++ b/pubsub/go.mod @@ -11,8 +11,8 @@ require ( golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c golang.org/x/sync v0.0.0-20210220032951-036812b2e83c golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba - google.golang.org/api v0.46.0 - google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a + google.golang.org/api v0.47.0 + google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d google.golang.org/grpc v1.37.1 google.golang.org/protobuf v1.26.0 ) diff --git a/pubsub/go.sum b/pubsub/go.sum index d4864f09eb9d..718ff884a7b4 100644 --- a/pubsub/go.sum +++ b/pubsub/go.sum @@ -144,6 +144,7 @@ github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -179,8 +180,9 @@ golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5 h1:2M3HP5CCK1Si9FQhwnzYhXdG6DXeebvUHFpre8QvbyI= golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 h1:VLliZ0d+/avPrXXH+OakdXhpJuEoBZuwh1m2j7U6Iug= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= @@ -190,8 +192,9 @@ golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.1 h1:Kvvh58BN8Y9/lBi7hTekvtMpm07eUZ0ck5pRHpsMWrY= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -225,6 +228,7 @@ golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420 h1:a8jGStKg0XqKDlKqjLrXn0ioF5MH36pT7Z0BRTqLhbk= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -238,7 +242,6 @@ golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210427180440-81ed05c6b58c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c h1:pkQiBZBvdos9qq4wBAHqlzuZHEXo07pqV06ef90u1WI= golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -288,9 +291,11 @@ golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210503080704-8803ae5d1324 h1:pAwJxDByZctfPwzlNGrDN2BQLsdPb9NkhoTJtUkAO28= -golang.org/x/sys v0.0.0-20210503080704-8803ae5d1324/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015 h1:hZR0X1kPW+nwyJ9xRxqZk1vx5RUObAPBdKVvXPDUH/E= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -351,8 +356,9 @@ golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.0 h1:po9/4sTYwZU9lPhi1tOrb4hCv3qrhiQ77LZfGa2OjwY= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.1 h1:wGiQel/hW0NnEkJUk8lbzkX2gFJU6PFxf1v5OlCfuOs= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -379,8 +385,8 @@ google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34q google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= -google.golang.org/api v0.46.0 h1:jkDWHOBIoNSD0OQpq4rtBVu+Rh325MPjXG1rakAp8JU= -google.golang.org/api v0.46.0/go.mod h1:ceL4oozhkAiTID8XMmJBsIxID/9wMXJVVFXPg4ylg3I= +google.golang.org/api v0.47.0 h1:sQLWZQvP6jPGIP4JGPkJu4zHswrv81iobiyszr3b/0I= +google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -428,9 +434,9 @@ google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= -google.golang.org/genproto v0.0.0-20210429181445-86c259c2b4ab/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= -google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a h1:VA0wtJaR+W1I11P2f535J7D/YxyvEFMTMvcmyeZ9FBE= -google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d h1:bRz6UmsZEz/CzoTjUDp4ZcdguhSWi6CyU299wMQBpZU= +google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= @@ -449,7 +455,6 @@ google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA5 google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.37.1 h1:ARnQJNWxGyYJpdf/JXscNlQr/uv607ZPU9Z7ogHi+iI= google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= diff --git a/pubsublite/apiv1/admin_client.go b/pubsublite/apiv1/admin_client.go index 92a65a34085a..e767d887bafa 100644 --- a/pubsublite/apiv1/admin_client.go +++ b/pubsublite/apiv1/admin_client.go @@ -53,7 +53,7 @@ type AdminCallOptions struct { DeleteSubscription []gax.CallOption } -func defaultAdminClientOptions() []option.ClientOption { +func defaultAdminGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("pubsublite.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("pubsublite.mtls.googleapis.com:443"), @@ -250,33 +250,147 @@ func defaultAdminCallOptions() *AdminCallOptions { } } +// internalAdminClient is an interface that defines the methods availaible from Pub/Sub Lite API. +type internalAdminClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateTopic(context.Context, *pubsublitepb.CreateTopicRequest, ...gax.CallOption) (*pubsublitepb.Topic, error) + GetTopic(context.Context, *pubsublitepb.GetTopicRequest, ...gax.CallOption) (*pubsublitepb.Topic, error) + GetTopicPartitions(context.Context, *pubsublitepb.GetTopicPartitionsRequest, ...gax.CallOption) (*pubsublitepb.TopicPartitions, error) + ListTopics(context.Context, *pubsublitepb.ListTopicsRequest, ...gax.CallOption) *TopicIterator + UpdateTopic(context.Context, *pubsublitepb.UpdateTopicRequest, ...gax.CallOption) (*pubsublitepb.Topic, error) + DeleteTopic(context.Context, *pubsublitepb.DeleteTopicRequest, ...gax.CallOption) error + ListTopicSubscriptions(context.Context, *pubsublitepb.ListTopicSubscriptionsRequest, ...gax.CallOption) *StringIterator + CreateSubscription(context.Context, *pubsublitepb.CreateSubscriptionRequest, ...gax.CallOption) (*pubsublitepb.Subscription, error) + GetSubscription(context.Context, *pubsublitepb.GetSubscriptionRequest, ...gax.CallOption) (*pubsublitepb.Subscription, error) + ListSubscriptions(context.Context, *pubsublitepb.ListSubscriptionsRequest, ...gax.CallOption) *SubscriptionIterator + UpdateSubscription(context.Context, *pubsublitepb.UpdateSubscriptionRequest, ...gax.CallOption) (*pubsublitepb.Subscription, error) + DeleteSubscription(context.Context, *pubsublitepb.DeleteSubscriptionRequest, ...gax.CallOption) error +} + // AdminClient is a client for interacting with Pub/Sub Lite API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The service that a client application uses to manage topics and +// subscriptions, such creating, listing, and deleting topics and subscriptions. type AdminClient struct { + // The internal transport-dependent client. + internalClient internalAdminClient + + // The call options for this service. + CallOptions *AdminCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *AdminClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *AdminClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *AdminClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateTopic creates a new topic. +func (c *AdminClient) CreateTopic(ctx context.Context, req *pubsublitepb.CreateTopicRequest, opts ...gax.CallOption) (*pubsublitepb.Topic, error) { + return c.internalClient.CreateTopic(ctx, req, opts...) +} + +// GetTopic returns the topic configuration. +func (c *AdminClient) GetTopic(ctx context.Context, req *pubsublitepb.GetTopicRequest, opts ...gax.CallOption) (*pubsublitepb.Topic, error) { + return c.internalClient.GetTopic(ctx, req, opts...) +} + +// GetTopicPartitions returns the partition information for the requested topic. +func (c *AdminClient) GetTopicPartitions(ctx context.Context, req *pubsublitepb.GetTopicPartitionsRequest, opts ...gax.CallOption) (*pubsublitepb.TopicPartitions, error) { + return c.internalClient.GetTopicPartitions(ctx, req, opts...) +} + +// ListTopics returns the list of topics for the given project. +func (c *AdminClient) ListTopics(ctx context.Context, req *pubsublitepb.ListTopicsRequest, opts ...gax.CallOption) *TopicIterator { + return c.internalClient.ListTopics(ctx, req, opts...) +} + +// UpdateTopic updates properties of the specified topic. +func (c *AdminClient) UpdateTopic(ctx context.Context, req *pubsublitepb.UpdateTopicRequest, opts ...gax.CallOption) (*pubsublitepb.Topic, error) { + return c.internalClient.UpdateTopic(ctx, req, opts...) +} + +// DeleteTopic deletes the specified topic. +func (c *AdminClient) DeleteTopic(ctx context.Context, req *pubsublitepb.DeleteTopicRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTopic(ctx, req, opts...) +} + +// ListTopicSubscriptions lists the subscriptions attached to the specified topic. +func (c *AdminClient) ListTopicSubscriptions(ctx context.Context, req *pubsublitepb.ListTopicSubscriptionsRequest, opts ...gax.CallOption) *StringIterator { + return c.internalClient.ListTopicSubscriptions(ctx, req, opts...) +} + +// CreateSubscription creates a new subscription. +func (c *AdminClient) CreateSubscription(ctx context.Context, req *pubsublitepb.CreateSubscriptionRequest, opts ...gax.CallOption) (*pubsublitepb.Subscription, error) { + return c.internalClient.CreateSubscription(ctx, req, opts...) +} + +// GetSubscription returns the subscription configuration. +func (c *AdminClient) GetSubscription(ctx context.Context, req *pubsublitepb.GetSubscriptionRequest, opts ...gax.CallOption) (*pubsublitepb.Subscription, error) { + return c.internalClient.GetSubscription(ctx, req, opts...) +} + +// ListSubscriptions returns the list of subscriptions for the given project. +func (c *AdminClient) ListSubscriptions(ctx context.Context, req *pubsublitepb.ListSubscriptionsRequest, opts ...gax.CallOption) *SubscriptionIterator { + return c.internalClient.ListSubscriptions(ctx, req, opts...) +} + +// UpdateSubscription updates properties of the specified subscription. +func (c *AdminClient) UpdateSubscription(ctx context.Context, req *pubsublitepb.UpdateSubscriptionRequest, opts ...gax.CallOption) (*pubsublitepb.Subscription, error) { + return c.internalClient.UpdateSubscription(ctx, req, opts...) +} + +// DeleteSubscription deletes the specified subscription. +func (c *AdminClient) DeleteSubscription(ctx context.Context, req *pubsublitepb.DeleteSubscriptionRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteSubscription(ctx, req, opts...) +} + +// adminGRPCClient is a client for interacting with Pub/Sub Lite API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type adminGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing AdminClient + CallOptions **AdminCallOptions + // The gRPC API client. adminClient pubsublitepb.AdminServiceClient - // The call options for this service. - CallOptions *AdminCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewAdminClient creates a new admin service client. +// NewAdminClient creates a new admin service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The service that a client application uses to manage topics and // subscriptions, such creating, listing, and deleting topics and subscriptions. func NewAdminClient(ctx context.Context, opts ...option.ClientOption) (*AdminClient, error) { - clientOpts := defaultAdminClientOptions() - + clientOpts := defaultAdminGRPCClientOptions() if newAdminClientHook != nil { hookOpts, err := newAdminClientHook(ctx, clientHookParams{}) if err != nil { @@ -294,42 +408,44 @@ func NewAdminClient(ctx context.Context, opts ...option.ClientOption) (*AdminCli if err != nil { return nil, err } - c := &AdminClient{ + client := AdminClient{CallOptions: defaultAdminCallOptions()} + + c := &adminGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultAdminCallOptions(), - - adminClient: pubsublitepb.NewAdminServiceClient(connPool), + adminClient: pubsublitepb.NewAdminServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *AdminClient) Connection() *grpc.ClientConn { +func (c *adminGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *AdminClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *AdminClient) setGoogleClientInfo(keyval ...string) { +func (c *adminGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateTopic creates a new topic. -func (c *AdminClient) CreateTopic(ctx context.Context, req *pubsublitepb.CreateTopicRequest, opts ...gax.CallOption) (*pubsublitepb.Topic, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *adminGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *adminGRPCClient) CreateTopic(ctx context.Context, req *pubsublitepb.CreateTopicRequest, opts ...gax.CallOption) (*pubsublitepb.Topic, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -337,7 +453,7 @@ func (c *AdminClient) CreateTopic(ctx context.Context, req *pubsublitepb.CreateT } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTopic[0:len(c.CallOptions.CreateTopic):len(c.CallOptions.CreateTopic)], opts...) + opts = append((*c.CallOptions).CreateTopic[0:len((*c.CallOptions).CreateTopic):len((*c.CallOptions).CreateTopic)], opts...) var resp *pubsublitepb.Topic err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -350,8 +466,7 @@ func (c *AdminClient) CreateTopic(ctx context.Context, req *pubsublitepb.CreateT return resp, nil } -// GetTopic returns the topic configuration. -func (c *AdminClient) GetTopic(ctx context.Context, req *pubsublitepb.GetTopicRequest, opts ...gax.CallOption) (*pubsublitepb.Topic, error) { +func (c *adminGRPCClient) GetTopic(ctx context.Context, req *pubsublitepb.GetTopicRequest, opts ...gax.CallOption) (*pubsublitepb.Topic, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -359,7 +474,7 @@ func (c *AdminClient) GetTopic(ctx context.Context, req *pubsublitepb.GetTopicRe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTopic[0:len(c.CallOptions.GetTopic):len(c.CallOptions.GetTopic)], opts...) + opts = append((*c.CallOptions).GetTopic[0:len((*c.CallOptions).GetTopic):len((*c.CallOptions).GetTopic)], opts...) var resp *pubsublitepb.Topic err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -372,8 +487,7 @@ func (c *AdminClient) GetTopic(ctx context.Context, req *pubsublitepb.GetTopicRe return resp, nil } -// GetTopicPartitions returns the partition information for the requested topic. -func (c *AdminClient) GetTopicPartitions(ctx context.Context, req *pubsublitepb.GetTopicPartitionsRequest, opts ...gax.CallOption) (*pubsublitepb.TopicPartitions, error) { +func (c *adminGRPCClient) GetTopicPartitions(ctx context.Context, req *pubsublitepb.GetTopicPartitionsRequest, opts ...gax.CallOption) (*pubsublitepb.TopicPartitions, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -381,7 +495,7 @@ func (c *AdminClient) GetTopicPartitions(ctx context.Context, req *pubsublitepb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTopicPartitions[0:len(c.CallOptions.GetTopicPartitions):len(c.CallOptions.GetTopicPartitions)], opts...) + opts = append((*c.CallOptions).GetTopicPartitions[0:len((*c.CallOptions).GetTopicPartitions):len((*c.CallOptions).GetTopicPartitions)], opts...) var resp *pubsublitepb.TopicPartitions err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -394,11 +508,10 @@ func (c *AdminClient) GetTopicPartitions(ctx context.Context, req *pubsublitepb. return resp, nil } -// ListTopics returns the list of topics for the given project. -func (c *AdminClient) ListTopics(ctx context.Context, req *pubsublitepb.ListTopicsRequest, opts ...gax.CallOption) *TopicIterator { +func (c *adminGRPCClient) ListTopics(ctx context.Context, req *pubsublitepb.ListTopicsRequest, opts ...gax.CallOption) *TopicIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTopics[0:len(c.CallOptions.ListTopics):len(c.CallOptions.ListTopics)], opts...) + opts = append((*c.CallOptions).ListTopics[0:len((*c.CallOptions).ListTopics):len((*c.CallOptions).ListTopics)], opts...) it := &TopicIterator{} req = proto.Clone(req).(*pubsublitepb.ListTopicsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*pubsublitepb.Topic, string, error) { @@ -435,8 +548,7 @@ func (c *AdminClient) ListTopics(ctx context.Context, req *pubsublitepb.ListTopi return it } -// UpdateTopic updates properties of the specified topic. -func (c *AdminClient) UpdateTopic(ctx context.Context, req *pubsublitepb.UpdateTopicRequest, opts ...gax.CallOption) (*pubsublitepb.Topic, error) { +func (c *adminGRPCClient) UpdateTopic(ctx context.Context, req *pubsublitepb.UpdateTopicRequest, opts ...gax.CallOption) (*pubsublitepb.Topic, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -444,7 +556,7 @@ func (c *AdminClient) UpdateTopic(ctx context.Context, req *pubsublitepb.UpdateT } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "topic.name", url.QueryEscape(req.GetTopic().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTopic[0:len(c.CallOptions.UpdateTopic):len(c.CallOptions.UpdateTopic)], opts...) + opts = append((*c.CallOptions).UpdateTopic[0:len((*c.CallOptions).UpdateTopic):len((*c.CallOptions).UpdateTopic)], opts...) var resp *pubsublitepb.Topic err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -457,8 +569,7 @@ func (c *AdminClient) UpdateTopic(ctx context.Context, req *pubsublitepb.UpdateT return resp, nil } -// DeleteTopic deletes the specified topic. -func (c *AdminClient) DeleteTopic(ctx context.Context, req *pubsublitepb.DeleteTopicRequest, opts ...gax.CallOption) error { +func (c *adminGRPCClient) DeleteTopic(ctx context.Context, req *pubsublitepb.DeleteTopicRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -466,7 +577,7 @@ func (c *AdminClient) DeleteTopic(ctx context.Context, req *pubsublitepb.DeleteT } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTopic[0:len(c.CallOptions.DeleteTopic):len(c.CallOptions.DeleteTopic)], opts...) + opts = append((*c.CallOptions).DeleteTopic[0:len((*c.CallOptions).DeleteTopic):len((*c.CallOptions).DeleteTopic)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.adminClient.DeleteTopic(ctx, req, settings.GRPC...) @@ -475,11 +586,10 @@ func (c *AdminClient) DeleteTopic(ctx context.Context, req *pubsublitepb.DeleteT return err } -// ListTopicSubscriptions lists the subscriptions attached to the specified topic. -func (c *AdminClient) ListTopicSubscriptions(ctx context.Context, req *pubsublitepb.ListTopicSubscriptionsRequest, opts ...gax.CallOption) *StringIterator { +func (c *adminGRPCClient) ListTopicSubscriptions(ctx context.Context, req *pubsublitepb.ListTopicSubscriptionsRequest, opts ...gax.CallOption) *StringIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTopicSubscriptions[0:len(c.CallOptions.ListTopicSubscriptions):len(c.CallOptions.ListTopicSubscriptions)], opts...) + opts = append((*c.CallOptions).ListTopicSubscriptions[0:len((*c.CallOptions).ListTopicSubscriptions):len((*c.CallOptions).ListTopicSubscriptions)], opts...) it := &StringIterator{} req = proto.Clone(req).(*pubsublitepb.ListTopicSubscriptionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]string, string, error) { @@ -516,8 +626,7 @@ func (c *AdminClient) ListTopicSubscriptions(ctx context.Context, req *pubsublit return it } -// CreateSubscription creates a new subscription. -func (c *AdminClient) CreateSubscription(ctx context.Context, req *pubsublitepb.CreateSubscriptionRequest, opts ...gax.CallOption) (*pubsublitepb.Subscription, error) { +func (c *adminGRPCClient) CreateSubscription(ctx context.Context, req *pubsublitepb.CreateSubscriptionRequest, opts ...gax.CallOption) (*pubsublitepb.Subscription, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -525,7 +634,7 @@ func (c *AdminClient) CreateSubscription(ctx context.Context, req *pubsublitepb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSubscription[0:len(c.CallOptions.CreateSubscription):len(c.CallOptions.CreateSubscription)], opts...) + opts = append((*c.CallOptions).CreateSubscription[0:len((*c.CallOptions).CreateSubscription):len((*c.CallOptions).CreateSubscription)], opts...) var resp *pubsublitepb.Subscription err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -538,8 +647,7 @@ func (c *AdminClient) CreateSubscription(ctx context.Context, req *pubsublitepb. return resp, nil } -// GetSubscription returns the subscription configuration. -func (c *AdminClient) GetSubscription(ctx context.Context, req *pubsublitepb.GetSubscriptionRequest, opts ...gax.CallOption) (*pubsublitepb.Subscription, error) { +func (c *adminGRPCClient) GetSubscription(ctx context.Context, req *pubsublitepb.GetSubscriptionRequest, opts ...gax.CallOption) (*pubsublitepb.Subscription, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -547,7 +655,7 @@ func (c *AdminClient) GetSubscription(ctx context.Context, req *pubsublitepb.Get } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSubscription[0:len(c.CallOptions.GetSubscription):len(c.CallOptions.GetSubscription)], opts...) + opts = append((*c.CallOptions).GetSubscription[0:len((*c.CallOptions).GetSubscription):len((*c.CallOptions).GetSubscription)], opts...) var resp *pubsublitepb.Subscription err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -560,11 +668,10 @@ func (c *AdminClient) GetSubscription(ctx context.Context, req *pubsublitepb.Get return resp, nil } -// ListSubscriptions returns the list of subscriptions for the given project. -func (c *AdminClient) ListSubscriptions(ctx context.Context, req *pubsublitepb.ListSubscriptionsRequest, opts ...gax.CallOption) *SubscriptionIterator { +func (c *adminGRPCClient) ListSubscriptions(ctx context.Context, req *pubsublitepb.ListSubscriptionsRequest, opts ...gax.CallOption) *SubscriptionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSubscriptions[0:len(c.CallOptions.ListSubscriptions):len(c.CallOptions.ListSubscriptions)], opts...) + opts = append((*c.CallOptions).ListSubscriptions[0:len((*c.CallOptions).ListSubscriptions):len((*c.CallOptions).ListSubscriptions)], opts...) it := &SubscriptionIterator{} req = proto.Clone(req).(*pubsublitepb.ListSubscriptionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*pubsublitepb.Subscription, string, error) { @@ -601,8 +708,7 @@ func (c *AdminClient) ListSubscriptions(ctx context.Context, req *pubsublitepb.L return it } -// UpdateSubscription updates properties of the specified subscription. -func (c *AdminClient) UpdateSubscription(ctx context.Context, req *pubsublitepb.UpdateSubscriptionRequest, opts ...gax.CallOption) (*pubsublitepb.Subscription, error) { +func (c *adminGRPCClient) UpdateSubscription(ctx context.Context, req *pubsublitepb.UpdateSubscriptionRequest, opts ...gax.CallOption) (*pubsublitepb.Subscription, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -610,7 +716,7 @@ func (c *AdminClient) UpdateSubscription(ctx context.Context, req *pubsublitepb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription.name", url.QueryEscape(req.GetSubscription().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSubscription[0:len(c.CallOptions.UpdateSubscription):len(c.CallOptions.UpdateSubscription)], opts...) + opts = append((*c.CallOptions).UpdateSubscription[0:len((*c.CallOptions).UpdateSubscription):len((*c.CallOptions).UpdateSubscription)], opts...) var resp *pubsublitepb.Subscription err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -623,8 +729,7 @@ func (c *AdminClient) UpdateSubscription(ctx context.Context, req *pubsublitepb. return resp, nil } -// DeleteSubscription deletes the specified subscription. -func (c *AdminClient) DeleteSubscription(ctx context.Context, req *pubsublitepb.DeleteSubscriptionRequest, opts ...gax.CallOption) error { +func (c *adminGRPCClient) DeleteSubscription(ctx context.Context, req *pubsublitepb.DeleteSubscriptionRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -632,7 +737,7 @@ func (c *AdminClient) DeleteSubscription(ctx context.Context, req *pubsublitepb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteSubscription[0:len(c.CallOptions.DeleteSubscription):len(c.CallOptions.DeleteSubscription)], opts...) + opts = append((*c.CallOptions).DeleteSubscription[0:len((*c.CallOptions).DeleteSubscription):len((*c.CallOptions).DeleteSubscription)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.adminClient.DeleteSubscription(ctx, req, settings.GRPC...) diff --git a/pubsublite/apiv1/admin_client_example_test.go b/pubsublite/apiv1/admin_client_example_test.go index fdff8222731e..a7d22f1014a8 100644 --- a/pubsublite/apiv1/admin_client_example_test.go +++ b/pubsublite/apiv1/admin_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewAdminClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleAdminClient_CreateTopic() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.CreateTopicRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleAdminClient_CreateTopic() { } func ExampleAdminClient_GetTopic() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.GetTopicRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleAdminClient_GetTopic() { } func ExampleAdminClient_GetTopicPartitions() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.GetTopicPartitionsRequest{ // TODO: Fill request struct fields. @@ -95,14 +94,12 @@ func ExampleAdminClient_GetTopicPartitions() { } func ExampleAdminClient_ListTopics() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.ListTopicsRequest{ // TODO: Fill request struct fields. @@ -122,13 +119,12 @@ func ExampleAdminClient_ListTopics() { } func ExampleAdminClient_UpdateTopic() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.UpdateTopicRequest{ // TODO: Fill request struct fields. @@ -147,6 +143,7 @@ func ExampleAdminClient_DeleteTopic() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.DeleteTopicRequest{ // TODO: Fill request struct fields. @@ -158,14 +155,12 @@ func ExampleAdminClient_DeleteTopic() { } func ExampleAdminClient_ListTopicSubscriptions() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.ListTopicSubscriptionsRequest{ // TODO: Fill request struct fields. @@ -185,13 +180,12 @@ func ExampleAdminClient_ListTopicSubscriptions() { } func ExampleAdminClient_CreateSubscription() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.CreateSubscriptionRequest{ // TODO: Fill request struct fields. @@ -205,13 +199,12 @@ func ExampleAdminClient_CreateSubscription() { } func ExampleAdminClient_GetSubscription() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.GetSubscriptionRequest{ // TODO: Fill request struct fields. @@ -225,14 +218,12 @@ func ExampleAdminClient_GetSubscription() { } func ExampleAdminClient_ListSubscriptions() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.ListSubscriptionsRequest{ // TODO: Fill request struct fields. @@ -252,13 +243,12 @@ func ExampleAdminClient_ListSubscriptions() { } func ExampleAdminClient_UpdateSubscription() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.UpdateSubscriptionRequest{ // TODO: Fill request struct fields. @@ -277,6 +267,7 @@ func ExampleAdminClient_DeleteSubscription() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.DeleteSubscriptionRequest{ // TODO: Fill request struct fields. diff --git a/pubsublite/apiv1/cursor_client.go b/pubsublite/apiv1/cursor_client.go index 2a8c7bf7614b..23fa0c4be383 100644 --- a/pubsublite/apiv1/cursor_client.go +++ b/pubsublite/apiv1/cursor_client.go @@ -44,7 +44,7 @@ type CursorCallOptions struct { ListPartitionCursors []gax.CallOption } -func defaultCursorClientOptions() []option.ClientOption { +func defaultCursorGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("pubsublite.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("pubsublite.mtls.googleapis.com:443"), @@ -92,34 +92,95 @@ func defaultCursorCallOptions() *CursorCallOptions { } } +// internalCursorClient is an interface that defines the methods availaible from Pub/Sub Lite API. +type internalCursorClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + StreamingCommitCursor(context.Context, ...gax.CallOption) (pubsublitepb.CursorService_StreamingCommitCursorClient, error) + CommitCursor(context.Context, *pubsublitepb.CommitCursorRequest, ...gax.CallOption) (*pubsublitepb.CommitCursorResponse, error) + ListPartitionCursors(context.Context, *pubsublitepb.ListPartitionCursorsRequest, ...gax.CallOption) *PartitionCursorIterator +} + // CursorClient is a client for interacting with Pub/Sub Lite API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The service that a subscriber client application uses to manage committed +// cursors while receiving messsages. A cursor represents a subscriber’s +// progress within a topic partition for a given subscription. type CursorClient struct { + // The internal transport-dependent client. + internalClient internalCursorClient + + // The call options for this service. + CallOptions *CursorCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CursorClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CursorClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CursorClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// StreamingCommitCursor establishes a stream with the server for managing committed cursors. +func (c *CursorClient) StreamingCommitCursor(ctx context.Context, opts ...gax.CallOption) (pubsublitepb.CursorService_StreamingCommitCursorClient, error) { + return c.internalClient.StreamingCommitCursor(ctx, opts...) +} + +// CommitCursor updates the committed cursor. +func (c *CursorClient) CommitCursor(ctx context.Context, req *pubsublitepb.CommitCursorRequest, opts ...gax.CallOption) (*pubsublitepb.CommitCursorResponse, error) { + return c.internalClient.CommitCursor(ctx, req, opts...) +} + +// ListPartitionCursors returns all committed cursor information for a subscription. +func (c *CursorClient) ListPartitionCursors(ctx context.Context, req *pubsublitepb.ListPartitionCursorsRequest, opts ...gax.CallOption) *PartitionCursorIterator { + return c.internalClient.ListPartitionCursors(ctx, req, opts...) +} + +// cursorGRPCClient is a client for interacting with Pub/Sub Lite API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cursorGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CursorClient + CallOptions **CursorCallOptions + // The gRPC API client. cursorClient pubsublitepb.CursorServiceClient - // The call options for this service. - CallOptions *CursorCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCursorClient creates a new cursor service client. +// NewCursorClient creates a new cursor service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The service that a subscriber client application uses to manage committed // cursors while receiving messsages. A cursor represents a subscriber’s // progress within a topic partition for a given subscription. func NewCursorClient(ctx context.Context, opts ...option.ClientOption) (*CursorClient, error) { - clientOpts := defaultCursorClientOptions() - + clientOpts := defaultCursorGRPCClientOptions() if newCursorClientHook != nil { hookOpts, err := newCursorClientHook(ctx, clientHookParams{}) if err != nil { @@ -137,45 +198,47 @@ func NewCursorClient(ctx context.Context, opts ...option.ClientOption) (*CursorC if err != nil { return nil, err } - c := &CursorClient{ + client := CursorClient{CallOptions: defaultCursorCallOptions()} + + c := &cursorGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCursorCallOptions(), - - cursorClient: pubsublitepb.NewCursorServiceClient(connPool), + cursorClient: pubsublitepb.NewCursorServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CursorClient) Connection() *grpc.ClientConn { +func (c *cursorGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CursorClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CursorClient) setGoogleClientInfo(keyval ...string) { +func (c *cursorGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// StreamingCommitCursor establishes a stream with the server for managing committed cursors. -func (c *CursorClient) StreamingCommitCursor(ctx context.Context, opts ...gax.CallOption) (pubsublitepb.CursorService_StreamingCommitCursorClient, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cursorGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *cursorGRPCClient) StreamingCommitCursor(ctx context.Context, opts ...gax.CallOption) (pubsublitepb.CursorService_StreamingCommitCursorClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.StreamingCommitCursor[0:len(c.CallOptions.StreamingCommitCursor):len(c.CallOptions.StreamingCommitCursor)], opts...) var resp pubsublitepb.CursorService_StreamingCommitCursorClient + opts = append((*c.CallOptions).StreamingCommitCursor[0:len((*c.CallOptions).StreamingCommitCursor):len((*c.CallOptions).StreamingCommitCursor)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.cursorClient.StreamingCommitCursor(ctx, settings.GRPC...) @@ -187,8 +250,7 @@ func (c *CursorClient) StreamingCommitCursor(ctx context.Context, opts ...gax.Ca return resp, nil } -// CommitCursor updates the committed cursor. -func (c *CursorClient) CommitCursor(ctx context.Context, req *pubsublitepb.CommitCursorRequest, opts ...gax.CallOption) (*pubsublitepb.CommitCursorResponse, error) { +func (c *cursorGRPCClient) CommitCursor(ctx context.Context, req *pubsublitepb.CommitCursorRequest, opts ...gax.CallOption) (*pubsublitepb.CommitCursorResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -196,7 +258,7 @@ func (c *CursorClient) CommitCursor(ctx context.Context, req *pubsublitepb.Commi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "subscription", url.QueryEscape(req.GetSubscription()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CommitCursor[0:len(c.CallOptions.CommitCursor):len(c.CallOptions.CommitCursor)], opts...) + opts = append((*c.CallOptions).CommitCursor[0:len((*c.CallOptions).CommitCursor):len((*c.CallOptions).CommitCursor)], opts...) var resp *pubsublitepb.CommitCursorResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -209,11 +271,10 @@ func (c *CursorClient) CommitCursor(ctx context.Context, req *pubsublitepb.Commi return resp, nil } -// ListPartitionCursors returns all committed cursor information for a subscription. -func (c *CursorClient) ListPartitionCursors(ctx context.Context, req *pubsublitepb.ListPartitionCursorsRequest, opts ...gax.CallOption) *PartitionCursorIterator { +func (c *cursorGRPCClient) ListPartitionCursors(ctx context.Context, req *pubsublitepb.ListPartitionCursorsRequest, opts ...gax.CallOption) *PartitionCursorIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListPartitionCursors[0:len(c.CallOptions.ListPartitionCursors):len(c.CallOptions.ListPartitionCursors)], opts...) + opts = append((*c.CallOptions).ListPartitionCursors[0:len((*c.CallOptions).ListPartitionCursors):len((*c.CallOptions).ListPartitionCursors)], opts...) it := &PartitionCursorIterator{} req = proto.Clone(req).(*pubsublitepb.ListPartitionCursorsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*pubsublitepb.PartitionCursor, string, error) { diff --git a/pubsublite/apiv1/cursor_client_example_test.go b/pubsublite/apiv1/cursor_client_example_test.go index 6e2f0706b704..41ac7d4cb328 100644 --- a/pubsublite/apiv1/cursor_client_example_test.go +++ b/pubsublite/apiv1/cursor_client_example_test.go @@ -31,18 +31,19 @@ func ExampleNewCursorClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCursorClient_StreamingCommitCursor() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewCursorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.StreamingCommitCursor(ctx) if err != nil { // TODO: Handle error. @@ -72,13 +73,12 @@ func ExampleCursorClient_StreamingCommitCursor() { } func ExampleCursorClient_CommitCursor() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewCursorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.CommitCursorRequest{ // TODO: Fill request struct fields. @@ -92,14 +92,12 @@ func ExampleCursorClient_CommitCursor() { } func ExampleCursorClient_ListPartitionCursors() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := pubsublite.NewCursorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.ListPartitionCursorsRequest{ // TODO: Fill request struct fields. diff --git a/pubsublite/apiv1/doc.go b/pubsublite/apiv1/doc.go index 20c0e4401905..b2e0d3b29efe 100644 --- a/pubsublite/apiv1/doc.go +++ b/pubsublite/apiv1/doc.go @@ -17,6 +17,8 @@ // Package pubsublite is an auto-generated package for the // Pub/Sub Lite API. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -26,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package pubsublite // import "cloud.google.com/go/pubsublite/apiv1" import ( @@ -46,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/pubsublite/apiv1/partition_assignment_client.go b/pubsublite/apiv1/partition_assignment_client.go index ac3f7ea2d3ac..6a8ae9de6f83 100644 --- a/pubsublite/apiv1/partition_assignment_client.go +++ b/pubsublite/apiv1/partition_assignment_client.go @@ -36,7 +36,7 @@ type PartitionAssignmentCallOptions struct { AssignPartitions []gax.CallOption } -func defaultPartitionAssignmentClientOptions() []option.ClientOption { +func defaultPartitionAssignmentGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("pubsublite.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("pubsublite.mtls.googleapis.com:443"), @@ -54,33 +54,87 @@ func defaultPartitionAssignmentCallOptions() *PartitionAssignmentCallOptions { } } +// internalPartitionAssignmentClient is an interface that defines the methods availaible from Pub/Sub Lite API. +type internalPartitionAssignmentClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + AssignPartitions(context.Context, ...gax.CallOption) (pubsublitepb.PartitionAssignmentService_AssignPartitionsClient, error) +} + // PartitionAssignmentClient is a client for interacting with Pub/Sub Lite API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The service that a subscriber client application uses to determine which +// partitions it should connect to. type PartitionAssignmentClient struct { + // The internal transport-dependent client. + internalClient internalPartitionAssignmentClient + + // The call options for this service. + CallOptions *PartitionAssignmentCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *PartitionAssignmentClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *PartitionAssignmentClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *PartitionAssignmentClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// AssignPartitions assign partitions for this client to handle for the specified subscription. +// +// The client must send an InitialPartitionAssignmentRequest first. +// The server will then send at most one unacknowledged PartitionAssignment +// outstanding on the stream at a time. +// The client should send a PartitionAssignmentAck after updating the +// partitions it is connected to to reflect the new assignment. +func (c *PartitionAssignmentClient) AssignPartitions(ctx context.Context, opts ...gax.CallOption) (pubsublitepb.PartitionAssignmentService_AssignPartitionsClient, error) { + return c.internalClient.AssignPartitions(ctx, opts...) +} + +// partitionAssignmentGRPCClient is a client for interacting with Pub/Sub Lite API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type partitionAssignmentGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing PartitionAssignmentClient + CallOptions **PartitionAssignmentCallOptions + // The gRPC API client. partitionAssignmentClient pubsublitepb.PartitionAssignmentServiceClient - // The call options for this service. - CallOptions *PartitionAssignmentCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewPartitionAssignmentClient creates a new partition assignment service client. +// NewPartitionAssignmentClient creates a new partition assignment service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The service that a subscriber client application uses to determine which // partitions it should connect to. func NewPartitionAssignmentClient(ctx context.Context, opts ...option.ClientOption) (*PartitionAssignmentClient, error) { - clientOpts := defaultPartitionAssignmentClientOptions() - + clientOpts := defaultPartitionAssignmentGRPCClientOptions() if newPartitionAssignmentClientHook != nil { hookOpts, err := newPartitionAssignmentClientHook(ctx, clientHookParams{}) if err != nil { @@ -98,51 +152,47 @@ func NewPartitionAssignmentClient(ctx context.Context, opts ...option.ClientOpti if err != nil { return nil, err } - c := &PartitionAssignmentClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultPartitionAssignmentCallOptions(), + client := PartitionAssignmentClient{CallOptions: defaultPartitionAssignmentCallOptions()} + c := &partitionAssignmentGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, partitionAssignmentClient: pubsublitepb.NewPartitionAssignmentServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *PartitionAssignmentClient) Connection() *grpc.ClientConn { +func (c *partitionAssignmentGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *PartitionAssignmentClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *PartitionAssignmentClient) setGoogleClientInfo(keyval ...string) { +func (c *partitionAssignmentGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// AssignPartitions assign partitions for this client to handle for the specified subscription. -// -// The client must send an InitialPartitionAssignmentRequest first. -// The server will then send at most one unacknowledged PartitionAssignment -// outstanding on the stream at a time. -// The client should send a PartitionAssignmentAck after updating the -// partitions it is connected to to reflect the new assignment. -func (c *PartitionAssignmentClient) AssignPartitions(ctx context.Context, opts ...gax.CallOption) (pubsublitepb.PartitionAssignmentService_AssignPartitionsClient, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *partitionAssignmentGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *partitionAssignmentGRPCClient) AssignPartitions(ctx context.Context, opts ...gax.CallOption) (pubsublitepb.PartitionAssignmentService_AssignPartitionsClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.AssignPartitions[0:len(c.CallOptions.AssignPartitions):len(c.CallOptions.AssignPartitions)], opts...) var resp pubsublitepb.PartitionAssignmentService_AssignPartitionsClient + opts = append((*c.CallOptions).AssignPartitions[0:len((*c.CallOptions).AssignPartitions):len((*c.CallOptions).AssignPartitions)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.partitionAssignmentClient.AssignPartitions(ctx, settings.GRPC...) diff --git a/pubsublite/apiv1/partition_assignment_client_example_test.go b/pubsublite/apiv1/partition_assignment_client_example_test.go index 34d6e7658ce9..fa3b9ec86f16 100644 --- a/pubsublite/apiv1/partition_assignment_client_example_test.go +++ b/pubsublite/apiv1/partition_assignment_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewPartitionAssignmentClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExamplePartitionAssignmentClient_AssignPartitions() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewPartitionAssignmentClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.AssignPartitions(ctx) if err != nil { // TODO: Handle error. diff --git a/pubsublite/apiv1/publisher_client.go b/pubsublite/apiv1/publisher_client.go index 8844c4685463..bb984425e9e1 100644 --- a/pubsublite/apiv1/publisher_client.go +++ b/pubsublite/apiv1/publisher_client.go @@ -36,7 +36,7 @@ type PublisherCallOptions struct { Publish []gax.CallOption } -func defaultPublisherClientOptions() []option.ClientOption { +func defaultPublisherGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("pubsublite.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("pubsublite.mtls.googleapis.com:443"), @@ -54,35 +54,91 @@ func defaultPublisherCallOptions() *PublisherCallOptions { } } +// internalPublisherClient is an interface that defines the methods availaible from Pub/Sub Lite API. +type internalPublisherClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + Publish(context.Context, ...gax.CallOption) (pubsublitepb.PublisherService_PublishClient, error) +} + // PublisherClient is a client for interacting with Pub/Sub Lite API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The service that a publisher client application uses to publish messages to +// topics. Published messages are retained by the service for the duration of +// the retention period configured for the respective topic, and are delivered +// to subscriber clients upon request (via the SubscriberService). type PublisherClient struct { + // The internal transport-dependent client. + internalClient internalPublisherClient + + // The call options for this service. + CallOptions *PublisherCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *PublisherClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *PublisherClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *PublisherClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// Publish establishes a stream with the server for publishing messages. Once the +// stream is initialized, the client publishes messages by sending publish +// requests on the stream. The server responds with a PublishResponse for each +// PublishRequest sent by the client, in the same order that the requests +// were sent. Note that multiple PublishRequests can be in flight +// simultaneously, but they will be processed by the server in the order that +// they are sent by the client on a given stream. +func (c *PublisherClient) Publish(ctx context.Context, opts ...gax.CallOption) (pubsublitepb.PublisherService_PublishClient, error) { + return c.internalClient.Publish(ctx, opts...) +} + +// publisherGRPCClient is a client for interacting with Pub/Sub Lite API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type publisherGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing PublisherClient + CallOptions **PublisherCallOptions + // The gRPC API client. publisherClient pubsublitepb.PublisherServiceClient - // The call options for this service. - CallOptions *PublisherCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewPublisherClient creates a new publisher service client. +// NewPublisherClient creates a new publisher service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The service that a publisher client application uses to publish messages to // topics. Published messages are retained by the service for the duration of // the retention period configured for the respective topic, and are delivered // to subscriber clients upon request (via the SubscriberService). func NewPublisherClient(ctx context.Context, opts ...option.ClientOption) (*PublisherClient, error) { - clientOpts := defaultPublisherClientOptions() - + clientOpts := defaultPublisherGRPCClientOptions() if newPublisherClientHook != nil { hookOpts, err := newPublisherClientHook(ctx, clientHookParams{}) if err != nil { @@ -100,51 +156,47 @@ func NewPublisherClient(ctx context.Context, opts ...option.ClientOption) (*Publ if err != nil { return nil, err } - c := &PublisherClient{ + client := PublisherClient{CallOptions: defaultPublisherCallOptions()} + + c := &publisherGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultPublisherCallOptions(), - - publisherClient: pubsublitepb.NewPublisherServiceClient(connPool), + publisherClient: pubsublitepb.NewPublisherServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *PublisherClient) Connection() *grpc.ClientConn { +func (c *publisherGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *PublisherClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *PublisherClient) setGoogleClientInfo(keyval ...string) { +func (c *publisherGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// Publish establishes a stream with the server for publishing messages. Once the -// stream is initialized, the client publishes messages by sending publish -// requests on the stream. The server responds with a PublishResponse for each -// PublishRequest sent by the client, in the same order that the requests -// were sent. Note that multiple PublishRequests can be in flight -// simultaneously, but they will be processed by the server in the order that -// they are sent by the client on a given stream. -func (c *PublisherClient) Publish(ctx context.Context, opts ...gax.CallOption) (pubsublitepb.PublisherService_PublishClient, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *publisherGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *publisherGRPCClient) Publish(ctx context.Context, opts ...gax.CallOption) (pubsublitepb.PublisherService_PublishClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.Publish[0:len(c.CallOptions.Publish):len(c.CallOptions.Publish)], opts...) var resp pubsublitepb.PublisherService_PublishClient + opts = append((*c.CallOptions).Publish[0:len((*c.CallOptions).Publish):len((*c.CallOptions).Publish)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.publisherClient.Publish(ctx, settings.GRPC...) diff --git a/pubsublite/apiv1/publisher_client_example_test.go b/pubsublite/apiv1/publisher_client_example_test.go index 30ce5549aac3..669ec040f70d 100644 --- a/pubsublite/apiv1/publisher_client_example_test.go +++ b/pubsublite/apiv1/publisher_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewPublisherClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExamplePublisherClient_Publish() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewPublisherClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.Publish(ctx) if err != nil { // TODO: Handle error. diff --git a/pubsublite/apiv1/subscriber_client.go b/pubsublite/apiv1/subscriber_client.go index 2c23f48c1cf7..7c181bd25465 100644 --- a/pubsublite/apiv1/subscriber_client.go +++ b/pubsublite/apiv1/subscriber_client.go @@ -36,7 +36,7 @@ type SubscriberCallOptions struct { Subscribe []gax.CallOption } -func defaultSubscriberClientOptions() []option.ClientOption { +func defaultSubscriberGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("pubsublite.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("pubsublite.mtls.googleapis.com:443"), @@ -54,33 +54,81 @@ func defaultSubscriberCallOptions() *SubscriberCallOptions { } } +// internalSubscriberClient is an interface that defines the methods availaible from Pub/Sub Lite API. +type internalSubscriberClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + Subscribe(context.Context, ...gax.CallOption) (pubsublitepb.SubscriberService_SubscribeClient, error) +} + // SubscriberClient is a client for interacting with Pub/Sub Lite API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The service that a subscriber client application uses to receive messages +// from subscriptions. type SubscriberClient struct { + // The internal transport-dependent client. + internalClient internalSubscriberClient + + // The call options for this service. + CallOptions *SubscriberCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *SubscriberClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *SubscriberClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *SubscriberClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// Subscribe establishes a stream with the server for receiving messages. +func (c *SubscriberClient) Subscribe(ctx context.Context, opts ...gax.CallOption) (pubsublitepb.SubscriberService_SubscribeClient, error) { + return c.internalClient.Subscribe(ctx, opts...) +} + +// subscriberGRPCClient is a client for interacting with Pub/Sub Lite API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type subscriberGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing SubscriberClient + CallOptions **SubscriberCallOptions + // The gRPC API client. subscriberClient pubsublitepb.SubscriberServiceClient - // The call options for this service. - CallOptions *SubscriberCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewSubscriberClient creates a new subscriber service client. +// NewSubscriberClient creates a new subscriber service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The service that a subscriber client application uses to receive messages // from subscriptions. func NewSubscriberClient(ctx context.Context, opts ...option.ClientOption) (*SubscriberClient, error) { - clientOpts := defaultSubscriberClientOptions() - + clientOpts := defaultSubscriberGRPCClientOptions() if newSubscriberClientHook != nil { hookOpts, err := newSubscriberClientHook(ctx, clientHookParams{}) if err != nil { @@ -98,45 +146,47 @@ func NewSubscriberClient(ctx context.Context, opts ...option.ClientOption) (*Sub if err != nil { return nil, err } - c := &SubscriberClient{ + client := SubscriberClient{CallOptions: defaultSubscriberCallOptions()} + + c := &subscriberGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultSubscriberCallOptions(), - subscriberClient: pubsublitepb.NewSubscriberServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *SubscriberClient) Connection() *grpc.ClientConn { +func (c *subscriberGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *SubscriberClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *SubscriberClient) setGoogleClientInfo(keyval ...string) { +func (c *subscriberGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// Subscribe establishes a stream with the server for receiving messages. -func (c *SubscriberClient) Subscribe(ctx context.Context, opts ...gax.CallOption) (pubsublitepb.SubscriberService_SubscribeClient, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *subscriberGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *subscriberGRPCClient) Subscribe(ctx context.Context, opts ...gax.CallOption) (pubsublitepb.SubscriberService_SubscribeClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.Subscribe[0:len(c.CallOptions.Subscribe):len(c.CallOptions.Subscribe)], opts...) var resp pubsublitepb.SubscriberService_SubscribeClient + opts = append((*c.CallOptions).Subscribe[0:len((*c.CallOptions).Subscribe):len((*c.CallOptions).Subscribe)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.subscriberClient.Subscribe(ctx, settings.GRPC...) diff --git a/pubsublite/apiv1/subscriber_client_example_test.go b/pubsublite/apiv1/subscriber_client_example_test.go index aa2385d140f9..d0867715c976 100644 --- a/pubsublite/apiv1/subscriber_client_example_test.go +++ b/pubsublite/apiv1/subscriber_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewSubscriberClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleSubscriberClient_Subscribe() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewSubscriberClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.Subscribe(ctx) if err != nil { // TODO: Handle error. diff --git a/pubsublite/apiv1/topic_stats_client.go b/pubsublite/apiv1/topic_stats_client.go index dd44063cdd4f..811288f13fa5 100644 --- a/pubsublite/apiv1/topic_stats_client.go +++ b/pubsublite/apiv1/topic_stats_client.go @@ -42,7 +42,7 @@ type TopicStatsCallOptions struct { ComputeTimeCursor []gax.CallOption } -func defaultTopicStatsClientOptions() []option.ClientOption { +func defaultTopicStatsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("pubsublite.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("pubsublite.mtls.googleapis.com:443"), @@ -104,32 +104,98 @@ func defaultTopicStatsCallOptions() *TopicStatsCallOptions { } } +// internalTopicStatsClient is an interface that defines the methods availaible from Pub/Sub Lite API. +type internalTopicStatsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ComputeMessageStats(context.Context, *pubsublitepb.ComputeMessageStatsRequest, ...gax.CallOption) (*pubsublitepb.ComputeMessageStatsResponse, error) + ComputeHeadCursor(context.Context, *pubsublitepb.ComputeHeadCursorRequest, ...gax.CallOption) (*pubsublitepb.ComputeHeadCursorResponse, error) + ComputeTimeCursor(context.Context, *pubsublitepb.ComputeTimeCursorRequest, ...gax.CallOption) (*pubsublitepb.ComputeTimeCursorResponse, error) +} + // TopicStatsClient is a client for interacting with Pub/Sub Lite API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// This service allows users to get stats about messages in their topic. type TopicStatsClient struct { + // The internal transport-dependent client. + internalClient internalTopicStatsClient + + // The call options for this service. + CallOptions *TopicStatsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *TopicStatsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *TopicStatsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *TopicStatsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ComputeMessageStats compute statistics about a range of messages in a given topic and +// partition. +func (c *TopicStatsClient) ComputeMessageStats(ctx context.Context, req *pubsublitepb.ComputeMessageStatsRequest, opts ...gax.CallOption) (*pubsublitepb.ComputeMessageStatsResponse, error) { + return c.internalClient.ComputeMessageStats(ctx, req, opts...) +} + +// ComputeHeadCursor compute the head cursor for the partition. +// The head cursor’s offset is guaranteed to be less than or equal to all +// messages which have not yet been acknowledged as published, and +// greater than the offset of any message whose publish has already +// been acknowledged. It is zero if there have never been messages in the +// partition. +func (c *TopicStatsClient) ComputeHeadCursor(ctx context.Context, req *pubsublitepb.ComputeHeadCursorRequest, opts ...gax.CallOption) (*pubsublitepb.ComputeHeadCursorResponse, error) { + return c.internalClient.ComputeHeadCursor(ctx, req, opts...) +} + +// ComputeTimeCursor compute the corresponding cursor for a publish or event time in a topic +// partition. +func (c *TopicStatsClient) ComputeTimeCursor(ctx context.Context, req *pubsublitepb.ComputeTimeCursorRequest, opts ...gax.CallOption) (*pubsublitepb.ComputeTimeCursorResponse, error) { + return c.internalClient.ComputeTimeCursor(ctx, req, opts...) +} + +// topicStatsGRPCClient is a client for interacting with Pub/Sub Lite API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type topicStatsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing TopicStatsClient + CallOptions **TopicStatsCallOptions + // The gRPC API client. topicStatsClient pubsublitepb.TopicStatsServiceClient - // The call options for this service. - CallOptions *TopicStatsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewTopicStatsClient creates a new topic stats service client. +// NewTopicStatsClient creates a new topic stats service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // This service allows users to get stats about messages in their topic. func NewTopicStatsClient(ctx context.Context, opts ...option.ClientOption) (*TopicStatsClient, error) { - clientOpts := defaultTopicStatsClientOptions() - + clientOpts := defaultTopicStatsGRPCClientOptions() if newTopicStatsClientHook != nil { hookOpts, err := newTopicStatsClientHook(ctx, clientHookParams{}) if err != nil { @@ -147,43 +213,44 @@ func NewTopicStatsClient(ctx context.Context, opts ...option.ClientOption) (*Top if err != nil { return nil, err } - c := &TopicStatsClient{ + client := TopicStatsClient{CallOptions: defaultTopicStatsCallOptions()} + + c := &topicStatsGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultTopicStatsCallOptions(), - topicStatsClient: pubsublitepb.NewTopicStatsServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *TopicStatsClient) Connection() *grpc.ClientConn { +func (c *topicStatsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *TopicStatsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *TopicStatsClient) setGoogleClientInfo(keyval ...string) { +func (c *topicStatsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ComputeMessageStats compute statistics about a range of messages in a given topic and -// partition. -func (c *TopicStatsClient) ComputeMessageStats(ctx context.Context, req *pubsublitepb.ComputeMessageStatsRequest, opts ...gax.CallOption) (*pubsublitepb.ComputeMessageStatsResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *topicStatsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *topicStatsGRPCClient) ComputeMessageStats(ctx context.Context, req *pubsublitepb.ComputeMessageStatsRequest, opts ...gax.CallOption) (*pubsublitepb.ComputeMessageStatsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -191,7 +258,7 @@ func (c *TopicStatsClient) ComputeMessageStats(ctx context.Context, req *pubsubl } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "topic", url.QueryEscape(req.GetTopic()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ComputeMessageStats[0:len(c.CallOptions.ComputeMessageStats):len(c.CallOptions.ComputeMessageStats)], opts...) + opts = append((*c.CallOptions).ComputeMessageStats[0:len((*c.CallOptions).ComputeMessageStats):len((*c.CallOptions).ComputeMessageStats)], opts...) var resp *pubsublitepb.ComputeMessageStatsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -204,13 +271,7 @@ func (c *TopicStatsClient) ComputeMessageStats(ctx context.Context, req *pubsubl return resp, nil } -// ComputeHeadCursor compute the head cursor for the partition. -// The head cursor’s offset is guaranteed to be less than or equal to all -// messages which have not yet been acknowledged as published, and -// greater than the offset of any message whose publish has already -// been acknowledged. It is zero if there have never been messages in the -// partition. -func (c *TopicStatsClient) ComputeHeadCursor(ctx context.Context, req *pubsublitepb.ComputeHeadCursorRequest, opts ...gax.CallOption) (*pubsublitepb.ComputeHeadCursorResponse, error) { +func (c *topicStatsGRPCClient) ComputeHeadCursor(ctx context.Context, req *pubsublitepb.ComputeHeadCursorRequest, opts ...gax.CallOption) (*pubsublitepb.ComputeHeadCursorResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -218,7 +279,7 @@ func (c *TopicStatsClient) ComputeHeadCursor(ctx context.Context, req *pubsublit } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "topic", url.QueryEscape(req.GetTopic()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ComputeHeadCursor[0:len(c.CallOptions.ComputeHeadCursor):len(c.CallOptions.ComputeHeadCursor)], opts...) + opts = append((*c.CallOptions).ComputeHeadCursor[0:len((*c.CallOptions).ComputeHeadCursor):len((*c.CallOptions).ComputeHeadCursor)], opts...) var resp *pubsublitepb.ComputeHeadCursorResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -231,9 +292,7 @@ func (c *TopicStatsClient) ComputeHeadCursor(ctx context.Context, req *pubsublit return resp, nil } -// ComputeTimeCursor compute the corresponding cursor for a publish or event time in a topic -// partition. -func (c *TopicStatsClient) ComputeTimeCursor(ctx context.Context, req *pubsublitepb.ComputeTimeCursorRequest, opts ...gax.CallOption) (*pubsublitepb.ComputeTimeCursorResponse, error) { +func (c *topicStatsGRPCClient) ComputeTimeCursor(ctx context.Context, req *pubsublitepb.ComputeTimeCursorRequest, opts ...gax.CallOption) (*pubsublitepb.ComputeTimeCursorResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -241,7 +300,7 @@ func (c *TopicStatsClient) ComputeTimeCursor(ctx context.Context, req *pubsublit } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "topic", url.QueryEscape(req.GetTopic()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ComputeTimeCursor[0:len(c.CallOptions.ComputeTimeCursor):len(c.CallOptions.ComputeTimeCursor)], opts...) + opts = append((*c.CallOptions).ComputeTimeCursor[0:len((*c.CallOptions).ComputeTimeCursor):len((*c.CallOptions).ComputeTimeCursor)], opts...) var resp *pubsublitepb.ComputeTimeCursorResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/pubsublite/apiv1/topic_stats_client_example_test.go b/pubsublite/apiv1/topic_stats_client_example_test.go index 8efe686bb709..2a71ed5e0fa8 100644 --- a/pubsublite/apiv1/topic_stats_client_example_test.go +++ b/pubsublite/apiv1/topic_stats_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewTopicStatsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleTopicStatsClient_ComputeMessageStats() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewTopicStatsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.ComputeMessageStatsRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleTopicStatsClient_ComputeMessageStats() { } func ExampleTopicStatsClient_ComputeHeadCursor() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewTopicStatsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.ComputeHeadCursorRequest{ // TODO: Fill request struct fields. @@ -74,13 +74,12 @@ func ExampleTopicStatsClient_ComputeHeadCursor() { } func ExampleTopicStatsClient_ComputeTimeCursor() { - // import pubsublitepb "google.golang.org/genproto/googleapis/cloud/pubsublite/v1" - ctx := context.Background() c, err := pubsublite.NewTopicStatsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &pubsublitepb.ComputeTimeCursorRequest{ // TODO: Fill request struct fields. diff --git a/pubsublite/go.mod b/pubsublite/go.mod index db83757e3486..e49cb66d4aeb 100644 --- a/pubsublite/go.mod +++ b/pubsublite/go.mod @@ -11,8 +11,8 @@ require ( github.com/googleapis/gax-go/v2 v2.0.5 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 - google.golang.org/api v0.46.0 - google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a + google.golang.org/api v0.47.0 + google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d google.golang.org/grpc v1.37.1 google.golang.org/protobuf v1.26.0 ) diff --git a/pubsublite/go.sum b/pubsublite/go.sum index 1ac4433c3dff..6c2bc7132c78 100644 --- a/pubsublite/go.sum +++ b/pubsublite/go.sum @@ -150,6 +150,7 @@ github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -185,8 +186,9 @@ golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5 h1:2M3HP5CCK1Si9FQhwnzYhXdG6DXeebvUHFpre8QvbyI= golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 h1:VLliZ0d+/avPrXXH+OakdXhpJuEoBZuwh1m2j7U6Iug= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= @@ -196,8 +198,9 @@ golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.1 h1:Kvvh58BN8Y9/lBi7hTekvtMpm07eUZ0ck5pRHpsMWrY= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -231,6 +234,7 @@ golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420 h1:a8jGStKg0XqKDlKqjLrXn0ioF5MH36pT7Z0BRTqLhbk= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -244,8 +248,8 @@ golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210427180440-81ed05c6b58c h1:SgVl/sCtkicsS7psKkje4H9YtjdEl3xsYh7N+5TDHqY= -golang.org/x/oauth2 v0.0.0-20210427180440-81ed05c6b58c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c h1:pkQiBZBvdos9qq4wBAHqlzuZHEXo07pqV06ef90u1WI= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -293,9 +297,11 @@ golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210503080704-8803ae5d1324 h1:pAwJxDByZctfPwzlNGrDN2BQLsdPb9NkhoTJtUkAO28= -golang.org/x/sys v0.0.0-20210503080704-8803ae5d1324/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015 h1:hZR0X1kPW+nwyJ9xRxqZk1vx5RUObAPBdKVvXPDUH/E= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -356,8 +362,9 @@ golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20201202200335-bef1c476418a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.0 h1:po9/4sTYwZU9lPhi1tOrb4hCv3qrhiQ77LZfGa2OjwY= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.1 h1:wGiQel/hW0NnEkJUk8lbzkX2gFJU6PFxf1v5OlCfuOs= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -384,8 +391,8 @@ google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34q google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= -google.golang.org/api v0.46.0 h1:jkDWHOBIoNSD0OQpq4rtBVu+Rh325MPjXG1rakAp8JU= -google.golang.org/api v0.46.0/go.mod h1:ceL4oozhkAiTID8XMmJBsIxID/9wMXJVVFXPg4ylg3I= +google.golang.org/api v0.47.0 h1:sQLWZQvP6jPGIP4JGPkJu4zHswrv81iobiyszr3b/0I= +google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -435,9 +442,9 @@ google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= -google.golang.org/genproto v0.0.0-20210429181445-86c259c2b4ab/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= -google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a h1:VA0wtJaR+W1I11P2f535J7D/YxyvEFMTMvcmyeZ9FBE= -google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d h1:bRz6UmsZEz/CzoTjUDp4ZcdguhSWi6CyU299wMQBpZU= +google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= @@ -456,7 +463,6 @@ google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA5 google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.37.1 h1:ARnQJNWxGyYJpdf/JXscNlQr/uv607ZPU9Z7ogHi+iI= google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= diff --git a/recaptchaenterprise/apiv1/doc.go b/recaptchaenterprise/apiv1/doc.go index e442b6604141..2145bac933ec 100644 --- a/recaptchaenterprise/apiv1/doc.go +++ b/recaptchaenterprise/apiv1/doc.go @@ -26,7 +26,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package recaptchaenterprise // import "cloud.google.com/go/recaptchaenterprise/apiv1" import ( @@ -46,7 +46,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/recaptchaenterprise/apiv1/recaptcha_enterprise_client.go b/recaptchaenterprise/apiv1/recaptcha_enterprise_client.go index cdbfe9a4d781..68393c790f99 100644 --- a/recaptchaenterprise/apiv1/recaptcha_enterprise_client.go +++ b/recaptchaenterprise/apiv1/recaptcha_enterprise_client.go @@ -47,7 +47,7 @@ type CallOptions struct { DeleteKey []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("recaptchaenterprise.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("recaptchaenterprise.mtls.googleapis.com:443"), @@ -71,32 +71,116 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from reCAPTCHA Enterprise API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateAssessment(context.Context, *recaptchaenterprisepb.CreateAssessmentRequest, ...gax.CallOption) (*recaptchaenterprisepb.Assessment, error) + AnnotateAssessment(context.Context, *recaptchaenterprisepb.AnnotateAssessmentRequest, ...gax.CallOption) (*recaptchaenterprisepb.AnnotateAssessmentResponse, error) + CreateKey(context.Context, *recaptchaenterprisepb.CreateKeyRequest, ...gax.CallOption) (*recaptchaenterprisepb.Key, error) + ListKeys(context.Context, *recaptchaenterprisepb.ListKeysRequest, ...gax.CallOption) *KeyIterator + GetKey(context.Context, *recaptchaenterprisepb.GetKeyRequest, ...gax.CallOption) (*recaptchaenterprisepb.Key, error) + UpdateKey(context.Context, *recaptchaenterprisepb.UpdateKeyRequest, ...gax.CallOption) (*recaptchaenterprisepb.Key, error) + DeleteKey(context.Context, *recaptchaenterprisepb.DeleteKeyRequest, ...gax.CallOption) error +} + // Client is a client for interacting with reCAPTCHA Enterprise API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service to determine the likelihood an event is legitimate. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateAssessment creates an Assessment of the likelihood an event is legitimate. +func (c *Client) CreateAssessment(ctx context.Context, req *recaptchaenterprisepb.CreateAssessmentRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Assessment, error) { + return c.internalClient.CreateAssessment(ctx, req, opts...) +} + +// AnnotateAssessment annotates a previously created Assessment to provide additional information +// on whether the event turned out to be authentic or fradulent. +func (c *Client) AnnotateAssessment(ctx context.Context, req *recaptchaenterprisepb.AnnotateAssessmentRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.AnnotateAssessmentResponse, error) { + return c.internalClient.AnnotateAssessment(ctx, req, opts...) +} + +// CreateKey creates a new reCAPTCHA Enterprise key. +func (c *Client) CreateKey(ctx context.Context, req *recaptchaenterprisepb.CreateKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { + return c.internalClient.CreateKey(ctx, req, opts...) +} + +// ListKeys returns the list of all keys that belong to a project. +func (c *Client) ListKeys(ctx context.Context, req *recaptchaenterprisepb.ListKeysRequest, opts ...gax.CallOption) *KeyIterator { + return c.internalClient.ListKeys(ctx, req, opts...) +} + +// GetKey returns the specified key. +func (c *Client) GetKey(ctx context.Context, req *recaptchaenterprisepb.GetKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { + return c.internalClient.GetKey(ctx, req, opts...) +} + +// UpdateKey updates the specified key. +func (c *Client) UpdateKey(ctx context.Context, req *recaptchaenterprisepb.UpdateKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { + return c.internalClient.UpdateKey(ctx, req, opts...) +} + +// DeleteKey deletes the specified key. +func (c *Client) DeleteKey(ctx context.Context, req *recaptchaenterprisepb.DeleteKeyRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteKey(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with reCAPTCHA Enterprise API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client recaptchaenterprisepb.RecaptchaEnterpriseServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new recaptcha enterprise service client. +// NewClient creates a new recaptcha enterprise service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service to determine the likelihood an event is legitimate. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -114,42 +198,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: recaptchaenterprisepb.NewRecaptchaEnterpriseServiceClient(connPool), + client: recaptchaenterprisepb.NewRecaptchaEnterpriseServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateAssessment creates an Assessment of the likelihood an event is legitimate. -func (c *Client) CreateAssessment(ctx context.Context, req *recaptchaenterprisepb.CreateAssessmentRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Assessment, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateAssessment(ctx context.Context, req *recaptchaenterprisepb.CreateAssessmentRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Assessment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -157,7 +243,7 @@ func (c *Client) CreateAssessment(ctx context.Context, req *recaptchaenterprisep } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateAssessment[0:len(c.CallOptions.CreateAssessment):len(c.CallOptions.CreateAssessment)], opts...) + opts = append((*c.CallOptions).CreateAssessment[0:len((*c.CallOptions).CreateAssessment):len((*c.CallOptions).CreateAssessment)], opts...) var resp *recaptchaenterprisepb.Assessment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -170,9 +256,7 @@ func (c *Client) CreateAssessment(ctx context.Context, req *recaptchaenterprisep return resp, nil } -// AnnotateAssessment annotates a previously created Assessment to provide additional information -// on whether the event turned out to be authentic or fradulent. -func (c *Client) AnnotateAssessment(ctx context.Context, req *recaptchaenterprisepb.AnnotateAssessmentRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.AnnotateAssessmentResponse, error) { +func (c *gRPCClient) AnnotateAssessment(ctx context.Context, req *recaptchaenterprisepb.AnnotateAssessmentRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.AnnotateAssessmentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -180,7 +264,7 @@ func (c *Client) AnnotateAssessment(ctx context.Context, req *recaptchaenterpris } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AnnotateAssessment[0:len(c.CallOptions.AnnotateAssessment):len(c.CallOptions.AnnotateAssessment)], opts...) + opts = append((*c.CallOptions).AnnotateAssessment[0:len((*c.CallOptions).AnnotateAssessment):len((*c.CallOptions).AnnotateAssessment)], opts...) var resp *recaptchaenterprisepb.AnnotateAssessmentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -193,8 +277,7 @@ func (c *Client) AnnotateAssessment(ctx context.Context, req *recaptchaenterpris return resp, nil } -// CreateKey creates a new reCAPTCHA Enterprise key. -func (c *Client) CreateKey(ctx context.Context, req *recaptchaenterprisepb.CreateKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { +func (c *gRPCClient) CreateKey(ctx context.Context, req *recaptchaenterprisepb.CreateKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -202,7 +285,7 @@ func (c *Client) CreateKey(ctx context.Context, req *recaptchaenterprisepb.Creat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateKey[0:len(c.CallOptions.CreateKey):len(c.CallOptions.CreateKey)], opts...) + opts = append((*c.CallOptions).CreateKey[0:len((*c.CallOptions).CreateKey):len((*c.CallOptions).CreateKey)], opts...) var resp *recaptchaenterprisepb.Key err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -215,11 +298,10 @@ func (c *Client) CreateKey(ctx context.Context, req *recaptchaenterprisepb.Creat return resp, nil } -// ListKeys returns the list of all keys that belong to a project. -func (c *Client) ListKeys(ctx context.Context, req *recaptchaenterprisepb.ListKeysRequest, opts ...gax.CallOption) *KeyIterator { +func (c *gRPCClient) ListKeys(ctx context.Context, req *recaptchaenterprisepb.ListKeysRequest, opts ...gax.CallOption) *KeyIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListKeys[0:len(c.CallOptions.ListKeys):len(c.CallOptions.ListKeys)], opts...) + opts = append((*c.CallOptions).ListKeys[0:len((*c.CallOptions).ListKeys):len((*c.CallOptions).ListKeys)], opts...) it := &KeyIterator{} req = proto.Clone(req).(*recaptchaenterprisepb.ListKeysRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*recaptchaenterprisepb.Key, string, error) { @@ -256,8 +338,7 @@ func (c *Client) ListKeys(ctx context.Context, req *recaptchaenterprisepb.ListKe return it } -// GetKey returns the specified key. -func (c *Client) GetKey(ctx context.Context, req *recaptchaenterprisepb.GetKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { +func (c *gRPCClient) GetKey(ctx context.Context, req *recaptchaenterprisepb.GetKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -265,7 +346,7 @@ func (c *Client) GetKey(ctx context.Context, req *recaptchaenterprisepb.GetKeyRe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetKey[0:len(c.CallOptions.GetKey):len(c.CallOptions.GetKey)], opts...) + opts = append((*c.CallOptions).GetKey[0:len((*c.CallOptions).GetKey):len((*c.CallOptions).GetKey)], opts...) var resp *recaptchaenterprisepb.Key err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -278,8 +359,7 @@ func (c *Client) GetKey(ctx context.Context, req *recaptchaenterprisepb.GetKeyRe return resp, nil } -// UpdateKey updates the specified key. -func (c *Client) UpdateKey(ctx context.Context, req *recaptchaenterprisepb.UpdateKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { +func (c *gRPCClient) UpdateKey(ctx context.Context, req *recaptchaenterprisepb.UpdateKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -287,7 +367,7 @@ func (c *Client) UpdateKey(ctx context.Context, req *recaptchaenterprisepb.Updat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "key.name", url.QueryEscape(req.GetKey().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateKey[0:len(c.CallOptions.UpdateKey):len(c.CallOptions.UpdateKey)], opts...) + opts = append((*c.CallOptions).UpdateKey[0:len((*c.CallOptions).UpdateKey):len((*c.CallOptions).UpdateKey)], opts...) var resp *recaptchaenterprisepb.Key err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -300,8 +380,7 @@ func (c *Client) UpdateKey(ctx context.Context, req *recaptchaenterprisepb.Updat return resp, nil } -// DeleteKey deletes the specified key. -func (c *Client) DeleteKey(ctx context.Context, req *recaptchaenterprisepb.DeleteKeyRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteKey(ctx context.Context, req *recaptchaenterprisepb.DeleteKeyRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -309,7 +388,7 @@ func (c *Client) DeleteKey(ctx context.Context, req *recaptchaenterprisepb.Delet } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteKey[0:len(c.CallOptions.DeleteKey):len(c.CallOptions.DeleteKey)], opts...) + opts = append((*c.CallOptions).DeleteKey[0:len((*c.CallOptions).DeleteKey):len((*c.CallOptions).DeleteKey)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteKey(ctx, req, settings.GRPC...) diff --git a/recaptchaenterprise/apiv1/recaptcha_enterprise_client_example_test.go b/recaptchaenterprise/apiv1/recaptcha_enterprise_client_example_test.go index 11a825fa0de1..0b7b5ca43bf3 100644 --- a/recaptchaenterprise/apiv1/recaptcha_enterprise_client_example_test.go +++ b/recaptchaenterprise/apiv1/recaptcha_enterprise_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateAssessment() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1" - ctx := context.Background() c, err := recaptchaenterprise.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.CreateAssessmentRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleClient_CreateAssessment() { } func ExampleClient_AnnotateAssessment() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1" - ctx := context.Background() c, err := recaptchaenterprise.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.AnnotateAssessmentRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleClient_AnnotateAssessment() { } func ExampleClient_CreateKey() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1" - ctx := context.Background() c, err := recaptchaenterprise.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.CreateKeyRequest{ // TODO: Fill request struct fields. @@ -95,14 +94,12 @@ func ExampleClient_CreateKey() { } func ExampleClient_ListKeys() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recaptchaenterprise.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.ListKeysRequest{ // TODO: Fill request struct fields. @@ -122,13 +119,12 @@ func ExampleClient_ListKeys() { } func ExampleClient_GetKey() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1" - ctx := context.Background() c, err := recaptchaenterprise.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.GetKeyRequest{ // TODO: Fill request struct fields. @@ -142,13 +138,12 @@ func ExampleClient_GetKey() { } func ExampleClient_UpdateKey() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1" - ctx := context.Background() c, err := recaptchaenterprise.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.UpdateKeyRequest{ // TODO: Fill request struct fields. @@ -167,6 +162,7 @@ func ExampleClient_DeleteKey() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.DeleteKeyRequest{ // TODO: Fill request struct fields. diff --git a/recaptchaenterprise/apiv1beta1/doc.go b/recaptchaenterprise/apiv1beta1/doc.go index 74d0746238e3..46cb1d38e819 100644 --- a/recaptchaenterprise/apiv1beta1/doc.go +++ b/recaptchaenterprise/apiv1beta1/doc.go @@ -17,6 +17,8 @@ // Package recaptchaenterprise is an auto-generated package for the // reCAPTCHA Enterprise API. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -26,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package recaptchaenterprise // import "cloud.google.com/go/recaptchaenterprise/apiv1beta1" import ( @@ -46,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/recaptchaenterprise/apiv1beta1/recaptcha_enterprise_service_v1_beta1_client.go b/recaptchaenterprise/apiv1beta1/recaptcha_enterprise_service_v1_beta1_client.go index 3d19047e2a10..2e4df8ae8f23 100644 --- a/recaptchaenterprise/apiv1beta1/recaptcha_enterprise_service_v1_beta1_client.go +++ b/recaptchaenterprise/apiv1beta1/recaptcha_enterprise_service_v1_beta1_client.go @@ -47,7 +47,7 @@ type RecaptchaEnterpriseServiceV1Beta1CallOptions struct { DeleteKey []gax.CallOption } -func defaultRecaptchaEnterpriseServiceV1Beta1ClientOptions() []option.ClientOption { +func defaultRecaptchaEnterpriseServiceV1Beta1GRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("recaptchaenterprise.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("recaptchaenterprise.mtls.googleapis.com:443"), @@ -71,32 +71,116 @@ func defaultRecaptchaEnterpriseServiceV1Beta1CallOptions() *RecaptchaEnterpriseS } } +// internalRecaptchaEnterpriseServiceV1Beta1Client is an interface that defines the methods availaible from reCAPTCHA Enterprise API. +type internalRecaptchaEnterpriseServiceV1Beta1Client interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateAssessment(context.Context, *recaptchaenterprisepb.CreateAssessmentRequest, ...gax.CallOption) (*recaptchaenterprisepb.Assessment, error) + AnnotateAssessment(context.Context, *recaptchaenterprisepb.AnnotateAssessmentRequest, ...gax.CallOption) (*recaptchaenterprisepb.AnnotateAssessmentResponse, error) + CreateKey(context.Context, *recaptchaenterprisepb.CreateKeyRequest, ...gax.CallOption) (*recaptchaenterprisepb.Key, error) + ListKeys(context.Context, *recaptchaenterprisepb.ListKeysRequest, ...gax.CallOption) *KeyIterator + GetKey(context.Context, *recaptchaenterprisepb.GetKeyRequest, ...gax.CallOption) (*recaptchaenterprisepb.Key, error) + UpdateKey(context.Context, *recaptchaenterprisepb.UpdateKeyRequest, ...gax.CallOption) (*recaptchaenterprisepb.Key, error) + DeleteKey(context.Context, *recaptchaenterprisepb.DeleteKeyRequest, ...gax.CallOption) error +} + // RecaptchaEnterpriseServiceV1Beta1Client is a client for interacting with reCAPTCHA Enterprise API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service to determine the likelihood an event is legitimate. type RecaptchaEnterpriseServiceV1Beta1Client struct { + // The internal transport-dependent client. + internalClient internalRecaptchaEnterpriseServiceV1Beta1Client + + // The call options for this service. + CallOptions *RecaptchaEnterpriseServiceV1Beta1CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *RecaptchaEnterpriseServiceV1Beta1Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *RecaptchaEnterpriseServiceV1Beta1Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *RecaptchaEnterpriseServiceV1Beta1Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateAssessment creates an Assessment of the likelihood an event is legitimate. +func (c *RecaptchaEnterpriseServiceV1Beta1Client) CreateAssessment(ctx context.Context, req *recaptchaenterprisepb.CreateAssessmentRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Assessment, error) { + return c.internalClient.CreateAssessment(ctx, req, opts...) +} + +// AnnotateAssessment annotates a previously created Assessment to provide additional information +// on whether the event turned out to be authentic or fradulent. +func (c *RecaptchaEnterpriseServiceV1Beta1Client) AnnotateAssessment(ctx context.Context, req *recaptchaenterprisepb.AnnotateAssessmentRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.AnnotateAssessmentResponse, error) { + return c.internalClient.AnnotateAssessment(ctx, req, opts...) +} + +// CreateKey creates a new reCAPTCHA Enterprise key. +func (c *RecaptchaEnterpriseServiceV1Beta1Client) CreateKey(ctx context.Context, req *recaptchaenterprisepb.CreateKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { + return c.internalClient.CreateKey(ctx, req, opts...) +} + +// ListKeys returns the list of all keys that belong to a project. +func (c *RecaptchaEnterpriseServiceV1Beta1Client) ListKeys(ctx context.Context, req *recaptchaenterprisepb.ListKeysRequest, opts ...gax.CallOption) *KeyIterator { + return c.internalClient.ListKeys(ctx, req, opts...) +} + +// GetKey returns the specified key. +func (c *RecaptchaEnterpriseServiceV1Beta1Client) GetKey(ctx context.Context, req *recaptchaenterprisepb.GetKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { + return c.internalClient.GetKey(ctx, req, opts...) +} + +// UpdateKey updates the specified key. +func (c *RecaptchaEnterpriseServiceV1Beta1Client) UpdateKey(ctx context.Context, req *recaptchaenterprisepb.UpdateKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { + return c.internalClient.UpdateKey(ctx, req, opts...) +} + +// DeleteKey deletes the specified key. +func (c *RecaptchaEnterpriseServiceV1Beta1Client) DeleteKey(ctx context.Context, req *recaptchaenterprisepb.DeleteKeyRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteKey(ctx, req, opts...) +} + +// recaptchaEnterpriseServiceV1Beta1GRPCClient is a client for interacting with reCAPTCHA Enterprise API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type recaptchaEnterpriseServiceV1Beta1GRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing RecaptchaEnterpriseServiceV1Beta1Client + CallOptions **RecaptchaEnterpriseServiceV1Beta1CallOptions + // The gRPC API client. recaptchaEnterpriseServiceV1Beta1Client recaptchaenterprisepb.RecaptchaEnterpriseServiceV1Beta1Client - // The call options for this service. - CallOptions *RecaptchaEnterpriseServiceV1Beta1CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewRecaptchaEnterpriseServiceV1Beta1Client creates a new recaptcha enterprise service v1 beta1 client. +// NewRecaptchaEnterpriseServiceV1Beta1Client creates a new recaptcha enterprise service v1 beta1 client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service to determine the likelihood an event is legitimate. func NewRecaptchaEnterpriseServiceV1Beta1Client(ctx context.Context, opts ...option.ClientOption) (*RecaptchaEnterpriseServiceV1Beta1Client, error) { - clientOpts := defaultRecaptchaEnterpriseServiceV1Beta1ClientOptions() - + clientOpts := defaultRecaptchaEnterpriseServiceV1Beta1GRPCClientOptions() if newRecaptchaEnterpriseServiceV1Beta1ClientHook != nil { hookOpts, err := newRecaptchaEnterpriseServiceV1Beta1ClientHook(ctx, clientHookParams{}) if err != nil { @@ -114,42 +198,44 @@ func NewRecaptchaEnterpriseServiceV1Beta1Client(ctx context.Context, opts ...opt if err != nil { return nil, err } - c := &RecaptchaEnterpriseServiceV1Beta1Client{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultRecaptchaEnterpriseServiceV1Beta1CallOptions(), + client := RecaptchaEnterpriseServiceV1Beta1Client{CallOptions: defaultRecaptchaEnterpriseServiceV1Beta1CallOptions()} + c := &recaptchaEnterpriseServiceV1Beta1GRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, recaptchaEnterpriseServiceV1Beta1Client: recaptchaenterprisepb.NewRecaptchaEnterpriseServiceV1Beta1Client(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *RecaptchaEnterpriseServiceV1Beta1Client) Connection() *grpc.ClientConn { +func (c *recaptchaEnterpriseServiceV1Beta1GRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *RecaptchaEnterpriseServiceV1Beta1Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *RecaptchaEnterpriseServiceV1Beta1Client) setGoogleClientInfo(keyval ...string) { +func (c *recaptchaEnterpriseServiceV1Beta1GRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateAssessment creates an Assessment of the likelihood an event is legitimate. -func (c *RecaptchaEnterpriseServiceV1Beta1Client) CreateAssessment(ctx context.Context, req *recaptchaenterprisepb.CreateAssessmentRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Assessment, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *recaptchaEnterpriseServiceV1Beta1GRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *recaptchaEnterpriseServiceV1Beta1GRPCClient) CreateAssessment(ctx context.Context, req *recaptchaenterprisepb.CreateAssessmentRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Assessment, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -157,7 +243,7 @@ func (c *RecaptchaEnterpriseServiceV1Beta1Client) CreateAssessment(ctx context.C } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateAssessment[0:len(c.CallOptions.CreateAssessment):len(c.CallOptions.CreateAssessment)], opts...) + opts = append((*c.CallOptions).CreateAssessment[0:len((*c.CallOptions).CreateAssessment):len((*c.CallOptions).CreateAssessment)], opts...) var resp *recaptchaenterprisepb.Assessment err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -170,9 +256,7 @@ func (c *RecaptchaEnterpriseServiceV1Beta1Client) CreateAssessment(ctx context.C return resp, nil } -// AnnotateAssessment annotates a previously created Assessment to provide additional information -// on whether the event turned out to be authentic or fradulent. -func (c *RecaptchaEnterpriseServiceV1Beta1Client) AnnotateAssessment(ctx context.Context, req *recaptchaenterprisepb.AnnotateAssessmentRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.AnnotateAssessmentResponse, error) { +func (c *recaptchaEnterpriseServiceV1Beta1GRPCClient) AnnotateAssessment(ctx context.Context, req *recaptchaenterprisepb.AnnotateAssessmentRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.AnnotateAssessmentResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -180,7 +264,7 @@ func (c *RecaptchaEnterpriseServiceV1Beta1Client) AnnotateAssessment(ctx context } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AnnotateAssessment[0:len(c.CallOptions.AnnotateAssessment):len(c.CallOptions.AnnotateAssessment)], opts...) + opts = append((*c.CallOptions).AnnotateAssessment[0:len((*c.CallOptions).AnnotateAssessment):len((*c.CallOptions).AnnotateAssessment)], opts...) var resp *recaptchaenterprisepb.AnnotateAssessmentResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -193,8 +277,7 @@ func (c *RecaptchaEnterpriseServiceV1Beta1Client) AnnotateAssessment(ctx context return resp, nil } -// CreateKey creates a new reCAPTCHA Enterprise key. -func (c *RecaptchaEnterpriseServiceV1Beta1Client) CreateKey(ctx context.Context, req *recaptchaenterprisepb.CreateKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { +func (c *recaptchaEnterpriseServiceV1Beta1GRPCClient) CreateKey(ctx context.Context, req *recaptchaenterprisepb.CreateKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -202,7 +285,7 @@ func (c *RecaptchaEnterpriseServiceV1Beta1Client) CreateKey(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateKey[0:len(c.CallOptions.CreateKey):len(c.CallOptions.CreateKey)], opts...) + opts = append((*c.CallOptions).CreateKey[0:len((*c.CallOptions).CreateKey):len((*c.CallOptions).CreateKey)], opts...) var resp *recaptchaenterprisepb.Key err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -215,11 +298,10 @@ func (c *RecaptchaEnterpriseServiceV1Beta1Client) CreateKey(ctx context.Context, return resp, nil } -// ListKeys returns the list of all keys that belong to a project. -func (c *RecaptchaEnterpriseServiceV1Beta1Client) ListKeys(ctx context.Context, req *recaptchaenterprisepb.ListKeysRequest, opts ...gax.CallOption) *KeyIterator { +func (c *recaptchaEnterpriseServiceV1Beta1GRPCClient) ListKeys(ctx context.Context, req *recaptchaenterprisepb.ListKeysRequest, opts ...gax.CallOption) *KeyIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListKeys[0:len(c.CallOptions.ListKeys):len(c.CallOptions.ListKeys)], opts...) + opts = append((*c.CallOptions).ListKeys[0:len((*c.CallOptions).ListKeys):len((*c.CallOptions).ListKeys)], opts...) it := &KeyIterator{} req = proto.Clone(req).(*recaptchaenterprisepb.ListKeysRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*recaptchaenterprisepb.Key, string, error) { @@ -256,8 +338,7 @@ func (c *RecaptchaEnterpriseServiceV1Beta1Client) ListKeys(ctx context.Context, return it } -// GetKey returns the specified key. -func (c *RecaptchaEnterpriseServiceV1Beta1Client) GetKey(ctx context.Context, req *recaptchaenterprisepb.GetKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { +func (c *recaptchaEnterpriseServiceV1Beta1GRPCClient) GetKey(ctx context.Context, req *recaptchaenterprisepb.GetKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -265,7 +346,7 @@ func (c *RecaptchaEnterpriseServiceV1Beta1Client) GetKey(ctx context.Context, re } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetKey[0:len(c.CallOptions.GetKey):len(c.CallOptions.GetKey)], opts...) + opts = append((*c.CallOptions).GetKey[0:len((*c.CallOptions).GetKey):len((*c.CallOptions).GetKey)], opts...) var resp *recaptchaenterprisepb.Key err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -278,8 +359,7 @@ func (c *RecaptchaEnterpriseServiceV1Beta1Client) GetKey(ctx context.Context, re return resp, nil } -// UpdateKey updates the specified key. -func (c *RecaptchaEnterpriseServiceV1Beta1Client) UpdateKey(ctx context.Context, req *recaptchaenterprisepb.UpdateKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { +func (c *recaptchaEnterpriseServiceV1Beta1GRPCClient) UpdateKey(ctx context.Context, req *recaptchaenterprisepb.UpdateKeyRequest, opts ...gax.CallOption) (*recaptchaenterprisepb.Key, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -287,7 +367,7 @@ func (c *RecaptchaEnterpriseServiceV1Beta1Client) UpdateKey(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "key.name", url.QueryEscape(req.GetKey().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateKey[0:len(c.CallOptions.UpdateKey):len(c.CallOptions.UpdateKey)], opts...) + opts = append((*c.CallOptions).UpdateKey[0:len((*c.CallOptions).UpdateKey):len((*c.CallOptions).UpdateKey)], opts...) var resp *recaptchaenterprisepb.Key err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -300,8 +380,7 @@ func (c *RecaptchaEnterpriseServiceV1Beta1Client) UpdateKey(ctx context.Context, return resp, nil } -// DeleteKey deletes the specified key. -func (c *RecaptchaEnterpriseServiceV1Beta1Client) DeleteKey(ctx context.Context, req *recaptchaenterprisepb.DeleteKeyRequest, opts ...gax.CallOption) error { +func (c *recaptchaEnterpriseServiceV1Beta1GRPCClient) DeleteKey(ctx context.Context, req *recaptchaenterprisepb.DeleteKeyRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -309,7 +388,7 @@ func (c *RecaptchaEnterpriseServiceV1Beta1Client) DeleteKey(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteKey[0:len(c.CallOptions.DeleteKey):len(c.CallOptions.DeleteKey)], opts...) + opts = append((*c.CallOptions).DeleteKey[0:len((*c.CallOptions).DeleteKey):len((*c.CallOptions).DeleteKey)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.recaptchaEnterpriseServiceV1Beta1Client.DeleteKey(ctx, req, settings.GRPC...) diff --git a/recaptchaenterprise/apiv1beta1/recaptcha_enterprise_service_v1_beta1_client_example_test.go b/recaptchaenterprise/apiv1beta1/recaptcha_enterprise_service_v1_beta1_client_example_test.go index 08afbf3a056d..7d197a232b74 100644 --- a/recaptchaenterprise/apiv1beta1/recaptcha_enterprise_service_v1_beta1_client_example_test.go +++ b/recaptchaenterprise/apiv1beta1/recaptcha_enterprise_service_v1_beta1_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewRecaptchaEnterpriseServiceV1Beta1Client() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleRecaptchaEnterpriseServiceV1Beta1Client_CreateAssessment() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1beta1" - ctx := context.Background() c, err := recaptchaenterprise.NewRecaptchaEnterpriseServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.CreateAssessmentRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleRecaptchaEnterpriseServiceV1Beta1Client_CreateAssessment() { } func ExampleRecaptchaEnterpriseServiceV1Beta1Client_AnnotateAssessment() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1beta1" - ctx := context.Background() c, err := recaptchaenterprise.NewRecaptchaEnterpriseServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.AnnotateAssessmentRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleRecaptchaEnterpriseServiceV1Beta1Client_AnnotateAssessment() { } func ExampleRecaptchaEnterpriseServiceV1Beta1Client_CreateKey() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1beta1" - ctx := context.Background() c, err := recaptchaenterprise.NewRecaptchaEnterpriseServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.CreateKeyRequest{ // TODO: Fill request struct fields. @@ -95,14 +94,12 @@ func ExampleRecaptchaEnterpriseServiceV1Beta1Client_CreateKey() { } func ExampleRecaptchaEnterpriseServiceV1Beta1Client_ListKeys() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recaptchaenterprise.NewRecaptchaEnterpriseServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.ListKeysRequest{ // TODO: Fill request struct fields. @@ -122,13 +119,12 @@ func ExampleRecaptchaEnterpriseServiceV1Beta1Client_ListKeys() { } func ExampleRecaptchaEnterpriseServiceV1Beta1Client_GetKey() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1beta1" - ctx := context.Background() c, err := recaptchaenterprise.NewRecaptchaEnterpriseServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.GetKeyRequest{ // TODO: Fill request struct fields. @@ -142,13 +138,12 @@ func ExampleRecaptchaEnterpriseServiceV1Beta1Client_GetKey() { } func ExampleRecaptchaEnterpriseServiceV1Beta1Client_UpdateKey() { - // import recaptchaenterprisepb "google.golang.org/genproto/googleapis/cloud/recaptchaenterprise/v1beta1" - ctx := context.Background() c, err := recaptchaenterprise.NewRecaptchaEnterpriseServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.UpdateKeyRequest{ // TODO: Fill request struct fields. @@ -167,6 +162,7 @@ func ExampleRecaptchaEnterpriseServiceV1Beta1Client_DeleteKey() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &recaptchaenterprisepb.DeleteKeyRequest{ // TODO: Fill request struct fields. diff --git a/recommendationengine/apiv1beta1/catalog_client.go b/recommendationengine/apiv1beta1/catalog_client.go index c1666f625e2b..11653d90fe61 100644 --- a/recommendationengine/apiv1beta1/catalog_client.go +++ b/recommendationengine/apiv1beta1/catalog_client.go @@ -50,7 +50,7 @@ type CatalogCallOptions struct { ImportCatalogItems []gax.CallOption } -func defaultCatalogClientOptions() []option.ClientOption { +func defaultCatalogGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("recommendationengine.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("recommendationengine.mtls.googleapis.com:443"), @@ -139,37 +139,132 @@ func defaultCatalogCallOptions() *CatalogCallOptions { } } +// internalCatalogClient is an interface that defines the methods availaible from Recommendations AI. +type internalCatalogClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateCatalogItem(context.Context, *recommendationenginepb.CreateCatalogItemRequest, ...gax.CallOption) (*recommendationenginepb.CatalogItem, error) + GetCatalogItem(context.Context, *recommendationenginepb.GetCatalogItemRequest, ...gax.CallOption) (*recommendationenginepb.CatalogItem, error) + ListCatalogItems(context.Context, *recommendationenginepb.ListCatalogItemsRequest, ...gax.CallOption) *CatalogItemIterator + UpdateCatalogItem(context.Context, *recommendationenginepb.UpdateCatalogItemRequest, ...gax.CallOption) (*recommendationenginepb.CatalogItem, error) + DeleteCatalogItem(context.Context, *recommendationenginepb.DeleteCatalogItemRequest, ...gax.CallOption) error + ImportCatalogItems(context.Context, *recommendationenginepb.ImportCatalogItemsRequest, ...gax.CallOption) (*ImportCatalogItemsOperation, error) + ImportCatalogItemsOperation(name string) *ImportCatalogItemsOperation +} + // CatalogClient is a client for interacting with Recommendations AI. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for ingesting catalog information of the customer’s website. type CatalogClient struct { + // The internal transport-dependent client. + internalClient internalCatalogClient + + // The call options for this service. + CallOptions *CatalogCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CatalogClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CatalogClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CatalogClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateCatalogItem creates a catalog item. +func (c *CatalogClient) CreateCatalogItem(ctx context.Context, req *recommendationenginepb.CreateCatalogItemRequest, opts ...gax.CallOption) (*recommendationenginepb.CatalogItem, error) { + return c.internalClient.CreateCatalogItem(ctx, req, opts...) +} + +// GetCatalogItem gets a specific catalog item. +func (c *CatalogClient) GetCatalogItem(ctx context.Context, req *recommendationenginepb.GetCatalogItemRequest, opts ...gax.CallOption) (*recommendationenginepb.CatalogItem, error) { + return c.internalClient.GetCatalogItem(ctx, req, opts...) +} + +// ListCatalogItems gets a list of catalog items. +func (c *CatalogClient) ListCatalogItems(ctx context.Context, req *recommendationenginepb.ListCatalogItemsRequest, opts ...gax.CallOption) *CatalogItemIterator { + return c.internalClient.ListCatalogItems(ctx, req, opts...) +} + +// UpdateCatalogItem updates a catalog item. Partial updating is supported. Non-existing +// items will be created. +func (c *CatalogClient) UpdateCatalogItem(ctx context.Context, req *recommendationenginepb.UpdateCatalogItemRequest, opts ...gax.CallOption) (*recommendationenginepb.CatalogItem, error) { + return c.internalClient.UpdateCatalogItem(ctx, req, opts...) +} + +// DeleteCatalogItem deletes a catalog item. +func (c *CatalogClient) DeleteCatalogItem(ctx context.Context, req *recommendationenginepb.DeleteCatalogItemRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteCatalogItem(ctx, req, opts...) +} + +// ImportCatalogItems bulk import of multiple catalog items. Request processing may be +// synchronous. No partial updating supported. Non-existing items will be +// created. +// +// Operation.response is of type ImportResponse. Note that it is +// possible for a subset of the items to be successfully updated. +func (c *CatalogClient) ImportCatalogItems(ctx context.Context, req *recommendationenginepb.ImportCatalogItemsRequest, opts ...gax.CallOption) (*ImportCatalogItemsOperation, error) { + return c.internalClient.ImportCatalogItems(ctx, req, opts...) +} + +// ImportCatalogItemsOperation returns a new ImportCatalogItemsOperation from a given name. +// The name must be that of a previously created ImportCatalogItemsOperation, possibly from a different process. +func (c *CatalogClient) ImportCatalogItemsOperation(name string) *ImportCatalogItemsOperation { + return c.internalClient.ImportCatalogItemsOperation(name) +} + +// catalogGRPCClient is a client for interacting with Recommendations AI over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type catalogGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CatalogClient + CallOptions **CatalogCallOptions + // The gRPC API client. catalogClient recommendationenginepb.CatalogServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CatalogCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCatalogClient creates a new catalog service client. +// NewCatalogClient creates a new catalog service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for ingesting catalog information of the customer’s website. func NewCatalogClient(ctx context.Context, opts ...option.ClientOption) (*CatalogClient, error) { - clientOpts := defaultCatalogClientOptions() - + clientOpts := defaultCatalogGRPCClientOptions() if newCatalogClientHook != nil { hookOpts, err := newCatalogClientHook(ctx, clientHookParams{}) if err != nil { @@ -187,16 +282,19 @@ func NewCatalogClient(ctx context.Context, opts ...option.ClientOption) (*Catalo if err != nil { return nil, err } - c := &CatalogClient{ + client := CatalogClient{CallOptions: defaultCatalogCallOptions()} + + c := &catalogGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCatalogCallOptions(), - - catalogClient: recommendationenginepb.NewCatalogServiceClient(connPool), + catalogClient: recommendationenginepb.NewCatalogServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -206,33 +304,33 @@ func NewCatalogClient(ctx context.Context, opts ...option.ClientOption) (*Catalo // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CatalogClient) Connection() *grpc.ClientConn { +func (c *catalogGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CatalogClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CatalogClient) setGoogleClientInfo(keyval ...string) { +func (c *catalogGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateCatalogItem creates a catalog item. -func (c *CatalogClient) CreateCatalogItem(ctx context.Context, req *recommendationenginepb.CreateCatalogItemRequest, opts ...gax.CallOption) (*recommendationenginepb.CatalogItem, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *catalogGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *catalogGRPCClient) CreateCatalogItem(ctx context.Context, req *recommendationenginepb.CreateCatalogItemRequest, opts ...gax.CallOption) (*recommendationenginepb.CatalogItem, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -240,7 +338,7 @@ func (c *CatalogClient) CreateCatalogItem(ctx context.Context, req *recommendati } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCatalogItem[0:len(c.CallOptions.CreateCatalogItem):len(c.CallOptions.CreateCatalogItem)], opts...) + opts = append((*c.CallOptions).CreateCatalogItem[0:len((*c.CallOptions).CreateCatalogItem):len((*c.CallOptions).CreateCatalogItem)], opts...) var resp *recommendationenginepb.CatalogItem err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -253,8 +351,7 @@ func (c *CatalogClient) CreateCatalogItem(ctx context.Context, req *recommendati return resp, nil } -// GetCatalogItem gets a specific catalog item. -func (c *CatalogClient) GetCatalogItem(ctx context.Context, req *recommendationenginepb.GetCatalogItemRequest, opts ...gax.CallOption) (*recommendationenginepb.CatalogItem, error) { +func (c *catalogGRPCClient) GetCatalogItem(ctx context.Context, req *recommendationenginepb.GetCatalogItemRequest, opts ...gax.CallOption) (*recommendationenginepb.CatalogItem, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -262,7 +359,7 @@ func (c *CatalogClient) GetCatalogItem(ctx context.Context, req *recommendatione } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCatalogItem[0:len(c.CallOptions.GetCatalogItem):len(c.CallOptions.GetCatalogItem)], opts...) + opts = append((*c.CallOptions).GetCatalogItem[0:len((*c.CallOptions).GetCatalogItem):len((*c.CallOptions).GetCatalogItem)], opts...) var resp *recommendationenginepb.CatalogItem err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -275,11 +372,10 @@ func (c *CatalogClient) GetCatalogItem(ctx context.Context, req *recommendatione return resp, nil } -// ListCatalogItems gets a list of catalog items. -func (c *CatalogClient) ListCatalogItems(ctx context.Context, req *recommendationenginepb.ListCatalogItemsRequest, opts ...gax.CallOption) *CatalogItemIterator { +func (c *catalogGRPCClient) ListCatalogItems(ctx context.Context, req *recommendationenginepb.ListCatalogItemsRequest, opts ...gax.CallOption) *CatalogItemIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCatalogItems[0:len(c.CallOptions.ListCatalogItems):len(c.CallOptions.ListCatalogItems)], opts...) + opts = append((*c.CallOptions).ListCatalogItems[0:len((*c.CallOptions).ListCatalogItems):len((*c.CallOptions).ListCatalogItems)], opts...) it := &CatalogItemIterator{} req = proto.Clone(req).(*recommendationenginepb.ListCatalogItemsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*recommendationenginepb.CatalogItem, string, error) { @@ -316,9 +412,7 @@ func (c *CatalogClient) ListCatalogItems(ctx context.Context, req *recommendatio return it } -// UpdateCatalogItem updates a catalog item. Partial updating is supported. Non-existing -// items will be created. -func (c *CatalogClient) UpdateCatalogItem(ctx context.Context, req *recommendationenginepb.UpdateCatalogItemRequest, opts ...gax.CallOption) (*recommendationenginepb.CatalogItem, error) { +func (c *catalogGRPCClient) UpdateCatalogItem(ctx context.Context, req *recommendationenginepb.UpdateCatalogItemRequest, opts ...gax.CallOption) (*recommendationenginepb.CatalogItem, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -326,7 +420,7 @@ func (c *CatalogClient) UpdateCatalogItem(ctx context.Context, req *recommendati } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCatalogItem[0:len(c.CallOptions.UpdateCatalogItem):len(c.CallOptions.UpdateCatalogItem)], opts...) + opts = append((*c.CallOptions).UpdateCatalogItem[0:len((*c.CallOptions).UpdateCatalogItem):len((*c.CallOptions).UpdateCatalogItem)], opts...) var resp *recommendationenginepb.CatalogItem err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -339,8 +433,7 @@ func (c *CatalogClient) UpdateCatalogItem(ctx context.Context, req *recommendati return resp, nil } -// DeleteCatalogItem deletes a catalog item. -func (c *CatalogClient) DeleteCatalogItem(ctx context.Context, req *recommendationenginepb.DeleteCatalogItemRequest, opts ...gax.CallOption) error { +func (c *catalogGRPCClient) DeleteCatalogItem(ctx context.Context, req *recommendationenginepb.DeleteCatalogItemRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -348,7 +441,7 @@ func (c *CatalogClient) DeleteCatalogItem(ctx context.Context, req *recommendati } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteCatalogItem[0:len(c.CallOptions.DeleteCatalogItem):len(c.CallOptions.DeleteCatalogItem)], opts...) + opts = append((*c.CallOptions).DeleteCatalogItem[0:len((*c.CallOptions).DeleteCatalogItem):len((*c.CallOptions).DeleteCatalogItem)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.catalogClient.DeleteCatalogItem(ctx, req, settings.GRPC...) @@ -357,13 +450,7 @@ func (c *CatalogClient) DeleteCatalogItem(ctx context.Context, req *recommendati return err } -// ImportCatalogItems bulk import of multiple catalog items. Request processing may be -// synchronous. No partial updating supported. Non-existing items will be -// created. -// -// Operation.response is of type ImportResponse. Note that it is -// possible for a subset of the items to be successfully updated. -func (c *CatalogClient) ImportCatalogItems(ctx context.Context, req *recommendationenginepb.ImportCatalogItemsRequest, opts ...gax.CallOption) (*ImportCatalogItemsOperation, error) { +func (c *catalogGRPCClient) ImportCatalogItems(ctx context.Context, req *recommendationenginepb.ImportCatalogItemsRequest, opts ...gax.CallOption) (*ImportCatalogItemsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -371,7 +458,7 @@ func (c *CatalogClient) ImportCatalogItems(ctx context.Context, req *recommendat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportCatalogItems[0:len(c.CallOptions.ImportCatalogItems):len(c.CallOptions.ImportCatalogItems)], opts...) + opts = append((*c.CallOptions).ImportCatalogItems[0:len((*c.CallOptions).ImportCatalogItems):len((*c.CallOptions).ImportCatalogItems)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -382,7 +469,7 @@ func (c *CatalogClient) ImportCatalogItems(ctx context.Context, req *recommendat return nil, err } return &ImportCatalogItemsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -393,9 +480,9 @@ type ImportCatalogItemsOperation struct { // ImportCatalogItemsOperation returns a new ImportCatalogItemsOperation from a given name. // The name must be that of a previously created ImportCatalogItemsOperation, possibly from a different process. -func (c *CatalogClient) ImportCatalogItemsOperation(name string) *ImportCatalogItemsOperation { +func (c *catalogGRPCClient) ImportCatalogItemsOperation(name string) *ImportCatalogItemsOperation { return &ImportCatalogItemsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/recommendationengine/apiv1beta1/catalog_client_example_test.go b/recommendationengine/apiv1beta1/catalog_client_example_test.go index 6270605d221f..d521cf514e6a 100644 --- a/recommendationengine/apiv1beta1/catalog_client_example_test.go +++ b/recommendationengine/apiv1beta1/catalog_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewCatalogClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCatalogClient_CreateCatalogItem() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.CreateCatalogItemRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleCatalogClient_CreateCatalogItem() { } func ExampleCatalogClient_GetCatalogItem() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.GetCatalogItemRequest{ // TODO: Fill request struct fields. @@ -75,14 +75,12 @@ func ExampleCatalogClient_GetCatalogItem() { } func ExampleCatalogClient_ListCatalogItems() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recommendationengine.NewCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.ListCatalogItemsRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleCatalogClient_ListCatalogItems() { } func ExampleCatalogClient_UpdateCatalogItem() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.UpdateCatalogItemRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleCatalogClient_DeleteCatalogItem() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.DeleteCatalogItemRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleCatalogClient_DeleteCatalogItem() { } func ExampleCatalogClient_ImportCatalogItems() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.ImportCatalogItemsRequest{ // TODO: Fill request struct fields. diff --git a/recommendationengine/apiv1beta1/doc.go b/recommendationengine/apiv1beta1/doc.go index 968c3a23f941..1b9aa30aeb17 100644 --- a/recommendationengine/apiv1beta1/doc.go +++ b/recommendationengine/apiv1beta1/doc.go @@ -21,6 +21,8 @@ // personalized recommendation systems without requiring a high level of // expertise in machine learning, recommendation system, or Google Cloud. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -30,7 +32,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package recommendationengine // import "cloud.google.com/go/recommendationengine/apiv1beta1" import ( @@ -50,7 +52,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/recommendationengine/apiv1beta1/prediction_api_key_registry_client.go b/recommendationengine/apiv1beta1/prediction_api_key_registry_client.go index fcffa0c157e9..b53a4bb757af 100644 --- a/recommendationengine/apiv1beta1/prediction_api_key_registry_client.go +++ b/recommendationengine/apiv1beta1/prediction_api_key_registry_client.go @@ -44,7 +44,7 @@ type PredictionApiKeyRegistryCallOptions struct { DeletePredictionApiKeyRegistration []gax.CallOption } -func defaultPredictionApiKeyRegistryClientOptions() []option.ClientOption { +func defaultPredictionApiKeyRegistryGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("recommendationengine.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("recommendationengine.mtls.googleapis.com:443"), @@ -97,27 +97,91 @@ func defaultPredictionApiKeyRegistryCallOptions() *PredictionApiKeyRegistryCallO } } +// internalPredictionApiKeyRegistryClient is an interface that defines the methods availaible from Recommendations AI. +type internalPredictionApiKeyRegistryClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreatePredictionApiKeyRegistration(context.Context, *recommendationenginepb.CreatePredictionApiKeyRegistrationRequest, ...gax.CallOption) (*recommendationenginepb.PredictionApiKeyRegistration, error) + ListPredictionApiKeyRegistrations(context.Context, *recommendationenginepb.ListPredictionApiKeyRegistrationsRequest, ...gax.CallOption) *PredictionApiKeyRegistrationIterator + DeletePredictionApiKeyRegistration(context.Context, *recommendationenginepb.DeletePredictionApiKeyRegistrationRequest, ...gax.CallOption) error +} + // PredictionApiKeyRegistryClient is a client for interacting with Recommendations AI. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for registering API keys for use with the predict method. If you +// use an API key to request predictions, you must first register the API key. +// Otherwise, your prediction request is rejected. If you use OAuth to +// authenticate your predict method call, you do not need to register an API +// key. You can register up to 20 API keys per project. type PredictionApiKeyRegistryClient struct { + // The internal transport-dependent client. + internalClient internalPredictionApiKeyRegistryClient + + // The call options for this service. + CallOptions *PredictionApiKeyRegistryCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *PredictionApiKeyRegistryClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *PredictionApiKeyRegistryClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *PredictionApiKeyRegistryClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreatePredictionApiKeyRegistration register an API key for use with predict method. +func (c *PredictionApiKeyRegistryClient) CreatePredictionApiKeyRegistration(ctx context.Context, req *recommendationenginepb.CreatePredictionApiKeyRegistrationRequest, opts ...gax.CallOption) (*recommendationenginepb.PredictionApiKeyRegistration, error) { + return c.internalClient.CreatePredictionApiKeyRegistration(ctx, req, opts...) +} + +// ListPredictionApiKeyRegistrations list the registered apiKeys for use with predict method. +func (c *PredictionApiKeyRegistryClient) ListPredictionApiKeyRegistrations(ctx context.Context, req *recommendationenginepb.ListPredictionApiKeyRegistrationsRequest, opts ...gax.CallOption) *PredictionApiKeyRegistrationIterator { + return c.internalClient.ListPredictionApiKeyRegistrations(ctx, req, opts...) +} + +// DeletePredictionApiKeyRegistration unregister an apiKey from using for predict method. +func (c *PredictionApiKeyRegistryClient) DeletePredictionApiKeyRegistration(ctx context.Context, req *recommendationenginepb.DeletePredictionApiKeyRegistrationRequest, opts ...gax.CallOption) error { + return c.internalClient.DeletePredictionApiKeyRegistration(ctx, req, opts...) +} + +// predictionApiKeyRegistryGRPCClient is a client for interacting with Recommendations AI over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type predictionApiKeyRegistryGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing PredictionApiKeyRegistryClient + CallOptions **PredictionApiKeyRegistryCallOptions + // The gRPC API client. predictionApiKeyRegistryClient recommendationenginepb.PredictionApiKeyRegistryClient - // The call options for this service. - CallOptions *PredictionApiKeyRegistryCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewPredictionApiKeyRegistryClient creates a new prediction api key registry client. +// NewPredictionApiKeyRegistryClient creates a new prediction api key registry client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for registering API keys for use with the predict method. If you // use an API key to request predictions, you must first register the API key. @@ -125,8 +189,7 @@ type PredictionApiKeyRegistryClient struct { // authenticate your predict method call, you do not need to register an API // key. You can register up to 20 API keys per project. func NewPredictionApiKeyRegistryClient(ctx context.Context, opts ...option.ClientOption) (*PredictionApiKeyRegistryClient, error) { - clientOpts := defaultPredictionApiKeyRegistryClientOptions() - + clientOpts := defaultPredictionApiKeyRegistryGRPCClientOptions() if newPredictionApiKeyRegistryClientHook != nil { hookOpts, err := newPredictionApiKeyRegistryClientHook(ctx, clientHookParams{}) if err != nil { @@ -144,42 +207,44 @@ func NewPredictionApiKeyRegistryClient(ctx context.Context, opts ...option.Clien if err != nil { return nil, err } - c := &PredictionApiKeyRegistryClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultPredictionApiKeyRegistryCallOptions(), + client := PredictionApiKeyRegistryClient{CallOptions: defaultPredictionApiKeyRegistryCallOptions()} + c := &predictionApiKeyRegistryGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, predictionApiKeyRegistryClient: recommendationenginepb.NewPredictionApiKeyRegistryClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *PredictionApiKeyRegistryClient) Connection() *grpc.ClientConn { +func (c *predictionApiKeyRegistryGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *PredictionApiKeyRegistryClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *PredictionApiKeyRegistryClient) setGoogleClientInfo(keyval ...string) { +func (c *predictionApiKeyRegistryGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreatePredictionApiKeyRegistration register an API key for use with predict method. -func (c *PredictionApiKeyRegistryClient) CreatePredictionApiKeyRegistration(ctx context.Context, req *recommendationenginepb.CreatePredictionApiKeyRegistrationRequest, opts ...gax.CallOption) (*recommendationenginepb.PredictionApiKeyRegistration, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *predictionApiKeyRegistryGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *predictionApiKeyRegistryGRPCClient) CreatePredictionApiKeyRegistration(ctx context.Context, req *recommendationenginepb.CreatePredictionApiKeyRegistrationRequest, opts ...gax.CallOption) (*recommendationenginepb.PredictionApiKeyRegistration, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -187,7 +252,7 @@ func (c *PredictionApiKeyRegistryClient) CreatePredictionApiKeyRegistration(ctx } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreatePredictionApiKeyRegistration[0:len(c.CallOptions.CreatePredictionApiKeyRegistration):len(c.CallOptions.CreatePredictionApiKeyRegistration)], opts...) + opts = append((*c.CallOptions).CreatePredictionApiKeyRegistration[0:len((*c.CallOptions).CreatePredictionApiKeyRegistration):len((*c.CallOptions).CreatePredictionApiKeyRegistration)], opts...) var resp *recommendationenginepb.PredictionApiKeyRegistration err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -200,11 +265,10 @@ func (c *PredictionApiKeyRegistryClient) CreatePredictionApiKeyRegistration(ctx return resp, nil } -// ListPredictionApiKeyRegistrations list the registered apiKeys for use with predict method. -func (c *PredictionApiKeyRegistryClient) ListPredictionApiKeyRegistrations(ctx context.Context, req *recommendationenginepb.ListPredictionApiKeyRegistrationsRequest, opts ...gax.CallOption) *PredictionApiKeyRegistrationIterator { +func (c *predictionApiKeyRegistryGRPCClient) ListPredictionApiKeyRegistrations(ctx context.Context, req *recommendationenginepb.ListPredictionApiKeyRegistrationsRequest, opts ...gax.CallOption) *PredictionApiKeyRegistrationIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListPredictionApiKeyRegistrations[0:len(c.CallOptions.ListPredictionApiKeyRegistrations):len(c.CallOptions.ListPredictionApiKeyRegistrations)], opts...) + opts = append((*c.CallOptions).ListPredictionApiKeyRegistrations[0:len((*c.CallOptions).ListPredictionApiKeyRegistrations):len((*c.CallOptions).ListPredictionApiKeyRegistrations)], opts...) it := &PredictionApiKeyRegistrationIterator{} req = proto.Clone(req).(*recommendationenginepb.ListPredictionApiKeyRegistrationsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*recommendationenginepb.PredictionApiKeyRegistration, string, error) { @@ -241,8 +305,7 @@ func (c *PredictionApiKeyRegistryClient) ListPredictionApiKeyRegistrations(ctx c return it } -// DeletePredictionApiKeyRegistration unregister an apiKey from using for predict method. -func (c *PredictionApiKeyRegistryClient) DeletePredictionApiKeyRegistration(ctx context.Context, req *recommendationenginepb.DeletePredictionApiKeyRegistrationRequest, opts ...gax.CallOption) error { +func (c *predictionApiKeyRegistryGRPCClient) DeletePredictionApiKeyRegistration(ctx context.Context, req *recommendationenginepb.DeletePredictionApiKeyRegistrationRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -250,7 +313,7 @@ func (c *PredictionApiKeyRegistryClient) DeletePredictionApiKeyRegistration(ctx } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeletePredictionApiKeyRegistration[0:len(c.CallOptions.DeletePredictionApiKeyRegistration):len(c.CallOptions.DeletePredictionApiKeyRegistration)], opts...) + opts = append((*c.CallOptions).DeletePredictionApiKeyRegistration[0:len((*c.CallOptions).DeletePredictionApiKeyRegistration):len((*c.CallOptions).DeletePredictionApiKeyRegistration)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.predictionApiKeyRegistryClient.DeletePredictionApiKeyRegistration(ctx, req, settings.GRPC...) diff --git a/recommendationengine/apiv1beta1/prediction_api_key_registry_client_example_test.go b/recommendationengine/apiv1beta1/prediction_api_key_registry_client_example_test.go index 747f74a31ae6..db9b00eb2f5b 100644 --- a/recommendationengine/apiv1beta1/prediction_api_key_registry_client_example_test.go +++ b/recommendationengine/apiv1beta1/prediction_api_key_registry_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewPredictionApiKeyRegistryClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExamplePredictionApiKeyRegistryClient_CreatePredictionApiKeyRegistration() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewPredictionApiKeyRegistryClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.CreatePredictionApiKeyRegistrationRequest{ // TODO: Fill request struct fields. @@ -55,14 +56,12 @@ func ExamplePredictionApiKeyRegistryClient_CreatePredictionApiKeyRegistration() } func ExamplePredictionApiKeyRegistryClient_ListPredictionApiKeyRegistrations() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recommendationengine.NewPredictionApiKeyRegistryClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.ListPredictionApiKeyRegistrationsRequest{ // TODO: Fill request struct fields. @@ -87,6 +86,7 @@ func ExamplePredictionApiKeyRegistryClient_DeletePredictionApiKeyRegistration() if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.DeletePredictionApiKeyRegistrationRequest{ // TODO: Fill request struct fields. diff --git a/recommendationengine/apiv1beta1/prediction_client.go b/recommendationengine/apiv1beta1/prediction_client.go index e1c436fbaa3e..e0daba8f9d12 100644 --- a/recommendationengine/apiv1beta1/prediction_client.go +++ b/recommendationengine/apiv1beta1/prediction_client.go @@ -42,7 +42,7 @@ type PredictionCallOptions struct { Predict []gax.CallOption } -func defaultPredictionClientOptions() []option.ClientOption { +func defaultPredictionGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("recommendationengine.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("recommendationengine.mtls.googleapis.com:443"), @@ -71,32 +71,82 @@ func defaultPredictionCallOptions() *PredictionCallOptions { } } +// internalPredictionClient is an interface that defines the methods availaible from Recommendations AI. +type internalPredictionClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + Predict(context.Context, *recommendationenginepb.PredictRequest, ...gax.CallOption) *PredictResponse_PredictionResultIterator +} + // PredictionClient is a client for interacting with Recommendations AI. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for making recommendation prediction. type PredictionClient struct { + // The internal transport-dependent client. + internalClient internalPredictionClient + + // The call options for this service. + CallOptions *PredictionCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *PredictionClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *PredictionClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *PredictionClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// Predict makes a recommendation prediction. If using API Key based authentication, +// the API Key must be registered using the +// PredictionApiKeyRegistry +// service. Learn more (at /recommendations-ai/docs/setting-up#register-key). +func (c *PredictionClient) Predict(ctx context.Context, req *recommendationenginepb.PredictRequest, opts ...gax.CallOption) *PredictResponse_PredictionResultIterator { + return c.internalClient.Predict(ctx, req, opts...) +} + +// predictionGRPCClient is a client for interacting with Recommendations AI over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type predictionGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing PredictionClient + CallOptions **PredictionCallOptions + // The gRPC API client. predictionClient recommendationenginepb.PredictionServiceClient - // The call options for this service. - CallOptions *PredictionCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewPredictionClient creates a new prediction service client. +// NewPredictionClient creates a new prediction service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for making recommendation prediction. func NewPredictionClient(ctx context.Context, opts ...option.ClientOption) (*PredictionClient, error) { - clientOpts := defaultPredictionClientOptions() - + clientOpts := defaultPredictionGRPCClientOptions() if newPredictionClientHook != nil { hookOpts, err := newPredictionClientHook(ctx, clientHookParams{}) if err != nil { @@ -114,48 +164,47 @@ func NewPredictionClient(ctx context.Context, opts ...option.ClientOption) (*Pre if err != nil { return nil, err } - c := &PredictionClient{ + client := PredictionClient{CallOptions: defaultPredictionCallOptions()} + + c := &predictionGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultPredictionCallOptions(), - predictionClient: recommendationenginepb.NewPredictionServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *PredictionClient) Connection() *grpc.ClientConn { +func (c *predictionGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *PredictionClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *PredictionClient) setGoogleClientInfo(keyval ...string) { +func (c *predictionGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// Predict makes a recommendation prediction. If using API Key based authentication, -// the API Key must be registered using the -// PredictionApiKeyRegistry -// service. Learn more (at /recommendations-ai/docs/setting-up#register-key). -func (c *PredictionClient) Predict(ctx context.Context, req *recommendationenginepb.PredictRequest, opts ...gax.CallOption) *PredictResponse_PredictionResultIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *predictionGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *predictionGRPCClient) Predict(ctx context.Context, req *recommendationenginepb.PredictRequest, opts ...gax.CallOption) *PredictResponse_PredictionResultIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.Predict[0:len(c.CallOptions.Predict):len(c.CallOptions.Predict)], opts...) + opts = append((*c.CallOptions).Predict[0:len((*c.CallOptions).Predict):len((*c.CallOptions).Predict)], opts...) it := &PredictResponse_PredictionResultIterator{} req = proto.Clone(req).(*recommendationenginepb.PredictRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*recommendationenginepb.PredictResponse_PredictionResult, string, error) { diff --git a/recommendationengine/apiv1beta1/prediction_client_example_test.go b/recommendationengine/apiv1beta1/prediction_client_example_test.go index 7c98db896294..2a4e8e25e738 100644 --- a/recommendationengine/apiv1beta1/prediction_client_example_test.go +++ b/recommendationengine/apiv1beta1/prediction_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewPredictionClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExamplePredictionClient_Predict() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recommendationengine.NewPredictionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.PredictRequest{ // TODO: Fill request struct fields. diff --git a/recommendationengine/apiv1beta1/user_event_client.go b/recommendationengine/apiv1beta1/user_event_client.go index d6d5f67489c9..2cc81d4863c2 100644 --- a/recommendationengine/apiv1beta1/user_event_client.go +++ b/recommendationengine/apiv1beta1/user_event_client.go @@ -50,7 +50,7 @@ type UserEventCallOptions struct { ImportUserEvents []gax.CallOption } -func defaultUserEventClientOptions() []option.ClientOption { +func defaultUserEventGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("recommendationengine.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("recommendationengine.mtls.googleapis.com:443"), @@ -127,37 +127,140 @@ func defaultUserEventCallOptions() *UserEventCallOptions { } } +// internalUserEventClient is an interface that defines the methods availaible from Recommendations AI. +type internalUserEventClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + WriteUserEvent(context.Context, *recommendationenginepb.WriteUserEventRequest, ...gax.CallOption) (*recommendationenginepb.UserEvent, error) + CollectUserEvent(context.Context, *recommendationenginepb.CollectUserEventRequest, ...gax.CallOption) (*httpbodypb.HttpBody, error) + ListUserEvents(context.Context, *recommendationenginepb.ListUserEventsRequest, ...gax.CallOption) *UserEventIterator + PurgeUserEvents(context.Context, *recommendationenginepb.PurgeUserEventsRequest, ...gax.CallOption) (*PurgeUserEventsOperation, error) + PurgeUserEventsOperation(name string) *PurgeUserEventsOperation + ImportUserEvents(context.Context, *recommendationenginepb.ImportUserEventsRequest, ...gax.CallOption) (*ImportUserEventsOperation, error) + ImportUserEventsOperation(name string) *ImportUserEventsOperation +} + // UserEventClient is a client for interacting with Recommendations AI. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for ingesting end user actions on the customer website. type UserEventClient struct { + // The internal transport-dependent client. + internalClient internalUserEventClient + + // The call options for this service. + CallOptions *UserEventCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *UserEventClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *UserEventClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *UserEventClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// WriteUserEvent writes a single user event. +func (c *UserEventClient) WriteUserEvent(ctx context.Context, req *recommendationenginepb.WriteUserEventRequest, opts ...gax.CallOption) (*recommendationenginepb.UserEvent, error) { + return c.internalClient.WriteUserEvent(ctx, req, opts...) +} + +// CollectUserEvent writes a single user event from the browser. This uses a GET request to +// due to browser restriction of POST-ing to a 3rd party domain. +// +// This method is used only by the Recommendations AI JavaScript pixel. +// Users should not call this method directly. +func (c *UserEventClient) CollectUserEvent(ctx context.Context, req *recommendationenginepb.CollectUserEventRequest, opts ...gax.CallOption) (*httpbodypb.HttpBody, error) { + return c.internalClient.CollectUserEvent(ctx, req, opts...) +} + +// ListUserEvents gets a list of user events within a time range, with potential filtering. +func (c *UserEventClient) ListUserEvents(ctx context.Context, req *recommendationenginepb.ListUserEventsRequest, opts ...gax.CallOption) *UserEventIterator { + return c.internalClient.ListUserEvents(ctx, req, opts...) +} + +// PurgeUserEvents deletes permanently all user events specified by the filter provided. +// Depending on the number of events specified by the filter, this operation +// could take hours or days to complete. To test a filter, use the list +// command first. +func (c *UserEventClient) PurgeUserEvents(ctx context.Context, req *recommendationenginepb.PurgeUserEventsRequest, opts ...gax.CallOption) (*PurgeUserEventsOperation, error) { + return c.internalClient.PurgeUserEvents(ctx, req, opts...) +} + +// PurgeUserEventsOperation returns a new PurgeUserEventsOperation from a given name. +// The name must be that of a previously created PurgeUserEventsOperation, possibly from a different process. +func (c *UserEventClient) PurgeUserEventsOperation(name string) *PurgeUserEventsOperation { + return c.internalClient.PurgeUserEventsOperation(name) +} + +// ImportUserEvents bulk import of User events. Request processing might be +// synchronous. Events that already exist are skipped. +// Use this method for backfilling historical user events. +// +// Operation.response is of type ImportResponse. Note that it is +// possible for a subset of the items to be successfully inserted. +// Operation.metadata is of type ImportMetadata. +func (c *UserEventClient) ImportUserEvents(ctx context.Context, req *recommendationenginepb.ImportUserEventsRequest, opts ...gax.CallOption) (*ImportUserEventsOperation, error) { + return c.internalClient.ImportUserEvents(ctx, req, opts...) +} + +// ImportUserEventsOperation returns a new ImportUserEventsOperation from a given name. +// The name must be that of a previously created ImportUserEventsOperation, possibly from a different process. +func (c *UserEventClient) ImportUserEventsOperation(name string) *ImportUserEventsOperation { + return c.internalClient.ImportUserEventsOperation(name) +} + +// userEventGRPCClient is a client for interacting with Recommendations AI over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type userEventGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing UserEventClient + CallOptions **UserEventCallOptions + // The gRPC API client. userEventClient recommendationenginepb.UserEventServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *UserEventCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewUserEventClient creates a new user event service client. +// NewUserEventClient creates a new user event service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for ingesting end user actions on the customer website. func NewUserEventClient(ctx context.Context, opts ...option.ClientOption) (*UserEventClient, error) { - clientOpts := defaultUserEventClientOptions() - + clientOpts := defaultUserEventGRPCClientOptions() if newUserEventClientHook != nil { hookOpts, err := newUserEventClientHook(ctx, clientHookParams{}) if err != nil { @@ -175,16 +278,19 @@ func NewUserEventClient(ctx context.Context, opts ...option.ClientOption) (*User if err != nil { return nil, err } - c := &UserEventClient{ + client := UserEventClient{CallOptions: defaultUserEventCallOptions()} + + c := &userEventGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultUserEventCallOptions(), - - userEventClient: recommendationenginepb.NewUserEventServiceClient(connPool), + userEventClient: recommendationenginepb.NewUserEventServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -194,33 +300,33 @@ func NewUserEventClient(ctx context.Context, opts ...option.ClientOption) (*User // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *UserEventClient) Connection() *grpc.ClientConn { +func (c *userEventGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *UserEventClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *UserEventClient) setGoogleClientInfo(keyval ...string) { +func (c *userEventGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// WriteUserEvent writes a single user event. -func (c *UserEventClient) WriteUserEvent(ctx context.Context, req *recommendationenginepb.WriteUserEventRequest, opts ...gax.CallOption) (*recommendationenginepb.UserEvent, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *userEventGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *userEventGRPCClient) WriteUserEvent(ctx context.Context, req *recommendationenginepb.WriteUserEventRequest, opts ...gax.CallOption) (*recommendationenginepb.UserEvent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -228,7 +334,7 @@ func (c *UserEventClient) WriteUserEvent(ctx context.Context, req *recommendatio } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.WriteUserEvent[0:len(c.CallOptions.WriteUserEvent):len(c.CallOptions.WriteUserEvent)], opts...) + opts = append((*c.CallOptions).WriteUserEvent[0:len((*c.CallOptions).WriteUserEvent):len((*c.CallOptions).WriteUserEvent)], opts...) var resp *recommendationenginepb.UserEvent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -241,12 +347,7 @@ func (c *UserEventClient) WriteUserEvent(ctx context.Context, req *recommendatio return resp, nil } -// CollectUserEvent writes a single user event from the browser. This uses a GET request to -// due to browser restriction of POST-ing to a 3rd party domain. -// -// This method is used only by the Recommendations AI JavaScript pixel. -// Users should not call this method directly. -func (c *UserEventClient) CollectUserEvent(ctx context.Context, req *recommendationenginepb.CollectUserEventRequest, opts ...gax.CallOption) (*httpbodypb.HttpBody, error) { +func (c *userEventGRPCClient) CollectUserEvent(ctx context.Context, req *recommendationenginepb.CollectUserEventRequest, opts ...gax.CallOption) (*httpbodypb.HttpBody, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -254,7 +355,7 @@ func (c *UserEventClient) CollectUserEvent(ctx context.Context, req *recommendat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CollectUserEvent[0:len(c.CallOptions.CollectUserEvent):len(c.CallOptions.CollectUserEvent)], opts...) + opts = append((*c.CallOptions).CollectUserEvent[0:len((*c.CallOptions).CollectUserEvent):len((*c.CallOptions).CollectUserEvent)], opts...) var resp *httpbodypb.HttpBody err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -267,11 +368,10 @@ func (c *UserEventClient) CollectUserEvent(ctx context.Context, req *recommendat return resp, nil } -// ListUserEvents gets a list of user events within a time range, with potential filtering. -func (c *UserEventClient) ListUserEvents(ctx context.Context, req *recommendationenginepb.ListUserEventsRequest, opts ...gax.CallOption) *UserEventIterator { +func (c *userEventGRPCClient) ListUserEvents(ctx context.Context, req *recommendationenginepb.ListUserEventsRequest, opts ...gax.CallOption) *UserEventIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListUserEvents[0:len(c.CallOptions.ListUserEvents):len(c.CallOptions.ListUserEvents)], opts...) + opts = append((*c.CallOptions).ListUserEvents[0:len((*c.CallOptions).ListUserEvents):len((*c.CallOptions).ListUserEvents)], opts...) it := &UserEventIterator{} req = proto.Clone(req).(*recommendationenginepb.ListUserEventsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*recommendationenginepb.UserEvent, string, error) { @@ -308,11 +408,7 @@ func (c *UserEventClient) ListUserEvents(ctx context.Context, req *recommendatio return it } -// PurgeUserEvents deletes permanently all user events specified by the filter provided. -// Depending on the number of events specified by the filter, this operation -// could take hours or days to complete. To test a filter, use the list -// command first. -func (c *UserEventClient) PurgeUserEvents(ctx context.Context, req *recommendationenginepb.PurgeUserEventsRequest, opts ...gax.CallOption) (*PurgeUserEventsOperation, error) { +func (c *userEventGRPCClient) PurgeUserEvents(ctx context.Context, req *recommendationenginepb.PurgeUserEventsRequest, opts ...gax.CallOption) (*PurgeUserEventsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -320,7 +416,7 @@ func (c *UserEventClient) PurgeUserEvents(ctx context.Context, req *recommendati } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PurgeUserEvents[0:len(c.CallOptions.PurgeUserEvents):len(c.CallOptions.PurgeUserEvents)], opts...) + opts = append((*c.CallOptions).PurgeUserEvents[0:len((*c.CallOptions).PurgeUserEvents):len((*c.CallOptions).PurgeUserEvents)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -331,18 +427,11 @@ func (c *UserEventClient) PurgeUserEvents(ctx context.Context, req *recommendati return nil, err } return &PurgeUserEventsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ImportUserEvents bulk import of User events. Request processing might be -// synchronous. Events that already exist are skipped. -// Use this method for backfilling historical user events. -// -// Operation.response is of type ImportResponse. Note that it is -// possible for a subset of the items to be successfully inserted. -// Operation.metadata is of type ImportMetadata. -func (c *UserEventClient) ImportUserEvents(ctx context.Context, req *recommendationenginepb.ImportUserEventsRequest, opts ...gax.CallOption) (*ImportUserEventsOperation, error) { +func (c *userEventGRPCClient) ImportUserEvents(ctx context.Context, req *recommendationenginepb.ImportUserEventsRequest, opts ...gax.CallOption) (*ImportUserEventsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -350,7 +439,7 @@ func (c *UserEventClient) ImportUserEvents(ctx context.Context, req *recommendat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportUserEvents[0:len(c.CallOptions.ImportUserEvents):len(c.CallOptions.ImportUserEvents)], opts...) + opts = append((*c.CallOptions).ImportUserEvents[0:len((*c.CallOptions).ImportUserEvents):len((*c.CallOptions).ImportUserEvents)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -361,7 +450,7 @@ func (c *UserEventClient) ImportUserEvents(ctx context.Context, req *recommendat return nil, err } return &ImportUserEventsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -372,9 +461,9 @@ type ImportUserEventsOperation struct { // ImportUserEventsOperation returns a new ImportUserEventsOperation from a given name. // The name must be that of a previously created ImportUserEventsOperation, possibly from a different process. -func (c *UserEventClient) ImportUserEventsOperation(name string) *ImportUserEventsOperation { +func (c *userEventGRPCClient) ImportUserEventsOperation(name string) *ImportUserEventsOperation { return &ImportUserEventsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -441,9 +530,9 @@ type PurgeUserEventsOperation struct { // PurgeUserEventsOperation returns a new PurgeUserEventsOperation from a given name. // The name must be that of a previously created PurgeUserEventsOperation, possibly from a different process. -func (c *UserEventClient) PurgeUserEventsOperation(name string) *PurgeUserEventsOperation { +func (c *userEventGRPCClient) PurgeUserEventsOperation(name string) *PurgeUserEventsOperation { return &PurgeUserEventsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/recommendationengine/apiv1beta1/user_event_client_example_test.go b/recommendationengine/apiv1beta1/user_event_client_example_test.go index aac99c8a04e9..876345892c02 100644 --- a/recommendationengine/apiv1beta1/user_event_client_example_test.go +++ b/recommendationengine/apiv1beta1/user_event_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewUserEventClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleUserEventClient_WriteUserEvent() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.WriteUserEventRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleUserEventClient_WriteUserEvent() { } func ExampleUserEventClient_CollectUserEvent() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.CollectUserEventRequest{ // TODO: Fill request struct fields. @@ -75,14 +75,12 @@ func ExampleUserEventClient_CollectUserEvent() { } func ExampleUserEventClient_ListUserEvents() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recommendationengine.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.ListUserEventsRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleUserEventClient_ListUserEvents() { } func ExampleUserEventClient_PurgeUserEvents() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.PurgeUserEventsRequest{ // TODO: Fill request struct fields. @@ -127,13 +124,12 @@ func ExampleUserEventClient_PurgeUserEvents() { } func ExampleUserEventClient_ImportUserEvents() { - // import recommendationenginepb "google.golang.org/genproto/googleapis/cloud/recommendationengine/v1beta1" - ctx := context.Background() c, err := recommendationengine.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommendationenginepb.ImportUserEventsRequest{ // TODO: Fill request struct fields. diff --git a/recommender/apiv1/doc.go b/recommender/apiv1/doc.go index 98c7edbba3b0..e4d7d2fc26ba 100644 --- a/recommender/apiv1/doc.go +++ b/recommender/apiv1/doc.go @@ -26,7 +26,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package recommender // import "cloud.google.com/go/recommender/apiv1" import ( @@ -46,7 +46,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/recommender/apiv1/recommender_client.go b/recommender/apiv1/recommender_client.go index e3e23dd4224b..2b1fed39e437 100644 --- a/recommender/apiv1/recommender_client.go +++ b/recommender/apiv1/recommender_client.go @@ -49,7 +49,7 @@ type CallOptions struct { MarkRecommendationFailed []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("recommender.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("recommender.mtls.googleapis.com:443"), @@ -118,35 +118,165 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Recommender API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListInsights(context.Context, *recommenderpb.ListInsightsRequest, ...gax.CallOption) *InsightIterator + GetInsight(context.Context, *recommenderpb.GetInsightRequest, ...gax.CallOption) (*recommenderpb.Insight, error) + MarkInsightAccepted(context.Context, *recommenderpb.MarkInsightAcceptedRequest, ...gax.CallOption) (*recommenderpb.Insight, error) + ListRecommendations(context.Context, *recommenderpb.ListRecommendationsRequest, ...gax.CallOption) *RecommendationIterator + GetRecommendation(context.Context, *recommenderpb.GetRecommendationRequest, ...gax.CallOption) (*recommenderpb.Recommendation, error) + MarkRecommendationClaimed(context.Context, *recommenderpb.MarkRecommendationClaimedRequest, ...gax.CallOption) (*recommenderpb.Recommendation, error) + MarkRecommendationSucceeded(context.Context, *recommenderpb.MarkRecommendationSucceededRequest, ...gax.CallOption) (*recommenderpb.Recommendation, error) + MarkRecommendationFailed(context.Context, *recommenderpb.MarkRecommendationFailedRequest, ...gax.CallOption) (*recommenderpb.Recommendation, error) +} + // Client is a client for interacting with Recommender API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Provides insights and recommendations for cloud customers for various +// categories like performance optimization, cost savings, reliability, feature +// discovery, etc. Insights and recommendations are generated automatically +// based on analysis of user resources, configuration and monitoring metrics. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListInsights lists insights for a Cloud project. Requires the recommender.*.list IAM +// permission for the specified insight type. +func (c *Client) ListInsights(ctx context.Context, req *recommenderpb.ListInsightsRequest, opts ...gax.CallOption) *InsightIterator { + return c.internalClient.ListInsights(ctx, req, opts...) +} + +// GetInsight gets the requested insight. Requires the recommender.*.get IAM permission +// for the specified insight type. +func (c *Client) GetInsight(ctx context.Context, req *recommenderpb.GetInsightRequest, opts ...gax.CallOption) (*recommenderpb.Insight, error) { + return c.internalClient.GetInsight(ctx, req, opts...) +} + +// MarkInsightAccepted marks the Insight State as Accepted. Users can use this method to +// indicate to the Recommender API that they have applied some action based +// on the insight. This stops the insight content from being updated. +// +// MarkInsightAccepted can be applied to insights in ACTIVE state. Requires +// the recommender.*.update IAM permission for the specified insight. +func (c *Client) MarkInsightAccepted(ctx context.Context, req *recommenderpb.MarkInsightAcceptedRequest, opts ...gax.CallOption) (*recommenderpb.Insight, error) { + return c.internalClient.MarkInsightAccepted(ctx, req, opts...) +} + +// ListRecommendations lists recommendations for a Cloud project. Requires the recommender.*.list +// IAM permission for the specified recommender. +func (c *Client) ListRecommendations(ctx context.Context, req *recommenderpb.ListRecommendationsRequest, opts ...gax.CallOption) *RecommendationIterator { + return c.internalClient.ListRecommendations(ctx, req, opts...) +} + +// GetRecommendation gets the requested recommendation. Requires the recommender.*.get +// IAM permission for the specified recommender. +func (c *Client) GetRecommendation(ctx context.Context, req *recommenderpb.GetRecommendationRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { + return c.internalClient.GetRecommendation(ctx, req, opts...) +} + +// MarkRecommendationClaimed marks the Recommendation State as Claimed. Users can use this method to +// indicate to the Recommender API that they are starting to apply the +// recommendation themselves. This stops the recommendation content from being +// updated. Associated insights are frozen and placed in the ACCEPTED state. +// +// MarkRecommendationClaimed can be applied to recommendations in CLAIMED, +// SUCCEEDED, FAILED, or ACTIVE state. +// +// Requires the recommender.*.update IAM permission for the specified +// recommender. +func (c *Client) MarkRecommendationClaimed(ctx context.Context, req *recommenderpb.MarkRecommendationClaimedRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { + return c.internalClient.MarkRecommendationClaimed(ctx, req, opts...) +} + +// MarkRecommendationSucceeded marks the Recommendation State as Succeeded. Users can use this method to +// indicate to the Recommender API that they have applied the recommendation +// themselves, and the operation was successful. This stops the recommendation +// content from being updated. Associated insights are frozen and placed in +// the ACCEPTED state. +// +// MarkRecommendationSucceeded can be applied to recommendations in ACTIVE, +// CLAIMED, SUCCEEDED, or FAILED state. +// +// Requires the recommender.*.update IAM permission for the specified +// recommender. +func (c *Client) MarkRecommendationSucceeded(ctx context.Context, req *recommenderpb.MarkRecommendationSucceededRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { + return c.internalClient.MarkRecommendationSucceeded(ctx, req, opts...) +} + +// MarkRecommendationFailed marks the Recommendation State as Failed. Users can use this method to +// indicate to the Recommender API that they have applied the recommendation +// themselves, and the operation failed. This stops the recommendation content +// from being updated. Associated insights are frozen and placed in the +// ACCEPTED state. +// +// MarkRecommendationFailed can be applied to recommendations in ACTIVE, +// CLAIMED, SUCCEEDED, or FAILED state. +// +// Requires the recommender.*.update IAM permission for the specified +// recommender. +func (c *Client) MarkRecommendationFailed(ctx context.Context, req *recommenderpb.MarkRecommendationFailedRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { + return c.internalClient.MarkRecommendationFailed(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Recommender API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client recommenderpb.RecommenderClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new recommender client. +// NewClient creates a new recommender client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Provides insights and recommendations for cloud customers for various // categories like performance optimization, cost savings, reliability, feature // discovery, etc. Insights and recommendations are generated automatically // based on analysis of user resources, configuration and monitoring metrics. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -164,46 +294,47 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: recommenderpb.NewRecommenderClient(connPool), + client: recommenderpb.NewRecommenderClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListInsights lists insights for a Cloud project. Requires the recommender.*.list IAM -// permission for the specified insight type. -func (c *Client) ListInsights(ctx context.Context, req *recommenderpb.ListInsightsRequest, opts ...gax.CallOption) *InsightIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ListInsights(ctx context.Context, req *recommenderpb.ListInsightsRequest, opts ...gax.CallOption) *InsightIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListInsights[0:len(c.CallOptions.ListInsights):len(c.CallOptions.ListInsights)], opts...) + opts = append((*c.CallOptions).ListInsights[0:len((*c.CallOptions).ListInsights):len((*c.CallOptions).ListInsights)], opts...) it := &InsightIterator{} req = proto.Clone(req).(*recommenderpb.ListInsightsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*recommenderpb.Insight, string, error) { @@ -240,9 +371,7 @@ func (c *Client) ListInsights(ctx context.Context, req *recommenderpb.ListInsigh return it } -// GetInsight gets the requested insight. Requires the recommender.*.get IAM permission -// for the specified insight type. -func (c *Client) GetInsight(ctx context.Context, req *recommenderpb.GetInsightRequest, opts ...gax.CallOption) (*recommenderpb.Insight, error) { +func (c *gRPCClient) GetInsight(ctx context.Context, req *recommenderpb.GetInsightRequest, opts ...gax.CallOption) (*recommenderpb.Insight, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -250,7 +379,7 @@ func (c *Client) GetInsight(ctx context.Context, req *recommenderpb.GetInsightRe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetInsight[0:len(c.CallOptions.GetInsight):len(c.CallOptions.GetInsight)], opts...) + opts = append((*c.CallOptions).GetInsight[0:len((*c.CallOptions).GetInsight):len((*c.CallOptions).GetInsight)], opts...) var resp *recommenderpb.Insight err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -263,13 +392,7 @@ func (c *Client) GetInsight(ctx context.Context, req *recommenderpb.GetInsightRe return resp, nil } -// MarkInsightAccepted marks the Insight State as Accepted. Users can use this method to -// indicate to the Recommender API that they have applied some action based -// on the insight. This stops the insight content from being updated. -// -// MarkInsightAccepted can be applied to insights in ACTIVE state. Requires -// the recommender.*.update IAM permission for the specified insight. -func (c *Client) MarkInsightAccepted(ctx context.Context, req *recommenderpb.MarkInsightAcceptedRequest, opts ...gax.CallOption) (*recommenderpb.Insight, error) { +func (c *gRPCClient) MarkInsightAccepted(ctx context.Context, req *recommenderpb.MarkInsightAcceptedRequest, opts ...gax.CallOption) (*recommenderpb.Insight, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -277,7 +400,7 @@ func (c *Client) MarkInsightAccepted(ctx context.Context, req *recommenderpb.Mar } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.MarkInsightAccepted[0:len(c.CallOptions.MarkInsightAccepted):len(c.CallOptions.MarkInsightAccepted)], opts...) + opts = append((*c.CallOptions).MarkInsightAccepted[0:len((*c.CallOptions).MarkInsightAccepted):len((*c.CallOptions).MarkInsightAccepted)], opts...) var resp *recommenderpb.Insight err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -290,12 +413,10 @@ func (c *Client) MarkInsightAccepted(ctx context.Context, req *recommenderpb.Mar return resp, nil } -// ListRecommendations lists recommendations for a Cloud project. Requires the recommender.*.list -// IAM permission for the specified recommender. -func (c *Client) ListRecommendations(ctx context.Context, req *recommenderpb.ListRecommendationsRequest, opts ...gax.CallOption) *RecommendationIterator { +func (c *gRPCClient) ListRecommendations(ctx context.Context, req *recommenderpb.ListRecommendationsRequest, opts ...gax.CallOption) *RecommendationIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListRecommendations[0:len(c.CallOptions.ListRecommendations):len(c.CallOptions.ListRecommendations)], opts...) + opts = append((*c.CallOptions).ListRecommendations[0:len((*c.CallOptions).ListRecommendations):len((*c.CallOptions).ListRecommendations)], opts...) it := &RecommendationIterator{} req = proto.Clone(req).(*recommenderpb.ListRecommendationsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*recommenderpb.Recommendation, string, error) { @@ -332,9 +453,7 @@ func (c *Client) ListRecommendations(ctx context.Context, req *recommenderpb.Lis return it } -// GetRecommendation gets the requested recommendation. Requires the recommender.*.get -// IAM permission for the specified recommender. -func (c *Client) GetRecommendation(ctx context.Context, req *recommenderpb.GetRecommendationRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { +func (c *gRPCClient) GetRecommendation(ctx context.Context, req *recommenderpb.GetRecommendationRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -342,7 +461,7 @@ func (c *Client) GetRecommendation(ctx context.Context, req *recommenderpb.GetRe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetRecommendation[0:len(c.CallOptions.GetRecommendation):len(c.CallOptions.GetRecommendation)], opts...) + opts = append((*c.CallOptions).GetRecommendation[0:len((*c.CallOptions).GetRecommendation):len((*c.CallOptions).GetRecommendation)], opts...) var resp *recommenderpb.Recommendation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -355,17 +474,7 @@ func (c *Client) GetRecommendation(ctx context.Context, req *recommenderpb.GetRe return resp, nil } -// MarkRecommendationClaimed marks the Recommendation State as Claimed. Users can use this method to -// indicate to the Recommender API that they are starting to apply the -// recommendation themselves. This stops the recommendation content from being -// updated. Associated insights are frozen and placed in the ACCEPTED state. -// -// MarkRecommendationClaimed can be applied to recommendations in CLAIMED, -// SUCCEEDED, FAILED, or ACTIVE state. -// -// Requires the recommender.*.update IAM permission for the specified -// recommender. -func (c *Client) MarkRecommendationClaimed(ctx context.Context, req *recommenderpb.MarkRecommendationClaimedRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { +func (c *gRPCClient) MarkRecommendationClaimed(ctx context.Context, req *recommenderpb.MarkRecommendationClaimedRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -373,7 +482,7 @@ func (c *Client) MarkRecommendationClaimed(ctx context.Context, req *recommender } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.MarkRecommendationClaimed[0:len(c.CallOptions.MarkRecommendationClaimed):len(c.CallOptions.MarkRecommendationClaimed)], opts...) + opts = append((*c.CallOptions).MarkRecommendationClaimed[0:len((*c.CallOptions).MarkRecommendationClaimed):len((*c.CallOptions).MarkRecommendationClaimed)], opts...) var resp *recommenderpb.Recommendation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -386,18 +495,7 @@ func (c *Client) MarkRecommendationClaimed(ctx context.Context, req *recommender return resp, nil } -// MarkRecommendationSucceeded marks the Recommendation State as Succeeded. Users can use this method to -// indicate to the Recommender API that they have applied the recommendation -// themselves, and the operation was successful. This stops the recommendation -// content from being updated. Associated insights are frozen and placed in -// the ACCEPTED state. -// -// MarkRecommendationSucceeded can be applied to recommendations in ACTIVE, -// CLAIMED, SUCCEEDED, or FAILED state. -// -// Requires the recommender.*.update IAM permission for the specified -// recommender. -func (c *Client) MarkRecommendationSucceeded(ctx context.Context, req *recommenderpb.MarkRecommendationSucceededRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { +func (c *gRPCClient) MarkRecommendationSucceeded(ctx context.Context, req *recommenderpb.MarkRecommendationSucceededRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -405,7 +503,7 @@ func (c *Client) MarkRecommendationSucceeded(ctx context.Context, req *recommend } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.MarkRecommendationSucceeded[0:len(c.CallOptions.MarkRecommendationSucceeded):len(c.CallOptions.MarkRecommendationSucceeded)], opts...) + opts = append((*c.CallOptions).MarkRecommendationSucceeded[0:len((*c.CallOptions).MarkRecommendationSucceeded):len((*c.CallOptions).MarkRecommendationSucceeded)], opts...) var resp *recommenderpb.Recommendation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -418,18 +516,7 @@ func (c *Client) MarkRecommendationSucceeded(ctx context.Context, req *recommend return resp, nil } -// MarkRecommendationFailed marks the Recommendation State as Failed. Users can use this method to -// indicate to the Recommender API that they have applied the recommendation -// themselves, and the operation failed. This stops the recommendation content -// from being updated. Associated insights are frozen and placed in the -// ACCEPTED state. -// -// MarkRecommendationFailed can be applied to recommendations in ACTIVE, -// CLAIMED, SUCCEEDED, or FAILED state. -// -// Requires the recommender.*.update IAM permission for the specified -// recommender. -func (c *Client) MarkRecommendationFailed(ctx context.Context, req *recommenderpb.MarkRecommendationFailedRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { +func (c *gRPCClient) MarkRecommendationFailed(ctx context.Context, req *recommenderpb.MarkRecommendationFailedRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -437,7 +524,7 @@ func (c *Client) MarkRecommendationFailed(ctx context.Context, req *recommenderp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.MarkRecommendationFailed[0:len(c.CallOptions.MarkRecommendationFailed):len(c.CallOptions.MarkRecommendationFailed)], opts...) + opts = append((*c.CallOptions).MarkRecommendationFailed[0:len((*c.CallOptions).MarkRecommendationFailed):len((*c.CallOptions).MarkRecommendationFailed)], opts...) var resp *recommenderpb.Recommendation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/recommender/apiv1/recommender_client_example_test.go b/recommender/apiv1/recommender_client_example_test.go index 8af6b520eb11..c3b9fe70a908 100644 --- a/recommender/apiv1/recommender_client_example_test.go +++ b/recommender/apiv1/recommender_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ListInsights() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.ListInsightsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleClient_ListInsights() { } func ExampleClient_GetInsight() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.GetInsightRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleClient_GetInsight() { } func ExampleClient_MarkInsightAccepted() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.MarkInsightAcceptedRequest{ // TODO: Fill request struct fields. @@ -102,14 +100,12 @@ func ExampleClient_MarkInsightAccepted() { } func ExampleClient_ListRecommendations() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.ListRecommendationsRequest{ // TODO: Fill request struct fields. @@ -129,13 +125,12 @@ func ExampleClient_ListRecommendations() { } func ExampleClient_GetRecommendation() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.GetRecommendationRequest{ // TODO: Fill request struct fields. @@ -149,13 +144,12 @@ func ExampleClient_GetRecommendation() { } func ExampleClient_MarkRecommendationClaimed() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.MarkRecommendationClaimedRequest{ // TODO: Fill request struct fields. @@ -169,13 +163,12 @@ func ExampleClient_MarkRecommendationClaimed() { } func ExampleClient_MarkRecommendationSucceeded() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.MarkRecommendationSucceededRequest{ // TODO: Fill request struct fields. @@ -189,13 +182,12 @@ func ExampleClient_MarkRecommendationSucceeded() { } func ExampleClient_MarkRecommendationFailed() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.MarkRecommendationFailedRequest{ // TODO: Fill request struct fields. diff --git a/recommender/apiv1beta1/doc.go b/recommender/apiv1beta1/doc.go index 9ee53662cc60..3664b8b6204e 100644 --- a/recommender/apiv1beta1/doc.go +++ b/recommender/apiv1beta1/doc.go @@ -17,6 +17,8 @@ // Package recommender is an auto-generated package for the // Recommender API. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -26,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package recommender // import "cloud.google.com/go/recommender/apiv1beta1" import ( @@ -46,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/recommender/apiv1beta1/recommender_client.go b/recommender/apiv1beta1/recommender_client.go index d43be24bf78f..1ebcc5766ecc 100644 --- a/recommender/apiv1beta1/recommender_client.go +++ b/recommender/apiv1beta1/recommender_client.go @@ -49,7 +49,7 @@ type CallOptions struct { MarkRecommendationFailed []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("recommender.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("recommender.mtls.googleapis.com:443"), @@ -118,35 +118,165 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Recommender API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListInsights(context.Context, *recommenderpb.ListInsightsRequest, ...gax.CallOption) *InsightIterator + GetInsight(context.Context, *recommenderpb.GetInsightRequest, ...gax.CallOption) (*recommenderpb.Insight, error) + MarkInsightAccepted(context.Context, *recommenderpb.MarkInsightAcceptedRequest, ...gax.CallOption) (*recommenderpb.Insight, error) + ListRecommendations(context.Context, *recommenderpb.ListRecommendationsRequest, ...gax.CallOption) *RecommendationIterator + GetRecommendation(context.Context, *recommenderpb.GetRecommendationRequest, ...gax.CallOption) (*recommenderpb.Recommendation, error) + MarkRecommendationClaimed(context.Context, *recommenderpb.MarkRecommendationClaimedRequest, ...gax.CallOption) (*recommenderpb.Recommendation, error) + MarkRecommendationSucceeded(context.Context, *recommenderpb.MarkRecommendationSucceededRequest, ...gax.CallOption) (*recommenderpb.Recommendation, error) + MarkRecommendationFailed(context.Context, *recommenderpb.MarkRecommendationFailedRequest, ...gax.CallOption) (*recommenderpb.Recommendation, error) +} + // Client is a client for interacting with Recommender API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Provides insights and recommendations for cloud customers for various +// categories like performance optimization, cost savings, reliability, feature +// discovery, etc. Insights and recommendations are generated automatically +// based on analysis of user resources, configuration and monitoring metrics. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListInsights lists insights for a Cloud project. Requires the recommender.*.list IAM +// permission for the specified insight type. +func (c *Client) ListInsights(ctx context.Context, req *recommenderpb.ListInsightsRequest, opts ...gax.CallOption) *InsightIterator { + return c.internalClient.ListInsights(ctx, req, opts...) +} + +// GetInsight gets the requested insight. Requires the recommender.*.get IAM permission +// for the specified insight type. +func (c *Client) GetInsight(ctx context.Context, req *recommenderpb.GetInsightRequest, opts ...gax.CallOption) (*recommenderpb.Insight, error) { + return c.internalClient.GetInsight(ctx, req, opts...) +} + +// MarkInsightAccepted marks the Insight State as Accepted. Users can use this method to +// indicate to the Recommender API that they have applied some action based +// on the insight. This stops the insight content from being updated. +// +// MarkInsightAccepted can be applied to insights in ACTIVE state. Requires +// the recommender.*.update IAM permission for the specified insight. +func (c *Client) MarkInsightAccepted(ctx context.Context, req *recommenderpb.MarkInsightAcceptedRequest, opts ...gax.CallOption) (*recommenderpb.Insight, error) { + return c.internalClient.MarkInsightAccepted(ctx, req, opts...) +} + +// ListRecommendations lists recommendations for a Cloud project. Requires the recommender.*.list +// IAM permission for the specified recommender. +func (c *Client) ListRecommendations(ctx context.Context, req *recommenderpb.ListRecommendationsRequest, opts ...gax.CallOption) *RecommendationIterator { + return c.internalClient.ListRecommendations(ctx, req, opts...) +} + +// GetRecommendation gets the requested recommendation. Requires the recommender.*.get +// IAM permission for the specified recommender. +func (c *Client) GetRecommendation(ctx context.Context, req *recommenderpb.GetRecommendationRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { + return c.internalClient.GetRecommendation(ctx, req, opts...) +} + +// MarkRecommendationClaimed marks the Recommendation State as Claimed. Users can use this method to +// indicate to the Recommender API that they are starting to apply the +// recommendation themselves. This stops the recommendation content from being +// updated. Associated insights are frozen and placed in the ACCEPTED state. +// +// MarkRecommendationClaimed can be applied to recommendations in CLAIMED or +// ACTIVE state. +// +// Requires the recommender.*.update IAM permission for the specified +// recommender. +func (c *Client) MarkRecommendationClaimed(ctx context.Context, req *recommenderpb.MarkRecommendationClaimedRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { + return c.internalClient.MarkRecommendationClaimed(ctx, req, opts...) +} + +// MarkRecommendationSucceeded marks the Recommendation State as Succeeded. Users can use this method to +// indicate to the Recommender API that they have applied the recommendation +// themselves, and the operation was successful. This stops the recommendation +// content from being updated. Associated insights are frozen and placed in +// the ACCEPTED state. +// +// MarkRecommendationSucceeded can be applied to recommendations in ACTIVE, +// CLAIMED, SUCCEEDED, or FAILED state. +// +// Requires the recommender.*.update IAM permission for the specified +// recommender. +func (c *Client) MarkRecommendationSucceeded(ctx context.Context, req *recommenderpb.MarkRecommendationSucceededRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { + return c.internalClient.MarkRecommendationSucceeded(ctx, req, opts...) +} + +// MarkRecommendationFailed marks the Recommendation State as Failed. Users can use this method to +// indicate to the Recommender API that they have applied the recommendation +// themselves, and the operation failed. This stops the recommendation content +// from being updated. Associated insights are frozen and placed in the +// ACCEPTED state. +// +// MarkRecommendationFailed can be applied to recommendations in ACTIVE, +// CLAIMED, SUCCEEDED, or FAILED state. +// +// Requires the recommender.*.update IAM permission for the specified +// recommender. +func (c *Client) MarkRecommendationFailed(ctx context.Context, req *recommenderpb.MarkRecommendationFailedRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { + return c.internalClient.MarkRecommendationFailed(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Recommender API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client recommenderpb.RecommenderClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new recommender client. +// NewClient creates a new recommender client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Provides insights and recommendations for cloud customers for various // categories like performance optimization, cost savings, reliability, feature // discovery, etc. Insights and recommendations are generated automatically // based on analysis of user resources, configuration and monitoring metrics. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -164,46 +294,47 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: recommenderpb.NewRecommenderClient(connPool), + client: recommenderpb.NewRecommenderClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListInsights lists insights for a Cloud project. Requires the recommender.*.list IAM -// permission for the specified insight type. -func (c *Client) ListInsights(ctx context.Context, req *recommenderpb.ListInsightsRequest, opts ...gax.CallOption) *InsightIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ListInsights(ctx context.Context, req *recommenderpb.ListInsightsRequest, opts ...gax.CallOption) *InsightIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListInsights[0:len(c.CallOptions.ListInsights):len(c.CallOptions.ListInsights)], opts...) + opts = append((*c.CallOptions).ListInsights[0:len((*c.CallOptions).ListInsights):len((*c.CallOptions).ListInsights)], opts...) it := &InsightIterator{} req = proto.Clone(req).(*recommenderpb.ListInsightsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*recommenderpb.Insight, string, error) { @@ -240,9 +371,7 @@ func (c *Client) ListInsights(ctx context.Context, req *recommenderpb.ListInsigh return it } -// GetInsight gets the requested insight. Requires the recommender.*.get IAM permission -// for the specified insight type. -func (c *Client) GetInsight(ctx context.Context, req *recommenderpb.GetInsightRequest, opts ...gax.CallOption) (*recommenderpb.Insight, error) { +func (c *gRPCClient) GetInsight(ctx context.Context, req *recommenderpb.GetInsightRequest, opts ...gax.CallOption) (*recommenderpb.Insight, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -250,7 +379,7 @@ func (c *Client) GetInsight(ctx context.Context, req *recommenderpb.GetInsightRe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetInsight[0:len(c.CallOptions.GetInsight):len(c.CallOptions.GetInsight)], opts...) + opts = append((*c.CallOptions).GetInsight[0:len((*c.CallOptions).GetInsight):len((*c.CallOptions).GetInsight)], opts...) var resp *recommenderpb.Insight err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -263,13 +392,7 @@ func (c *Client) GetInsight(ctx context.Context, req *recommenderpb.GetInsightRe return resp, nil } -// MarkInsightAccepted marks the Insight State as Accepted. Users can use this method to -// indicate to the Recommender API that they have applied some action based -// on the insight. This stops the insight content from being updated. -// -// MarkInsightAccepted can be applied to insights in ACTIVE state. Requires -// the recommender.*.update IAM permission for the specified insight. -func (c *Client) MarkInsightAccepted(ctx context.Context, req *recommenderpb.MarkInsightAcceptedRequest, opts ...gax.CallOption) (*recommenderpb.Insight, error) { +func (c *gRPCClient) MarkInsightAccepted(ctx context.Context, req *recommenderpb.MarkInsightAcceptedRequest, opts ...gax.CallOption) (*recommenderpb.Insight, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -277,7 +400,7 @@ func (c *Client) MarkInsightAccepted(ctx context.Context, req *recommenderpb.Mar } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.MarkInsightAccepted[0:len(c.CallOptions.MarkInsightAccepted):len(c.CallOptions.MarkInsightAccepted)], opts...) + opts = append((*c.CallOptions).MarkInsightAccepted[0:len((*c.CallOptions).MarkInsightAccepted):len((*c.CallOptions).MarkInsightAccepted)], opts...) var resp *recommenderpb.Insight err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -290,12 +413,10 @@ func (c *Client) MarkInsightAccepted(ctx context.Context, req *recommenderpb.Mar return resp, nil } -// ListRecommendations lists recommendations for a Cloud project. Requires the recommender.*.list -// IAM permission for the specified recommender. -func (c *Client) ListRecommendations(ctx context.Context, req *recommenderpb.ListRecommendationsRequest, opts ...gax.CallOption) *RecommendationIterator { +func (c *gRPCClient) ListRecommendations(ctx context.Context, req *recommenderpb.ListRecommendationsRequest, opts ...gax.CallOption) *RecommendationIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListRecommendations[0:len(c.CallOptions.ListRecommendations):len(c.CallOptions.ListRecommendations)], opts...) + opts = append((*c.CallOptions).ListRecommendations[0:len((*c.CallOptions).ListRecommendations):len((*c.CallOptions).ListRecommendations)], opts...) it := &RecommendationIterator{} req = proto.Clone(req).(*recommenderpb.ListRecommendationsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*recommenderpb.Recommendation, string, error) { @@ -332,9 +453,7 @@ func (c *Client) ListRecommendations(ctx context.Context, req *recommenderpb.Lis return it } -// GetRecommendation gets the requested recommendation. Requires the recommender.*.get -// IAM permission for the specified recommender. -func (c *Client) GetRecommendation(ctx context.Context, req *recommenderpb.GetRecommendationRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { +func (c *gRPCClient) GetRecommendation(ctx context.Context, req *recommenderpb.GetRecommendationRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -342,7 +461,7 @@ func (c *Client) GetRecommendation(ctx context.Context, req *recommenderpb.GetRe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetRecommendation[0:len(c.CallOptions.GetRecommendation):len(c.CallOptions.GetRecommendation)], opts...) + opts = append((*c.CallOptions).GetRecommendation[0:len((*c.CallOptions).GetRecommendation):len((*c.CallOptions).GetRecommendation)], opts...) var resp *recommenderpb.Recommendation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -355,17 +474,7 @@ func (c *Client) GetRecommendation(ctx context.Context, req *recommenderpb.GetRe return resp, nil } -// MarkRecommendationClaimed marks the Recommendation State as Claimed. Users can use this method to -// indicate to the Recommender API that they are starting to apply the -// recommendation themselves. This stops the recommendation content from being -// updated. Associated insights are frozen and placed in the ACCEPTED state. -// -// MarkRecommendationClaimed can be applied to recommendations in CLAIMED or -// ACTIVE state. -// -// Requires the recommender.*.update IAM permission for the specified -// recommender. -func (c *Client) MarkRecommendationClaimed(ctx context.Context, req *recommenderpb.MarkRecommendationClaimedRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { +func (c *gRPCClient) MarkRecommendationClaimed(ctx context.Context, req *recommenderpb.MarkRecommendationClaimedRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -373,7 +482,7 @@ func (c *Client) MarkRecommendationClaimed(ctx context.Context, req *recommender } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.MarkRecommendationClaimed[0:len(c.CallOptions.MarkRecommendationClaimed):len(c.CallOptions.MarkRecommendationClaimed)], opts...) + opts = append((*c.CallOptions).MarkRecommendationClaimed[0:len((*c.CallOptions).MarkRecommendationClaimed):len((*c.CallOptions).MarkRecommendationClaimed)], opts...) var resp *recommenderpb.Recommendation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -386,18 +495,7 @@ func (c *Client) MarkRecommendationClaimed(ctx context.Context, req *recommender return resp, nil } -// MarkRecommendationSucceeded marks the Recommendation State as Succeeded. Users can use this method to -// indicate to the Recommender API that they have applied the recommendation -// themselves, and the operation was successful. This stops the recommendation -// content from being updated. Associated insights are frozen and placed in -// the ACCEPTED state. -// -// MarkRecommendationSucceeded can be applied to recommendations in ACTIVE, -// CLAIMED, SUCCEEDED, or FAILED state. -// -// Requires the recommender.*.update IAM permission for the specified -// recommender. -func (c *Client) MarkRecommendationSucceeded(ctx context.Context, req *recommenderpb.MarkRecommendationSucceededRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { +func (c *gRPCClient) MarkRecommendationSucceeded(ctx context.Context, req *recommenderpb.MarkRecommendationSucceededRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -405,7 +503,7 @@ func (c *Client) MarkRecommendationSucceeded(ctx context.Context, req *recommend } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.MarkRecommendationSucceeded[0:len(c.CallOptions.MarkRecommendationSucceeded):len(c.CallOptions.MarkRecommendationSucceeded)], opts...) + opts = append((*c.CallOptions).MarkRecommendationSucceeded[0:len((*c.CallOptions).MarkRecommendationSucceeded):len((*c.CallOptions).MarkRecommendationSucceeded)], opts...) var resp *recommenderpb.Recommendation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -418,18 +516,7 @@ func (c *Client) MarkRecommendationSucceeded(ctx context.Context, req *recommend return resp, nil } -// MarkRecommendationFailed marks the Recommendation State as Failed. Users can use this method to -// indicate to the Recommender API that they have applied the recommendation -// themselves, and the operation failed. This stops the recommendation content -// from being updated. Associated insights are frozen and placed in the -// ACCEPTED state. -// -// MarkRecommendationFailed can be applied to recommendations in ACTIVE, -// CLAIMED, SUCCEEDED, or FAILED state. -// -// Requires the recommender.*.update IAM permission for the specified -// recommender. -func (c *Client) MarkRecommendationFailed(ctx context.Context, req *recommenderpb.MarkRecommendationFailedRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { +func (c *gRPCClient) MarkRecommendationFailed(ctx context.Context, req *recommenderpb.MarkRecommendationFailedRequest, opts ...gax.CallOption) (*recommenderpb.Recommendation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -437,7 +524,7 @@ func (c *Client) MarkRecommendationFailed(ctx context.Context, req *recommenderp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.MarkRecommendationFailed[0:len(c.CallOptions.MarkRecommendationFailed):len(c.CallOptions.MarkRecommendationFailed)], opts...) + opts = append((*c.CallOptions).MarkRecommendationFailed[0:len((*c.CallOptions).MarkRecommendationFailed):len((*c.CallOptions).MarkRecommendationFailed)], opts...) var resp *recommenderpb.Recommendation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/recommender/apiv1beta1/recommender_client_example_test.go b/recommender/apiv1beta1/recommender_client_example_test.go index 30080f950dd6..60dc0fc18967 100644 --- a/recommender/apiv1beta1/recommender_client_example_test.go +++ b/recommender/apiv1beta1/recommender_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ListInsights() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.ListInsightsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleClient_ListInsights() { } func ExampleClient_GetInsight() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.GetInsightRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleClient_GetInsight() { } func ExampleClient_MarkInsightAccepted() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.MarkInsightAcceptedRequest{ // TODO: Fill request struct fields. @@ -102,14 +100,12 @@ func ExampleClient_MarkInsightAccepted() { } func ExampleClient_ListRecommendations() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.ListRecommendationsRequest{ // TODO: Fill request struct fields. @@ -129,13 +125,12 @@ func ExampleClient_ListRecommendations() { } func ExampleClient_GetRecommendation() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.GetRecommendationRequest{ // TODO: Fill request struct fields. @@ -149,13 +144,12 @@ func ExampleClient_GetRecommendation() { } func ExampleClient_MarkRecommendationClaimed() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.MarkRecommendationClaimedRequest{ // TODO: Fill request struct fields. @@ -169,13 +163,12 @@ func ExampleClient_MarkRecommendationClaimed() { } func ExampleClient_MarkRecommendationSucceeded() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.MarkRecommendationSucceededRequest{ // TODO: Fill request struct fields. @@ -189,13 +182,12 @@ func ExampleClient_MarkRecommendationSucceeded() { } func ExampleClient_MarkRecommendationFailed() { - // import recommenderpb "google.golang.org/genproto/googleapis/cloud/recommender/v1beta1" - ctx := context.Background() c, err := recommender.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &recommenderpb.MarkRecommendationFailedRequest{ // TODO: Fill request struct fields. diff --git a/redis/apiv1/cloud_redis_client.go b/redis/apiv1/cloud_redis_client.go index b4c7de786008..ab0f04cfc9ca 100644 --- a/redis/apiv1/cloud_redis_client.go +++ b/redis/apiv1/cloud_redis_client.go @@ -52,7 +52,7 @@ type CloudRedisCallOptions struct { DeleteInstance []gax.CallOption } -func defaultCloudRedisClientOptions() []option.ClientOption { +func defaultCloudRedisGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("redis.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("redis.mtls.googleapis.com:443"), @@ -78,32 +78,239 @@ func defaultCloudRedisCallOptions() *CloudRedisCallOptions { } } +// internalCloudRedisClient is an interface that defines the methods availaible from Google Cloud Memorystore for Redis API. +type internalCloudRedisClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListInstances(context.Context, *redispb.ListInstancesRequest, ...gax.CallOption) *InstanceIterator + GetInstance(context.Context, *redispb.GetInstanceRequest, ...gax.CallOption) (*redispb.Instance, error) + CreateInstance(context.Context, *redispb.CreateInstanceRequest, ...gax.CallOption) (*CreateInstanceOperation, error) + CreateInstanceOperation(name string) *CreateInstanceOperation + UpdateInstance(context.Context, *redispb.UpdateInstanceRequest, ...gax.CallOption) (*UpdateInstanceOperation, error) + UpdateInstanceOperation(name string) *UpdateInstanceOperation + UpgradeInstance(context.Context, *redispb.UpgradeInstanceRequest, ...gax.CallOption) (*UpgradeInstanceOperation, error) + UpgradeInstanceOperation(name string) *UpgradeInstanceOperation + ImportInstance(context.Context, *redispb.ImportInstanceRequest, ...gax.CallOption) (*ImportInstanceOperation, error) + ImportInstanceOperation(name string) *ImportInstanceOperation + ExportInstance(context.Context, *redispb.ExportInstanceRequest, ...gax.CallOption) (*ExportInstanceOperation, error) + ExportInstanceOperation(name string) *ExportInstanceOperation + FailoverInstance(context.Context, *redispb.FailoverInstanceRequest, ...gax.CallOption) (*FailoverInstanceOperation, error) + FailoverInstanceOperation(name string) *FailoverInstanceOperation + DeleteInstance(context.Context, *redispb.DeleteInstanceRequest, ...gax.CallOption) (*DeleteInstanceOperation, error) + DeleteInstanceOperation(name string) *DeleteInstanceOperation +} + // CloudRedisClient is a client for interacting with Google Cloud Memorystore for Redis API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Configures and manages Cloud Memorystore for Redis instances +// +// Google Cloud Memorystore for Redis v1 +// +// The redis.googleapis.com service implements the Google Cloud Memorystore +// for Redis API and defines the following resource model for managing Redis +// instances: +// +// The service works with a collection of cloud projects, named: /projects/* +// +// Each project has a collection of available locations, named: /locations/* +// +// Each location has a collection of Redis instances, named: /instances/* +// +// As such, Redis instances are resources of the form: +// /projects/{project_id}/locations/{location_id}/instances/{instance_id} +// +// Note that location_id must be referring to a GCP region; for example: +// +// projects/redpepper-1290/locations/us-central1/instances/my-redis type CloudRedisClient struct { + // The internal transport-dependent client. + internalClient internalCloudRedisClient + + // The call options for this service. + CallOptions *CloudRedisCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CloudRedisClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CloudRedisClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CloudRedisClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListInstances lists all Redis instances owned by a project in either the specified +// location (region) or all locations. +// +// The location should have the following format: +// +// projects/{project_id}/locations/{location_id} +// +// If location_id is specified as - (wildcard), then all regions +// available to the project are queried, and the results are aggregated. +func (c *CloudRedisClient) ListInstances(ctx context.Context, req *redispb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { + return c.internalClient.ListInstances(ctx, req, opts...) +} + +// GetInstance gets the details of a specific Redis instance. +func (c *CloudRedisClient) GetInstance(ctx context.Context, req *redispb.GetInstanceRequest, opts ...gax.CallOption) (*redispb.Instance, error) { + return c.internalClient.GetInstance(ctx, req, opts...) +} + +// CreateInstance creates a Redis instance based on the specified tier and memory size. +// +// By default, the instance is accessible from the project’s +// default network (at https://cloud.google.com/vpc/docs/vpc). +// +// The creation is executed asynchronously and callers may check the returned +// operation to track its progress. Once the operation is completed the Redis +// instance will be fully functional. Completed longrunning.Operation will +// contain the new instance object in the response field. +// +// The returned operation is automatically deleted after a few hours, so there +// is no need to call DeleteOperation. +func (c *CloudRedisClient) CreateInstance(ctx context.Context, req *redispb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { + return c.internalClient.CreateInstance(ctx, req, opts...) +} + +// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. +// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. +func (c *CloudRedisClient) CreateInstanceOperation(name string) *CreateInstanceOperation { + return c.internalClient.CreateInstanceOperation(name) +} + +// UpdateInstance updates the metadata and configuration of a specific Redis instance. +// +// Completed longrunning.Operation will contain the new instance object +// in the response field. The returned operation is automatically deleted +// after a few hours, so there is no need to call DeleteOperation. +func (c *CloudRedisClient) UpdateInstance(ctx context.Context, req *redispb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { + return c.internalClient.UpdateInstance(ctx, req, opts...) +} + +// UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. +// The name must be that of a previously created UpdateInstanceOperation, possibly from a different process. +func (c *CloudRedisClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { + return c.internalClient.UpdateInstanceOperation(name) +} + +// UpgradeInstance upgrades Redis instance to the newer Redis version specified in the +// request. +func (c *CloudRedisClient) UpgradeInstance(ctx context.Context, req *redispb.UpgradeInstanceRequest, opts ...gax.CallOption) (*UpgradeInstanceOperation, error) { + return c.internalClient.UpgradeInstance(ctx, req, opts...) +} + +// UpgradeInstanceOperation returns a new UpgradeInstanceOperation from a given name. +// The name must be that of a previously created UpgradeInstanceOperation, possibly from a different process. +func (c *CloudRedisClient) UpgradeInstanceOperation(name string) *UpgradeInstanceOperation { + return c.internalClient.UpgradeInstanceOperation(name) +} + +// ImportInstance import a Redis RDB snapshot file from Cloud Storage into a Redis instance. +// +// Redis may stop serving during this operation. Instance state will be +// IMPORTING for entire operation. When complete, the instance will contain +// only data from the imported file. +// +// The returned operation is automatically deleted after a few hours, so +// there is no need to call DeleteOperation. +func (c *CloudRedisClient) ImportInstance(ctx context.Context, req *redispb.ImportInstanceRequest, opts ...gax.CallOption) (*ImportInstanceOperation, error) { + return c.internalClient.ImportInstance(ctx, req, opts...) +} + +// ImportInstanceOperation returns a new ImportInstanceOperation from a given name. +// The name must be that of a previously created ImportInstanceOperation, possibly from a different process. +func (c *CloudRedisClient) ImportInstanceOperation(name string) *ImportInstanceOperation { + return c.internalClient.ImportInstanceOperation(name) +} + +// ExportInstance export Redis instance data into a Redis RDB format file in Cloud Storage. +// +// Redis will continue serving during this operation. +// +// The returned operation is automatically deleted after a few hours, so +// there is no need to call DeleteOperation. +func (c *CloudRedisClient) ExportInstance(ctx context.Context, req *redispb.ExportInstanceRequest, opts ...gax.CallOption) (*ExportInstanceOperation, error) { + return c.internalClient.ExportInstance(ctx, req, opts...) +} + +// ExportInstanceOperation returns a new ExportInstanceOperation from a given name. +// The name must be that of a previously created ExportInstanceOperation, possibly from a different process. +func (c *CloudRedisClient) ExportInstanceOperation(name string) *ExportInstanceOperation { + return c.internalClient.ExportInstanceOperation(name) +} + +// FailoverInstance initiates a failover of the master node to current replica node for a +// specific STANDARD tier Cloud Memorystore for Redis instance. +func (c *CloudRedisClient) FailoverInstance(ctx context.Context, req *redispb.FailoverInstanceRequest, opts ...gax.CallOption) (*FailoverInstanceOperation, error) { + return c.internalClient.FailoverInstance(ctx, req, opts...) +} + +// FailoverInstanceOperation returns a new FailoverInstanceOperation from a given name. +// The name must be that of a previously created FailoverInstanceOperation, possibly from a different process. +func (c *CloudRedisClient) FailoverInstanceOperation(name string) *FailoverInstanceOperation { + return c.internalClient.FailoverInstanceOperation(name) +} + +// DeleteInstance deletes a specific Redis instance. Instance stops serving and data is +// deleted. +func (c *CloudRedisClient) DeleteInstance(ctx context.Context, req *redispb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { + return c.internalClient.DeleteInstance(ctx, req, opts...) +} + +// DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. +// The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. +func (c *CloudRedisClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { + return c.internalClient.DeleteInstanceOperation(name) +} + +// cloudRedisGRPCClient is a client for interacting with Google Cloud Memorystore for Redis API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudRedisGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CloudRedisClient + CallOptions **CloudRedisCallOptions + // The gRPC API client. cloudRedisClient redispb.CloudRedisClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CloudRedisCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCloudRedisClient creates a new cloud redis client. +// NewCloudRedisClient creates a new cloud redis client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Configures and manages Cloud Memorystore for Redis instances // @@ -126,8 +333,7 @@ type CloudRedisClient struct { // // projects/redpepper-1290/locations/us-central1/instances/my-redis func NewCloudRedisClient(ctx context.Context, opts ...option.ClientOption) (*CloudRedisClient, error) { - clientOpts := defaultCloudRedisClientOptions() - + clientOpts := defaultCloudRedisGRPCClientOptions() if newCloudRedisClientHook != nil { hookOpts, err := newCloudRedisClientHook(ctx, clientHookParams{}) if err != nil { @@ -145,16 +351,19 @@ func NewCloudRedisClient(ctx context.Context, opts ...option.ClientOption) (*Clo if err != nil { return nil, err } - c := &CloudRedisClient{ + client := CloudRedisClient{CallOptions: defaultCloudRedisCallOptions()} + + c := &cloudRedisGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCloudRedisCallOptions(), - cloudRedisClient: redispb.NewCloudRedisClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -164,44 +373,36 @@ func NewCloudRedisClient(ctx context.Context, opts ...option.ClientOption) (*Clo // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CloudRedisClient) Connection() *grpc.ClientConn { +func (c *cloudRedisGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CloudRedisClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CloudRedisClient) setGoogleClientInfo(keyval ...string) { +func (c *cloudRedisGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListInstances lists all Redis instances owned by a project in either the specified -// location (region) or all locations. -// -// The location should have the following format: -// -// projects/{project_id}/locations/{location_id} -// -// If location_id is specified as - (wildcard), then all regions -// available to the project are queried, and the results are aggregated. -func (c *CloudRedisClient) ListInstances(ctx context.Context, req *redispb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudRedisGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *cloudRedisGRPCClient) ListInstances(ctx context.Context, req *redispb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListInstances[0:len(c.CallOptions.ListInstances):len(c.CallOptions.ListInstances)], opts...) + opts = append((*c.CallOptions).ListInstances[0:len((*c.CallOptions).ListInstances):len((*c.CallOptions).ListInstances)], opts...) it := &InstanceIterator{} req = proto.Clone(req).(*redispb.ListInstancesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*redispb.Instance, string, error) { @@ -238,8 +439,7 @@ func (c *CloudRedisClient) ListInstances(ctx context.Context, req *redispb.ListI return it } -// GetInstance gets the details of a specific Redis instance. -func (c *CloudRedisClient) GetInstance(ctx context.Context, req *redispb.GetInstanceRequest, opts ...gax.CallOption) (*redispb.Instance, error) { +func (c *cloudRedisGRPCClient) GetInstance(ctx context.Context, req *redispb.GetInstanceRequest, opts ...gax.CallOption) (*redispb.Instance, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -247,7 +447,7 @@ func (c *CloudRedisClient) GetInstance(ctx context.Context, req *redispb.GetInst } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetInstance[0:len(c.CallOptions.GetInstance):len(c.CallOptions.GetInstance)], opts...) + opts = append((*c.CallOptions).GetInstance[0:len((*c.CallOptions).GetInstance):len((*c.CallOptions).GetInstance)], opts...) var resp *redispb.Instance err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -260,19 +460,7 @@ func (c *CloudRedisClient) GetInstance(ctx context.Context, req *redispb.GetInst return resp, nil } -// CreateInstance creates a Redis instance based on the specified tier and memory size. -// -// By default, the instance is accessible from the project’s -// default network (at https://cloud.google.com/vpc/docs/vpc). -// -// The creation is executed asynchronously and callers may check the returned -// operation to track its progress. Once the operation is completed the Redis -// instance will be fully functional. Completed longrunning.Operation will -// contain the new instance object in the response field. -// -// The returned operation is automatically deleted after a few hours, so there -// is no need to call DeleteOperation. -func (c *CloudRedisClient) CreateInstance(ctx context.Context, req *redispb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { +func (c *cloudRedisGRPCClient) CreateInstance(ctx context.Context, req *redispb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -280,7 +468,7 @@ func (c *CloudRedisClient) CreateInstance(ctx context.Context, req *redispb.Crea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateInstance[0:len(c.CallOptions.CreateInstance):len(c.CallOptions.CreateInstance)], opts...) + opts = append((*c.CallOptions).CreateInstance[0:len((*c.CallOptions).CreateInstance):len((*c.CallOptions).CreateInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -291,16 +479,11 @@ func (c *CloudRedisClient) CreateInstance(ctx context.Context, req *redispb.Crea return nil, err } return &CreateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateInstance updates the metadata and configuration of a specific Redis instance. -// -// Completed longrunning.Operation will contain the new instance object -// in the response field. The returned operation is automatically deleted -// after a few hours, so there is no need to call DeleteOperation. -func (c *CloudRedisClient) UpdateInstance(ctx context.Context, req *redispb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { +func (c *cloudRedisGRPCClient) UpdateInstance(ctx context.Context, req *redispb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -308,7 +491,7 @@ func (c *CloudRedisClient) UpdateInstance(ctx context.Context, req *redispb.Upda } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance.name", url.QueryEscape(req.GetInstance().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateInstance[0:len(c.CallOptions.UpdateInstance):len(c.CallOptions.UpdateInstance)], opts...) + opts = append((*c.CallOptions).UpdateInstance[0:len((*c.CallOptions).UpdateInstance):len((*c.CallOptions).UpdateInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -319,13 +502,11 @@ func (c *CloudRedisClient) UpdateInstance(ctx context.Context, req *redispb.Upda return nil, err } return &UpdateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpgradeInstance upgrades Redis instance to the newer Redis version specified in the -// request. -func (c *CloudRedisClient) UpgradeInstance(ctx context.Context, req *redispb.UpgradeInstanceRequest, opts ...gax.CallOption) (*UpgradeInstanceOperation, error) { +func (c *cloudRedisGRPCClient) UpgradeInstance(ctx context.Context, req *redispb.UpgradeInstanceRequest, opts ...gax.CallOption) (*UpgradeInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -333,7 +514,7 @@ func (c *CloudRedisClient) UpgradeInstance(ctx context.Context, req *redispb.Upg } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpgradeInstance[0:len(c.CallOptions.UpgradeInstance):len(c.CallOptions.UpgradeInstance)], opts...) + opts = append((*c.CallOptions).UpgradeInstance[0:len((*c.CallOptions).UpgradeInstance):len((*c.CallOptions).UpgradeInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -344,19 +525,11 @@ func (c *CloudRedisClient) UpgradeInstance(ctx context.Context, req *redispb.Upg return nil, err } return &UpgradeInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ImportInstance import a Redis RDB snapshot file from Cloud Storage into a Redis instance. -// -// Redis may stop serving during this operation. Instance state will be -// IMPORTING for entire operation. When complete, the instance will contain -// only data from the imported file. -// -// The returned operation is automatically deleted after a few hours, so -// there is no need to call DeleteOperation. -func (c *CloudRedisClient) ImportInstance(ctx context.Context, req *redispb.ImportInstanceRequest, opts ...gax.CallOption) (*ImportInstanceOperation, error) { +func (c *cloudRedisGRPCClient) ImportInstance(ctx context.Context, req *redispb.ImportInstanceRequest, opts ...gax.CallOption) (*ImportInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -364,7 +537,7 @@ func (c *CloudRedisClient) ImportInstance(ctx context.Context, req *redispb.Impo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportInstance[0:len(c.CallOptions.ImportInstance):len(c.CallOptions.ImportInstance)], opts...) + opts = append((*c.CallOptions).ImportInstance[0:len((*c.CallOptions).ImportInstance):len((*c.CallOptions).ImportInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -375,17 +548,11 @@ func (c *CloudRedisClient) ImportInstance(ctx context.Context, req *redispb.Impo return nil, err } return &ImportInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ExportInstance export Redis instance data into a Redis RDB format file in Cloud Storage. -// -// Redis will continue serving during this operation. -// -// The returned operation is automatically deleted after a few hours, so -// there is no need to call DeleteOperation. -func (c *CloudRedisClient) ExportInstance(ctx context.Context, req *redispb.ExportInstanceRequest, opts ...gax.CallOption) (*ExportInstanceOperation, error) { +func (c *cloudRedisGRPCClient) ExportInstance(ctx context.Context, req *redispb.ExportInstanceRequest, opts ...gax.CallOption) (*ExportInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -393,7 +560,7 @@ func (c *CloudRedisClient) ExportInstance(ctx context.Context, req *redispb.Expo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportInstance[0:len(c.CallOptions.ExportInstance):len(c.CallOptions.ExportInstance)], opts...) + opts = append((*c.CallOptions).ExportInstance[0:len((*c.CallOptions).ExportInstance):len((*c.CallOptions).ExportInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -404,13 +571,11 @@ func (c *CloudRedisClient) ExportInstance(ctx context.Context, req *redispb.Expo return nil, err } return &ExportInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// FailoverInstance initiates a failover of the master node to current replica node for a -// specific STANDARD tier Cloud Memorystore for Redis instance. -func (c *CloudRedisClient) FailoverInstance(ctx context.Context, req *redispb.FailoverInstanceRequest, opts ...gax.CallOption) (*FailoverInstanceOperation, error) { +func (c *cloudRedisGRPCClient) FailoverInstance(ctx context.Context, req *redispb.FailoverInstanceRequest, opts ...gax.CallOption) (*FailoverInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -418,7 +583,7 @@ func (c *CloudRedisClient) FailoverInstance(ctx context.Context, req *redispb.Fa } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.FailoverInstance[0:len(c.CallOptions.FailoverInstance):len(c.CallOptions.FailoverInstance)], opts...) + opts = append((*c.CallOptions).FailoverInstance[0:len((*c.CallOptions).FailoverInstance):len((*c.CallOptions).FailoverInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -429,13 +594,11 @@ func (c *CloudRedisClient) FailoverInstance(ctx context.Context, req *redispb.Fa return nil, err } return &FailoverInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteInstance deletes a specific Redis instance. Instance stops serving and data is -// deleted. -func (c *CloudRedisClient) DeleteInstance(ctx context.Context, req *redispb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { +func (c *cloudRedisGRPCClient) DeleteInstance(ctx context.Context, req *redispb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -443,7 +606,7 @@ func (c *CloudRedisClient) DeleteInstance(ctx context.Context, req *redispb.Dele } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteInstance[0:len(c.CallOptions.DeleteInstance):len(c.CallOptions.DeleteInstance)], opts...) + opts = append((*c.CallOptions).DeleteInstance[0:len((*c.CallOptions).DeleteInstance):len((*c.CallOptions).DeleteInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -454,7 +617,7 @@ func (c *CloudRedisClient) DeleteInstance(ctx context.Context, req *redispb.Dele return nil, err } return &DeleteInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -465,9 +628,9 @@ type CreateInstanceOperation struct { // CreateInstanceOperation returns a new CreateInstanceOperation from a given name. // The name must be that of a previously created CreateInstanceOperation, possibly from a different process. -func (c *CloudRedisClient) CreateInstanceOperation(name string) *CreateInstanceOperation { +func (c *cloudRedisGRPCClient) CreateInstanceOperation(name string) *CreateInstanceOperation { return &CreateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -534,9 +697,9 @@ type DeleteInstanceOperation struct { // DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. // The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. -func (c *CloudRedisClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { +func (c *cloudRedisGRPCClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { return &DeleteInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -592,9 +755,9 @@ type ExportInstanceOperation struct { // ExportInstanceOperation returns a new ExportInstanceOperation from a given name. // The name must be that of a previously created ExportInstanceOperation, possibly from a different process. -func (c *CloudRedisClient) ExportInstanceOperation(name string) *ExportInstanceOperation { +func (c *cloudRedisGRPCClient) ExportInstanceOperation(name string) *ExportInstanceOperation { return &ExportInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -661,9 +824,9 @@ type FailoverInstanceOperation struct { // FailoverInstanceOperation returns a new FailoverInstanceOperation from a given name. // The name must be that of a previously created FailoverInstanceOperation, possibly from a different process. -func (c *CloudRedisClient) FailoverInstanceOperation(name string) *FailoverInstanceOperation { +func (c *cloudRedisGRPCClient) FailoverInstanceOperation(name string) *FailoverInstanceOperation { return &FailoverInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -730,9 +893,9 @@ type ImportInstanceOperation struct { // ImportInstanceOperation returns a new ImportInstanceOperation from a given name. // The name must be that of a previously created ImportInstanceOperation, possibly from a different process. -func (c *CloudRedisClient) ImportInstanceOperation(name string) *ImportInstanceOperation { +func (c *cloudRedisGRPCClient) ImportInstanceOperation(name string) *ImportInstanceOperation { return &ImportInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -799,9 +962,9 @@ type UpdateInstanceOperation struct { // UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. // The name must be that of a previously created UpdateInstanceOperation, possibly from a different process. -func (c *CloudRedisClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { +func (c *cloudRedisGRPCClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { return &UpdateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -868,9 +1031,9 @@ type UpgradeInstanceOperation struct { // UpgradeInstanceOperation returns a new UpgradeInstanceOperation from a given name. // The name must be that of a previously created UpgradeInstanceOperation, possibly from a different process. -func (c *CloudRedisClient) UpgradeInstanceOperation(name string) *UpgradeInstanceOperation { +func (c *cloudRedisGRPCClient) UpgradeInstanceOperation(name string) *UpgradeInstanceOperation { return &UpgradeInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/redis/apiv1/cloud_redis_client_example_test.go b/redis/apiv1/cloud_redis_client_example_test.go index 1d5ed5d81282..1a6f04bdc554 100644 --- a/redis/apiv1/cloud_redis_client_example_test.go +++ b/redis/apiv1/cloud_redis_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewCloudRedisClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCloudRedisClient_ListInstances() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.ListInstancesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleCloudRedisClient_ListInstances() { } func ExampleCloudRedisClient_GetInstance() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.GetInstanceRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleCloudRedisClient_GetInstance() { } func ExampleCloudRedisClient_CreateInstance() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.CreateInstanceRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleCloudRedisClient_CreateInstance() { } func ExampleCloudRedisClient_UpdateInstance() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.UpdateInstanceRequest{ // TODO: Fill request struct fields. @@ -132,13 +129,12 @@ func ExampleCloudRedisClient_UpdateInstance() { } func ExampleCloudRedisClient_UpgradeInstance() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.UpgradeInstanceRequest{ // TODO: Fill request struct fields. @@ -157,13 +153,12 @@ func ExampleCloudRedisClient_UpgradeInstance() { } func ExampleCloudRedisClient_ImportInstance() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.ImportInstanceRequest{ // TODO: Fill request struct fields. @@ -182,13 +177,12 @@ func ExampleCloudRedisClient_ImportInstance() { } func ExampleCloudRedisClient_ExportInstance() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.ExportInstanceRequest{ // TODO: Fill request struct fields. @@ -207,13 +201,12 @@ func ExampleCloudRedisClient_ExportInstance() { } func ExampleCloudRedisClient_FailoverInstance() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.FailoverInstanceRequest{ // TODO: Fill request struct fields. @@ -232,13 +225,12 @@ func ExampleCloudRedisClient_FailoverInstance() { } func ExampleCloudRedisClient_DeleteInstance() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.DeleteInstanceRequest{ // TODO: Fill request struct fields. diff --git a/redis/apiv1/doc.go b/redis/apiv1/doc.go index 8229a773f369..243ce769783c 100644 --- a/redis/apiv1/doc.go +++ b/redis/apiv1/doc.go @@ -28,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package redis // import "cloud.google.com/go/redis/apiv1" import ( @@ -48,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/redis/apiv1beta1/cloud_redis_client.go b/redis/apiv1beta1/cloud_redis_client.go index b6e4192b8598..a8a9c67e6822 100644 --- a/redis/apiv1beta1/cloud_redis_client.go +++ b/redis/apiv1beta1/cloud_redis_client.go @@ -53,7 +53,7 @@ type CloudRedisCallOptions struct { DeleteInstance []gax.CallOption } -func defaultCloudRedisClientOptions() []option.ClientOption { +func defaultCloudRedisGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("redis.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("redis.mtls.googleapis.com:443"), @@ -79,32 +79,239 @@ func defaultCloudRedisCallOptions() *CloudRedisCallOptions { } } +// internalCloudRedisClient is an interface that defines the methods availaible from Google Cloud Memorystore for Redis API. +type internalCloudRedisClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListInstances(context.Context, *redispb.ListInstancesRequest, ...gax.CallOption) *InstanceIterator + GetInstance(context.Context, *redispb.GetInstanceRequest, ...gax.CallOption) (*redispb.Instance, error) + CreateInstance(context.Context, *redispb.CreateInstanceRequest, ...gax.CallOption) (*CreateInstanceOperation, error) + CreateInstanceOperation(name string) *CreateInstanceOperation + UpdateInstance(context.Context, *redispb.UpdateInstanceRequest, ...gax.CallOption) (*UpdateInstanceOperation, error) + UpdateInstanceOperation(name string) *UpdateInstanceOperation + UpgradeInstance(context.Context, *redispb.UpgradeInstanceRequest, ...gax.CallOption) (*UpgradeInstanceOperation, error) + UpgradeInstanceOperation(name string) *UpgradeInstanceOperation + ImportInstance(context.Context, *redispb.ImportInstanceRequest, ...gax.CallOption) (*ImportInstanceOperation, error) + ImportInstanceOperation(name string) *ImportInstanceOperation + ExportInstance(context.Context, *redispb.ExportInstanceRequest, ...gax.CallOption) (*ExportInstanceOperation, error) + ExportInstanceOperation(name string) *ExportInstanceOperation + FailoverInstance(context.Context, *redispb.FailoverInstanceRequest, ...gax.CallOption) (*FailoverInstanceOperation, error) + FailoverInstanceOperation(name string) *FailoverInstanceOperation + DeleteInstance(context.Context, *redispb.DeleteInstanceRequest, ...gax.CallOption) (*DeleteInstanceOperation, error) + DeleteInstanceOperation(name string) *DeleteInstanceOperation +} + // CloudRedisClient is a client for interacting with Google Cloud Memorystore for Redis API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Configures and manages Cloud Memorystore for Redis instances +// +// Google Cloud Memorystore for Redis v1beta1 +// +// The redis.googleapis.com service implements the Google Cloud Memorystore +// for Redis API and defines the following resource model for managing Redis +// instances: +// +// The service works with a collection of cloud projects, named: /projects/* +// +// Each project has a collection of available locations, named: /locations/* +// +// Each location has a collection of Redis instances, named: /instances/* +// +// As such, Redis instances are resources of the form: +// /projects/{project_id}/locations/{location_id}/instances/{instance_id} +// +// Note that location_id must be refering to a GCP region; for example: +// +// projects/redpepper-1290/locations/us-central1/instances/my-redis type CloudRedisClient struct { + // The internal transport-dependent client. + internalClient internalCloudRedisClient + + // The call options for this service. + CallOptions *CloudRedisCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CloudRedisClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CloudRedisClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CloudRedisClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListInstances lists all Redis instances owned by a project in either the specified +// location (region) or all locations. +// +// The location should have the following format: +// +// projects/{project_id}/locations/{location_id} +// +// If location_id is specified as - (wildcard), then all regions +// available to the project are queried, and the results are aggregated. +func (c *CloudRedisClient) ListInstances(ctx context.Context, req *redispb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { + return c.internalClient.ListInstances(ctx, req, opts...) +} + +// GetInstance gets the details of a specific Redis instance. +func (c *CloudRedisClient) GetInstance(ctx context.Context, req *redispb.GetInstanceRequest, opts ...gax.CallOption) (*redispb.Instance, error) { + return c.internalClient.GetInstance(ctx, req, opts...) +} + +// CreateInstance creates a Redis instance based on the specified tier and memory size. +// +// By default, the instance is accessible from the project’s +// default network (at https://cloud.google.com/vpc/docs/vpc). +// +// The creation is executed asynchronously and callers may check the returned +// operation to track its progress. Once the operation is completed the Redis +// instance will be fully functional. Completed longrunning.Operation will +// contain the new instance object in the response field. +// +// The returned operation is automatically deleted after a few hours, so there +// is no need to call DeleteOperation. +func (c *CloudRedisClient) CreateInstance(ctx context.Context, req *redispb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { + return c.internalClient.CreateInstance(ctx, req, opts...) +} + +// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. +// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. +func (c *CloudRedisClient) CreateInstanceOperation(name string) *CreateInstanceOperation { + return c.internalClient.CreateInstanceOperation(name) +} + +// UpdateInstance updates the metadata and configuration of a specific Redis instance. +// +// Completed longrunning.Operation will contain the new instance object +// in the response field. The returned operation is automatically deleted +// after a few hours, so there is no need to call DeleteOperation. +func (c *CloudRedisClient) UpdateInstance(ctx context.Context, req *redispb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { + return c.internalClient.UpdateInstance(ctx, req, opts...) +} + +// UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. +// The name must be that of a previously created UpdateInstanceOperation, possibly from a different process. +func (c *CloudRedisClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { + return c.internalClient.UpdateInstanceOperation(name) +} + +// UpgradeInstance upgrades Redis instance to the newer Redis version specified in the +// request. +func (c *CloudRedisClient) UpgradeInstance(ctx context.Context, req *redispb.UpgradeInstanceRequest, opts ...gax.CallOption) (*UpgradeInstanceOperation, error) { + return c.internalClient.UpgradeInstance(ctx, req, opts...) +} + +// UpgradeInstanceOperation returns a new UpgradeInstanceOperation from a given name. +// The name must be that of a previously created UpgradeInstanceOperation, possibly from a different process. +func (c *CloudRedisClient) UpgradeInstanceOperation(name string) *UpgradeInstanceOperation { + return c.internalClient.UpgradeInstanceOperation(name) +} + +// ImportInstance import a Redis RDB snapshot file from Cloud Storage into a Redis instance. +// +// Redis may stop serving during this operation. Instance state will be +// IMPORTING for entire operation. When complete, the instance will contain +// only data from the imported file. +// +// The returned operation is automatically deleted after a few hours, so +// there is no need to call DeleteOperation. +func (c *CloudRedisClient) ImportInstance(ctx context.Context, req *redispb.ImportInstanceRequest, opts ...gax.CallOption) (*ImportInstanceOperation, error) { + return c.internalClient.ImportInstance(ctx, req, opts...) +} + +// ImportInstanceOperation returns a new ImportInstanceOperation from a given name. +// The name must be that of a previously created ImportInstanceOperation, possibly from a different process. +func (c *CloudRedisClient) ImportInstanceOperation(name string) *ImportInstanceOperation { + return c.internalClient.ImportInstanceOperation(name) +} + +// ExportInstance export Redis instance data into a Redis RDB format file in Cloud Storage. +// +// Redis will continue serving during this operation. +// +// The returned operation is automatically deleted after a few hours, so +// there is no need to call DeleteOperation. +func (c *CloudRedisClient) ExportInstance(ctx context.Context, req *redispb.ExportInstanceRequest, opts ...gax.CallOption) (*ExportInstanceOperation, error) { + return c.internalClient.ExportInstance(ctx, req, opts...) +} + +// ExportInstanceOperation returns a new ExportInstanceOperation from a given name. +// The name must be that of a previously created ExportInstanceOperation, possibly from a different process. +func (c *CloudRedisClient) ExportInstanceOperation(name string) *ExportInstanceOperation { + return c.internalClient.ExportInstanceOperation(name) +} + +// FailoverInstance initiates a failover of the master node to current replica node for a +// specific STANDARD tier Cloud Memorystore for Redis instance. +func (c *CloudRedisClient) FailoverInstance(ctx context.Context, req *redispb.FailoverInstanceRequest, opts ...gax.CallOption) (*FailoverInstanceOperation, error) { + return c.internalClient.FailoverInstance(ctx, req, opts...) +} + +// FailoverInstanceOperation returns a new FailoverInstanceOperation from a given name. +// The name must be that of a previously created FailoverInstanceOperation, possibly from a different process. +func (c *CloudRedisClient) FailoverInstanceOperation(name string) *FailoverInstanceOperation { + return c.internalClient.FailoverInstanceOperation(name) +} + +// DeleteInstance deletes a specific Redis instance. Instance stops serving and data is +// deleted. +func (c *CloudRedisClient) DeleteInstance(ctx context.Context, req *redispb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { + return c.internalClient.DeleteInstance(ctx, req, opts...) +} + +// DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. +// The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. +func (c *CloudRedisClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { + return c.internalClient.DeleteInstanceOperation(name) +} + +// cloudRedisGRPCClient is a client for interacting with Google Cloud Memorystore for Redis API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudRedisGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CloudRedisClient + CallOptions **CloudRedisCallOptions + // The gRPC API client. cloudRedisClient redispb.CloudRedisClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CloudRedisCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCloudRedisClient creates a new cloud redis client. +// NewCloudRedisClient creates a new cloud redis client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Configures and manages Cloud Memorystore for Redis instances // @@ -127,8 +334,7 @@ type CloudRedisClient struct { // // projects/redpepper-1290/locations/us-central1/instances/my-redis func NewCloudRedisClient(ctx context.Context, opts ...option.ClientOption) (*CloudRedisClient, error) { - clientOpts := defaultCloudRedisClientOptions() - + clientOpts := defaultCloudRedisGRPCClientOptions() if newCloudRedisClientHook != nil { hookOpts, err := newCloudRedisClientHook(ctx, clientHookParams{}) if err != nil { @@ -146,16 +352,19 @@ func NewCloudRedisClient(ctx context.Context, opts ...option.ClientOption) (*Clo if err != nil { return nil, err } - c := &CloudRedisClient{ + client := CloudRedisClient{CallOptions: defaultCloudRedisCallOptions()} + + c := &cloudRedisGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCloudRedisCallOptions(), - cloudRedisClient: redispb.NewCloudRedisClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -165,44 +374,36 @@ func NewCloudRedisClient(ctx context.Context, opts ...option.ClientOption) (*Clo // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CloudRedisClient) Connection() *grpc.ClientConn { +func (c *cloudRedisGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CloudRedisClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CloudRedisClient) setGoogleClientInfo(keyval ...string) { +func (c *cloudRedisGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListInstances lists all Redis instances owned by a project in either the specified -// location (region) or all locations. -// -// The location should have the following format: -// -// projects/{project_id}/locations/{location_id} -// -// If location_id is specified as - (wildcard), then all regions -// available to the project are queried, and the results are aggregated. -func (c *CloudRedisClient) ListInstances(ctx context.Context, req *redispb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudRedisGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *cloudRedisGRPCClient) ListInstances(ctx context.Context, req *redispb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListInstances[0:len(c.CallOptions.ListInstances):len(c.CallOptions.ListInstances)], opts...) + opts = append((*c.CallOptions).ListInstances[0:len((*c.CallOptions).ListInstances):len((*c.CallOptions).ListInstances)], opts...) it := &InstanceIterator{} req = proto.Clone(req).(*redispb.ListInstancesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*redispb.Instance, string, error) { @@ -239,8 +440,7 @@ func (c *CloudRedisClient) ListInstances(ctx context.Context, req *redispb.ListI return it } -// GetInstance gets the details of a specific Redis instance. -func (c *CloudRedisClient) GetInstance(ctx context.Context, req *redispb.GetInstanceRequest, opts ...gax.CallOption) (*redispb.Instance, error) { +func (c *cloudRedisGRPCClient) GetInstance(ctx context.Context, req *redispb.GetInstanceRequest, opts ...gax.CallOption) (*redispb.Instance, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -248,7 +448,7 @@ func (c *CloudRedisClient) GetInstance(ctx context.Context, req *redispb.GetInst } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetInstance[0:len(c.CallOptions.GetInstance):len(c.CallOptions.GetInstance)], opts...) + opts = append((*c.CallOptions).GetInstance[0:len((*c.CallOptions).GetInstance):len((*c.CallOptions).GetInstance)], opts...) var resp *redispb.Instance err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -261,19 +461,7 @@ func (c *CloudRedisClient) GetInstance(ctx context.Context, req *redispb.GetInst return resp, nil } -// CreateInstance creates a Redis instance based on the specified tier and memory size. -// -// By default, the instance is accessible from the project’s -// default network (at https://cloud.google.com/vpc/docs/vpc). -// -// The creation is executed asynchronously and callers may check the returned -// operation to track its progress. Once the operation is completed the Redis -// instance will be fully functional. Completed longrunning.Operation will -// contain the new instance object in the response field. -// -// The returned operation is automatically deleted after a few hours, so there -// is no need to call DeleteOperation. -func (c *CloudRedisClient) CreateInstance(ctx context.Context, req *redispb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { +func (c *cloudRedisGRPCClient) CreateInstance(ctx context.Context, req *redispb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -281,7 +469,7 @@ func (c *CloudRedisClient) CreateInstance(ctx context.Context, req *redispb.Crea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateInstance[0:len(c.CallOptions.CreateInstance):len(c.CallOptions.CreateInstance)], opts...) + opts = append((*c.CallOptions).CreateInstance[0:len((*c.CallOptions).CreateInstance):len((*c.CallOptions).CreateInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -292,16 +480,11 @@ func (c *CloudRedisClient) CreateInstance(ctx context.Context, req *redispb.Crea return nil, err } return &CreateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateInstance updates the metadata and configuration of a specific Redis instance. -// -// Completed longrunning.Operation will contain the new instance object -// in the response field. The returned operation is automatically deleted -// after a few hours, so there is no need to call DeleteOperation. -func (c *CloudRedisClient) UpdateInstance(ctx context.Context, req *redispb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { +func (c *cloudRedisGRPCClient) UpdateInstance(ctx context.Context, req *redispb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -309,7 +492,7 @@ func (c *CloudRedisClient) UpdateInstance(ctx context.Context, req *redispb.Upda } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance.name", url.QueryEscape(req.GetInstance().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateInstance[0:len(c.CallOptions.UpdateInstance):len(c.CallOptions.UpdateInstance)], opts...) + opts = append((*c.CallOptions).UpdateInstance[0:len((*c.CallOptions).UpdateInstance):len((*c.CallOptions).UpdateInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -320,13 +503,11 @@ func (c *CloudRedisClient) UpdateInstance(ctx context.Context, req *redispb.Upda return nil, err } return &UpdateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpgradeInstance upgrades Redis instance to the newer Redis version specified in the -// request. -func (c *CloudRedisClient) UpgradeInstance(ctx context.Context, req *redispb.UpgradeInstanceRequest, opts ...gax.CallOption) (*UpgradeInstanceOperation, error) { +func (c *cloudRedisGRPCClient) UpgradeInstance(ctx context.Context, req *redispb.UpgradeInstanceRequest, opts ...gax.CallOption) (*UpgradeInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -334,7 +515,7 @@ func (c *CloudRedisClient) UpgradeInstance(ctx context.Context, req *redispb.Upg } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpgradeInstance[0:len(c.CallOptions.UpgradeInstance):len(c.CallOptions.UpgradeInstance)], opts...) + opts = append((*c.CallOptions).UpgradeInstance[0:len((*c.CallOptions).UpgradeInstance):len((*c.CallOptions).UpgradeInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -345,19 +526,11 @@ func (c *CloudRedisClient) UpgradeInstance(ctx context.Context, req *redispb.Upg return nil, err } return &UpgradeInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ImportInstance import a Redis RDB snapshot file from Cloud Storage into a Redis instance. -// -// Redis may stop serving during this operation. Instance state will be -// IMPORTING for entire operation. When complete, the instance will contain -// only data from the imported file. -// -// The returned operation is automatically deleted after a few hours, so -// there is no need to call DeleteOperation. -func (c *CloudRedisClient) ImportInstance(ctx context.Context, req *redispb.ImportInstanceRequest, opts ...gax.CallOption) (*ImportInstanceOperation, error) { +func (c *cloudRedisGRPCClient) ImportInstance(ctx context.Context, req *redispb.ImportInstanceRequest, opts ...gax.CallOption) (*ImportInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -365,7 +538,7 @@ func (c *CloudRedisClient) ImportInstance(ctx context.Context, req *redispb.Impo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportInstance[0:len(c.CallOptions.ImportInstance):len(c.CallOptions.ImportInstance)], opts...) + opts = append((*c.CallOptions).ImportInstance[0:len((*c.CallOptions).ImportInstance):len((*c.CallOptions).ImportInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -376,17 +549,11 @@ func (c *CloudRedisClient) ImportInstance(ctx context.Context, req *redispb.Impo return nil, err } return &ImportInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ExportInstance export Redis instance data into a Redis RDB format file in Cloud Storage. -// -// Redis will continue serving during this operation. -// -// The returned operation is automatically deleted after a few hours, so -// there is no need to call DeleteOperation. -func (c *CloudRedisClient) ExportInstance(ctx context.Context, req *redispb.ExportInstanceRequest, opts ...gax.CallOption) (*ExportInstanceOperation, error) { +func (c *cloudRedisGRPCClient) ExportInstance(ctx context.Context, req *redispb.ExportInstanceRequest, opts ...gax.CallOption) (*ExportInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -394,7 +561,7 @@ func (c *CloudRedisClient) ExportInstance(ctx context.Context, req *redispb.Expo } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExportInstance[0:len(c.CallOptions.ExportInstance):len(c.CallOptions.ExportInstance)], opts...) + opts = append((*c.CallOptions).ExportInstance[0:len((*c.CallOptions).ExportInstance):len((*c.CallOptions).ExportInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -405,13 +572,11 @@ func (c *CloudRedisClient) ExportInstance(ctx context.Context, req *redispb.Expo return nil, err } return &ExportInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// FailoverInstance initiates a failover of the master node to current replica node for a -// specific STANDARD tier Cloud Memorystore for Redis instance. -func (c *CloudRedisClient) FailoverInstance(ctx context.Context, req *redispb.FailoverInstanceRequest, opts ...gax.CallOption) (*FailoverInstanceOperation, error) { +func (c *cloudRedisGRPCClient) FailoverInstance(ctx context.Context, req *redispb.FailoverInstanceRequest, opts ...gax.CallOption) (*FailoverInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -419,7 +584,7 @@ func (c *CloudRedisClient) FailoverInstance(ctx context.Context, req *redispb.Fa } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.FailoverInstance[0:len(c.CallOptions.FailoverInstance):len(c.CallOptions.FailoverInstance)], opts...) + opts = append((*c.CallOptions).FailoverInstance[0:len((*c.CallOptions).FailoverInstance):len((*c.CallOptions).FailoverInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -430,13 +595,11 @@ func (c *CloudRedisClient) FailoverInstance(ctx context.Context, req *redispb.Fa return nil, err } return &FailoverInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteInstance deletes a specific Redis instance. Instance stops serving and data is -// deleted. -func (c *CloudRedisClient) DeleteInstance(ctx context.Context, req *redispb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { +func (c *cloudRedisGRPCClient) DeleteInstance(ctx context.Context, req *redispb.DeleteInstanceRequest, opts ...gax.CallOption) (*DeleteInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -444,7 +607,7 @@ func (c *CloudRedisClient) DeleteInstance(ctx context.Context, req *redispb.Dele } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteInstance[0:len(c.CallOptions.DeleteInstance):len(c.CallOptions.DeleteInstance)], opts...) + opts = append((*c.CallOptions).DeleteInstance[0:len((*c.CallOptions).DeleteInstance):len((*c.CallOptions).DeleteInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -455,7 +618,7 @@ func (c *CloudRedisClient) DeleteInstance(ctx context.Context, req *redispb.Dele return nil, err } return &DeleteInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -466,9 +629,9 @@ type CreateInstanceOperation struct { // CreateInstanceOperation returns a new CreateInstanceOperation from a given name. // The name must be that of a previously created CreateInstanceOperation, possibly from a different process. -func (c *CloudRedisClient) CreateInstanceOperation(name string) *CreateInstanceOperation { +func (c *cloudRedisGRPCClient) CreateInstanceOperation(name string) *CreateInstanceOperation { return &CreateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -535,9 +698,9 @@ type DeleteInstanceOperation struct { // DeleteInstanceOperation returns a new DeleteInstanceOperation from a given name. // The name must be that of a previously created DeleteInstanceOperation, possibly from a different process. -func (c *CloudRedisClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { +func (c *cloudRedisGRPCClient) DeleteInstanceOperation(name string) *DeleteInstanceOperation { return &DeleteInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -593,9 +756,9 @@ type ExportInstanceOperation struct { // ExportInstanceOperation returns a new ExportInstanceOperation from a given name. // The name must be that of a previously created ExportInstanceOperation, possibly from a different process. -func (c *CloudRedisClient) ExportInstanceOperation(name string) *ExportInstanceOperation { +func (c *cloudRedisGRPCClient) ExportInstanceOperation(name string) *ExportInstanceOperation { return &ExportInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -662,9 +825,9 @@ type FailoverInstanceOperation struct { // FailoverInstanceOperation returns a new FailoverInstanceOperation from a given name. // The name must be that of a previously created FailoverInstanceOperation, possibly from a different process. -func (c *CloudRedisClient) FailoverInstanceOperation(name string) *FailoverInstanceOperation { +func (c *cloudRedisGRPCClient) FailoverInstanceOperation(name string) *FailoverInstanceOperation { return &FailoverInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -731,9 +894,9 @@ type ImportInstanceOperation struct { // ImportInstanceOperation returns a new ImportInstanceOperation from a given name. // The name must be that of a previously created ImportInstanceOperation, possibly from a different process. -func (c *CloudRedisClient) ImportInstanceOperation(name string) *ImportInstanceOperation { +func (c *cloudRedisGRPCClient) ImportInstanceOperation(name string) *ImportInstanceOperation { return &ImportInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -800,9 +963,9 @@ type UpdateInstanceOperation struct { // UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. // The name must be that of a previously created UpdateInstanceOperation, possibly from a different process. -func (c *CloudRedisClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { +func (c *cloudRedisGRPCClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { return &UpdateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -869,9 +1032,9 @@ type UpgradeInstanceOperation struct { // UpgradeInstanceOperation returns a new UpgradeInstanceOperation from a given name. // The name must be that of a previously created UpgradeInstanceOperation, possibly from a different process. -func (c *CloudRedisClient) UpgradeInstanceOperation(name string) *UpgradeInstanceOperation { +func (c *cloudRedisGRPCClient) UpgradeInstanceOperation(name string) *UpgradeInstanceOperation { return &UpgradeInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/redis/apiv1beta1/cloud_redis_client_example_test.go b/redis/apiv1beta1/cloud_redis_client_example_test.go index e13afd0b9471..8fdedfd8964b 100644 --- a/redis/apiv1beta1/cloud_redis_client_example_test.go +++ b/redis/apiv1beta1/cloud_redis_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewCloudRedisClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCloudRedisClient_ListInstances() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.ListInstancesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleCloudRedisClient_ListInstances() { } func ExampleCloudRedisClient_GetInstance() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.GetInstanceRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleCloudRedisClient_GetInstance() { } func ExampleCloudRedisClient_CreateInstance() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.CreateInstanceRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleCloudRedisClient_CreateInstance() { } func ExampleCloudRedisClient_UpdateInstance() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.UpdateInstanceRequest{ // TODO: Fill request struct fields. @@ -132,13 +129,12 @@ func ExampleCloudRedisClient_UpdateInstance() { } func ExampleCloudRedisClient_UpgradeInstance() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.UpgradeInstanceRequest{ // TODO: Fill request struct fields. @@ -157,13 +153,12 @@ func ExampleCloudRedisClient_UpgradeInstance() { } func ExampleCloudRedisClient_ImportInstance() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.ImportInstanceRequest{ // TODO: Fill request struct fields. @@ -182,13 +177,12 @@ func ExampleCloudRedisClient_ImportInstance() { } func ExampleCloudRedisClient_ExportInstance() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.ExportInstanceRequest{ // TODO: Fill request struct fields. @@ -207,13 +201,12 @@ func ExampleCloudRedisClient_ExportInstance() { } func ExampleCloudRedisClient_FailoverInstance() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.FailoverInstanceRequest{ // TODO: Fill request struct fields. @@ -232,13 +225,12 @@ func ExampleCloudRedisClient_FailoverInstance() { } func ExampleCloudRedisClient_DeleteInstance() { - // import redispb "google.golang.org/genproto/googleapis/cloud/redis/v1beta1" - ctx := context.Background() c, err := redis.NewCloudRedisClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &redispb.DeleteInstanceRequest{ // TODO: Fill request struct fields. diff --git a/redis/apiv1beta1/doc.go b/redis/apiv1beta1/doc.go index df4feacc0274..b30f0715d013 100644 --- a/redis/apiv1beta1/doc.go +++ b/redis/apiv1beta1/doc.go @@ -19,6 +19,8 @@ // // Creates and manages Redis instances on the Google Cloud Platform. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -28,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package redis // import "cloud.google.com/go/redis/apiv1beta1" import ( @@ -48,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/resourcemanager/apiv2/doc.go b/resourcemanager/apiv2/doc.go index 7eebb9404f2f..3acc95260167 100644 --- a/resourcemanager/apiv2/doc.go +++ b/resourcemanager/apiv2/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package resourcemanager // import "cloud.google.com/go/resourcemanager/apiv2" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/resourcemanager/apiv2/folders_client.go b/resourcemanager/apiv2/folders_client.go index ffa974041f31..d6bf1c9e7a53 100644 --- a/resourcemanager/apiv2/folders_client.go +++ b/resourcemanager/apiv2/folders_client.go @@ -55,7 +55,7 @@ type FoldersCallOptions struct { TestIamPermissions []gax.CallOption } -func defaultFoldersClientOptions() []option.ClientOption { +func defaultFoldersGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudresourcemanager.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudresourcemanager.mtls.googleapis.com:443"), @@ -83,39 +83,269 @@ func defaultFoldersCallOptions() *FoldersCallOptions { } } +// internalFoldersClient is an interface that defines the methods availaible from Cloud Resource Manager API. +type internalFoldersClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListFolders(context.Context, *resourcemanagerpb.ListFoldersRequest, ...gax.CallOption) *FolderIterator + SearchFolders(context.Context, *resourcemanagerpb.SearchFoldersRequest, ...gax.CallOption) *FolderIterator + GetFolder(context.Context, *resourcemanagerpb.GetFolderRequest, ...gax.CallOption) (*resourcemanagerpb.Folder, error) + CreateFolder(context.Context, *resourcemanagerpb.CreateFolderRequest, ...gax.CallOption) (*CreateFolderOperation, error) + CreateFolderOperation(name string) *CreateFolderOperation + UpdateFolder(context.Context, *resourcemanagerpb.UpdateFolderRequest, ...gax.CallOption) (*resourcemanagerpb.Folder, error) + MoveFolder(context.Context, *resourcemanagerpb.MoveFolderRequest, ...gax.CallOption) (*MoveFolderOperation, error) + MoveFolderOperation(name string) *MoveFolderOperation + DeleteFolder(context.Context, *resourcemanagerpb.DeleteFolderRequest, ...gax.CallOption) (*resourcemanagerpb.Folder, error) + UndeleteFolder(context.Context, *resourcemanagerpb.UndeleteFolderRequest, ...gax.CallOption) (*resourcemanagerpb.Folder, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) +} + // FoldersClient is a client for interacting with Cloud Resource Manager API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Manages Cloud Resource Folders. +// Cloud Resource Folders can be used to organize the resources under an +// organization and to control the IAM policies applied to groups of resources. type FoldersClient struct { + // The internal transport-dependent client. + internalClient internalFoldersClient + + // The call options for this service. + CallOptions *FoldersCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *FoldersClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *FoldersClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *FoldersClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListFolders lists the Folders that are direct descendants of supplied parent resource. +// List provides a strongly consistent view of the Folders underneath +// the specified parent resource. +// List returns Folders sorted based upon the (ascending) lexical ordering +// of their display_name. +// The caller must have resourcemanager.folders.list permission on the +// identified parent. +func (c *FoldersClient) ListFolders(ctx context.Context, req *resourcemanagerpb.ListFoldersRequest, opts ...gax.CallOption) *FolderIterator { + return c.internalClient.ListFolders(ctx, req, opts...) +} + +// SearchFolders search for folders that match specific filter criteria. +// Search provides an eventually consistent view of the folders a user has +// access to which meet the specified filter criteria. +// +// This will only return folders on which the caller has the +// permission resourcemanager.folders.get. +func (c *FoldersClient) SearchFolders(ctx context.Context, req *resourcemanagerpb.SearchFoldersRequest, opts ...gax.CallOption) *FolderIterator { + return c.internalClient.SearchFolders(ctx, req, opts...) +} + +// GetFolder retrieves a Folder identified by the supplied resource name. +// Valid Folder resource names have the format folders/{folder_id} +// (for example, folders/1234). +// The caller must have resourcemanager.folders.get permission on the +// identified folder. +func (c *FoldersClient) GetFolder(ctx context.Context, req *resourcemanagerpb.GetFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + return c.internalClient.GetFolder(ctx, req, opts...) +} + +// CreateFolder creates a Folder in the resource hierarchy. +// Returns an Operation which can be used to track the progress of the +// folder creation workflow. +// Upon success the Operation.response field will be populated with the +// created Folder. +// +// In order to succeed, the addition of this new Folder must not violate +// the Folder naming, height or fanout constraints. +// +// The Folder’s display_name must be distinct from all other Folder’s that +// share its parent. +// +// The addition of the Folder must not cause the active Folder hierarchy +// to exceed a height of 4. Note, the full active + deleted Folder hierarchy +// is allowed to reach a height of 8; this provides additional headroom when +// moving folders that contain deleted folders. +// +// The addition of the Folder must not cause the total number of Folders +// under its parent to exceed 100. +// +// If the operation fails due to a folder constraint violation, some errors +// may be returned by the CreateFolder request, with status code +// FAILED_PRECONDITION and an error description. Other folder constraint +// violations will be communicated in the Operation, with the specific +// PreconditionFailure returned via the details list in the Operation.error +// field. +// +// The caller must have resourcemanager.folders.create permission on the +// identified parent. +func (c *FoldersClient) CreateFolder(ctx context.Context, req *resourcemanagerpb.CreateFolderRequest, opts ...gax.CallOption) (*CreateFolderOperation, error) { + return c.internalClient.CreateFolder(ctx, req, opts...) +} + +// CreateFolderOperation returns a new CreateFolderOperation from a given name. +// The name must be that of a previously created CreateFolderOperation, possibly from a different process. +func (c *FoldersClient) CreateFolderOperation(name string) *CreateFolderOperation { + return c.internalClient.CreateFolderOperation(name) +} + +// UpdateFolder updates a Folder, changing its display_name. +// Changes to the folder display_name will be rejected if they violate either +// the display_name formatting rules or naming constraints described in +// the CreateFolder documentation. +// +// The Folder’s display name must start and end with a letter or digit, +// may contain letters, digits, spaces, hyphens and underscores and can be +// no longer than 30 characters. This is captured by the regular expression: +// [\p{L}\p{N}]([\p{L}\p{N}_- ]{0,28}[\p{L}\p{N}])?. +// The caller must have resourcemanager.folders.update permission on the +// identified folder. +// +// If the update fails due to the unique name constraint then a +// PreconditionFailure explaining this violation will be returned +// in the Status.details field. +func (c *FoldersClient) UpdateFolder(ctx context.Context, req *resourcemanagerpb.UpdateFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + return c.internalClient.UpdateFolder(ctx, req, opts...) +} + +// MoveFolder moves a Folder under a new resource parent. +// Returns an Operation which can be used to track the progress of the +// folder move workflow. +// Upon success the Operation.response field will be populated with the +// moved Folder. +// Upon failure, a FolderOperationError categorizing the failure cause will +// be returned - if the failure occurs synchronously then the +// FolderOperationError will be returned via the Status.details field +// and if it occurs asynchronously then the FolderOperation will be returned +// via the Operation.error field. +// In addition, the Operation.metadata field will be populated with a +// FolderOperation message as an aid to stateless clients. +// Folder moves will be rejected if they violate either the naming, height +// or fanout constraints described in the +// CreateFolder documentation. +// The caller must have resourcemanager.folders.move permission on the +// folder’s current and proposed new parent. +func (c *FoldersClient) MoveFolder(ctx context.Context, req *resourcemanagerpb.MoveFolderRequest, opts ...gax.CallOption) (*MoveFolderOperation, error) { + return c.internalClient.MoveFolder(ctx, req, opts...) +} + +// MoveFolderOperation returns a new MoveFolderOperation from a given name. +// The name must be that of a previously created MoveFolderOperation, possibly from a different process. +func (c *FoldersClient) MoveFolderOperation(name string) *MoveFolderOperation { + return c.internalClient.MoveFolderOperation(name) +} + +// DeleteFolder requests deletion of a Folder. The Folder is moved into the +// DELETE_REQUESTED state +// immediately, and is deleted approximately 30 days later. This method may +// only be called on an empty Folder in the +// [ACTIVE][google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE (at http://google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE)] state, where a Folder is empty if +// it doesn’t contain any Folders or Projects in the +// [ACTIVE][google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE (at http://google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE)] state. +// The caller must have resourcemanager.folders.delete permission on the +// identified folder. +func (c *FoldersClient) DeleteFolder(ctx context.Context, req *resourcemanagerpb.DeleteFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + return c.internalClient.DeleteFolder(ctx, req, opts...) +} + +// UndeleteFolder cancels the deletion request for a Folder. This method may only be +// called on a Folder in the +// DELETE_REQUESTED state. +// In order to succeed, the Folder’s parent must be in the +// [ACTIVE][google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE (at http://google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE)] state. +// In addition, reintroducing the folder into the tree must not violate +// folder naming, height and fanout constraints described in the +// CreateFolder documentation. +// The caller must have resourcemanager.folders.undelete permission on the +// identified folder. +func (c *FoldersClient) UndeleteFolder(ctx context.Context, req *resourcemanagerpb.UndeleteFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { + return c.internalClient.UndeleteFolder(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy for a Folder. The returned policy may be +// empty if no such policy or resource exists. The resource field should +// be the Folder’s resource name, e.g. “folders/1234”. +// The caller must have resourcemanager.folders.getIamPolicy permission +// on the identified folder. +func (c *FoldersClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// SetIamPolicy sets the access control policy on a Folder, replacing any existing policy. +// The resource field should be the Folder’s resource name, e.g. +// “folders/1234”. +// The caller must have resourcemanager.folders.setIamPolicy permission +// on the identified folder. +func (c *FoldersClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns permissions that a caller has on the specified Folder. +// The resource field should be the Folder’s resource name, +// e.g. “folders/1234”. +// +// There are no permissions required for making this API call. +func (c *FoldersClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// foldersGRPCClient is a client for interacting with Cloud Resource Manager API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type foldersGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing FoldersClient + CallOptions **FoldersCallOptions + // The gRPC API client. foldersClient resourcemanagerpb.FoldersClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *FoldersCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewFoldersClient creates a new folders client. +// NewFoldersClient creates a new folders client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Manages Cloud Resource Folders. // Cloud Resource Folders can be used to organize the resources under an // organization and to control the IAM policies applied to groups of resources. func NewFoldersClient(ctx context.Context, opts ...option.ClientOption) (*FoldersClient, error) { - clientOpts := defaultFoldersClientOptions() - + clientOpts := defaultFoldersGRPCClientOptions() if newFoldersClientHook != nil { hookOpts, err := newFoldersClientHook(ctx, clientHookParams{}) if err != nil { @@ -133,16 +363,19 @@ func NewFoldersClient(ctx context.Context, opts ...option.ClientOption) (*Folder if err != nil { return nil, err } - c := &FoldersClient{ + client := FoldersClient{CallOptions: defaultFoldersCallOptions()} + + c := &foldersGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultFoldersCallOptions(), - - foldersClient: resourcemanagerpb.NewFoldersClient(connPool), + foldersClient: resourcemanagerpb.NewFoldersClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -152,41 +385,35 @@ func NewFoldersClient(ctx context.Context, opts ...option.ClientOption) (*Folder // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *FoldersClient) Connection() *grpc.ClientConn { +func (c *foldersGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *FoldersClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *FoldersClient) setGoogleClientInfo(keyval ...string) { +func (c *foldersGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListFolders lists the Folders that are direct descendants of supplied parent resource. -// List provides a strongly consistent view of the Folders underneath -// the specified parent resource. -// List returns Folders sorted based upon the (ascending) lexical ordering -// of their display_name. -// The caller must have resourcemanager.folders.list permission on the -// identified parent. -func (c *FoldersClient) ListFolders(ctx context.Context, req *resourcemanagerpb.ListFoldersRequest, opts ...gax.CallOption) *FolderIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *foldersGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *foldersGRPCClient) ListFolders(ctx context.Context, req *resourcemanagerpb.ListFoldersRequest, opts ...gax.CallOption) *FolderIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListFolders[0:len(c.CallOptions.ListFolders):len(c.CallOptions.ListFolders)], opts...) + opts = append((*c.CallOptions).ListFolders[0:len((*c.CallOptions).ListFolders):len((*c.CallOptions).ListFolders)], opts...) it := &FolderIterator{} req = proto.Clone(req).(*resourcemanagerpb.ListFoldersRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*resourcemanagerpb.Folder, string, error) { @@ -223,15 +450,9 @@ func (c *FoldersClient) ListFolders(ctx context.Context, req *resourcemanagerpb. return it } -// SearchFolders search for folders that match specific filter criteria. -// Search provides an eventually consistent view of the folders a user has -// access to which meet the specified filter criteria. -// -// This will only return folders on which the caller has the -// permission resourcemanager.folders.get. -func (c *FoldersClient) SearchFolders(ctx context.Context, req *resourcemanagerpb.SearchFoldersRequest, opts ...gax.CallOption) *FolderIterator { +func (c *foldersGRPCClient) SearchFolders(ctx context.Context, req *resourcemanagerpb.SearchFoldersRequest, opts ...gax.CallOption) *FolderIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.SearchFolders[0:len(c.CallOptions.SearchFolders):len(c.CallOptions.SearchFolders)], opts...) + opts = append((*c.CallOptions).SearchFolders[0:len((*c.CallOptions).SearchFolders):len((*c.CallOptions).SearchFolders)], opts...) it := &FolderIterator{} req = proto.Clone(req).(*resourcemanagerpb.SearchFoldersRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*resourcemanagerpb.Folder, string, error) { @@ -268,15 +489,10 @@ func (c *FoldersClient) SearchFolders(ctx context.Context, req *resourcemanagerp return it } -// GetFolder retrieves a Folder identified by the supplied resource name. -// Valid Folder resource names have the format folders/{folder_id} -// (for example, folders/1234). -// The caller must have resourcemanager.folders.get permission on the -// identified folder. -func (c *FoldersClient) GetFolder(ctx context.Context, req *resourcemanagerpb.GetFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { +func (c *foldersGRPCClient) GetFolder(ctx context.Context, req *resourcemanagerpb.GetFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetFolder[0:len(c.CallOptions.GetFolder):len(c.CallOptions.GetFolder)], opts...) + opts = append((*c.CallOptions).GetFolder[0:len((*c.CallOptions).GetFolder):len((*c.CallOptions).GetFolder)], opts...) var resp *resourcemanagerpb.Folder err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -289,38 +505,9 @@ func (c *FoldersClient) GetFolder(ctx context.Context, req *resourcemanagerpb.Ge return resp, nil } -// CreateFolder creates a Folder in the resource hierarchy. -// Returns an Operation which can be used to track the progress of the -// folder creation workflow. -// Upon success the Operation.response field will be populated with the -// created Folder. -// -// In order to succeed, the addition of this new Folder must not violate -// the Folder naming, height or fanout constraints. -// -// The Folder’s display_name must be distinct from all other Folder’s that -// share its parent. -// -// The addition of the Folder must not cause the active Folder hierarchy -// to exceed a height of 4. Note, the full active + deleted Folder hierarchy -// is allowed to reach a height of 8; this provides additional headroom when -// moving folders that contain deleted folders. -// -// The addition of the Folder must not cause the total number of Folders -// under its parent to exceed 100. -// -// If the operation fails due to a folder constraint violation, some errors -// may be returned by the CreateFolder request, with status code -// FAILED_PRECONDITION and an error description. Other folder constraint -// violations will be communicated in the Operation, with the specific -// PreconditionFailure returned via the details list in the Operation.error -// field. -// -// The caller must have resourcemanager.folders.create permission on the -// identified parent. -func (c *FoldersClient) CreateFolder(ctx context.Context, req *resourcemanagerpb.CreateFolderRequest, opts ...gax.CallOption) (*CreateFolderOperation, error) { +func (c *foldersGRPCClient) CreateFolder(ctx context.Context, req *resourcemanagerpb.CreateFolderRequest, opts ...gax.CallOption) (*CreateFolderOperation, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.CreateFolder[0:len(c.CallOptions.CreateFolder):len(c.CallOptions.CreateFolder)], opts...) + opts = append((*c.CallOptions).CreateFolder[0:len((*c.CallOptions).CreateFolder):len((*c.CallOptions).CreateFolder)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -331,29 +518,14 @@ func (c *FoldersClient) CreateFolder(ctx context.Context, req *resourcemanagerpb return nil, err } return &CreateFolderOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateFolder updates a Folder, changing its display_name. -// Changes to the folder display_name will be rejected if they violate either -// the display_name formatting rules or naming constraints described in -// the CreateFolder documentation. -// -// The Folder’s display name must start and end with a letter or digit, -// may contain letters, digits, spaces, hyphens and underscores and can be -// no longer than 30 characters. This is captured by the regular expression: -// [\p{L}\p{N}]([\p{L}\p{N}_- ]{0,28}[\p{L}\p{N}])?. -// The caller must have resourcemanager.folders.update permission on the -// identified folder. -// -// If the update fails due to the unique name constraint then a -// PreconditionFailure explaining this violation will be returned -// in the Status.details field. -func (c *FoldersClient) UpdateFolder(ctx context.Context, req *resourcemanagerpb.UpdateFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { +func (c *foldersGRPCClient) UpdateFolder(ctx context.Context, req *resourcemanagerpb.UpdateFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "folder.name", url.QueryEscape(req.GetFolder().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateFolder[0:len(c.CallOptions.UpdateFolder):len(c.CallOptions.UpdateFolder)], opts...) + opts = append((*c.CallOptions).UpdateFolder[0:len((*c.CallOptions).UpdateFolder):len((*c.CallOptions).UpdateFolder)], opts...) var resp *resourcemanagerpb.Folder err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -366,27 +538,10 @@ func (c *FoldersClient) UpdateFolder(ctx context.Context, req *resourcemanagerpb return resp, nil } -// MoveFolder moves a Folder under a new resource parent. -// Returns an Operation which can be used to track the progress of the -// folder move workflow. -// Upon success the Operation.response field will be populated with the -// moved Folder. -// Upon failure, a FolderOperationError categorizing the failure cause will -// be returned - if the failure occurs synchronously then the -// FolderOperationError will be returned via the Status.details field -// and if it occurs asynchronously then the FolderOperation will be returned -// via the Operation.error field. -// In addition, the Operation.metadata field will be populated with a -// FolderOperation message as an aid to stateless clients. -// Folder moves will be rejected if they violate either the naming, height -// or fanout constraints described in the -// CreateFolder documentation. -// The caller must have resourcemanager.folders.move permission on the -// folder’s current and proposed new parent. -func (c *FoldersClient) MoveFolder(ctx context.Context, req *resourcemanagerpb.MoveFolderRequest, opts ...gax.CallOption) (*MoveFolderOperation, error) { +func (c *foldersGRPCClient) MoveFolder(ctx context.Context, req *resourcemanagerpb.MoveFolderRequest, opts ...gax.CallOption) (*MoveFolderOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.MoveFolder[0:len(c.CallOptions.MoveFolder):len(c.CallOptions.MoveFolder)], opts...) + opts = append((*c.CallOptions).MoveFolder[0:len((*c.CallOptions).MoveFolder):len((*c.CallOptions).MoveFolder)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -397,23 +552,14 @@ func (c *FoldersClient) MoveFolder(ctx context.Context, req *resourcemanagerpb.M return nil, err } return &MoveFolderOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteFolder requests deletion of a Folder. The Folder is moved into the -// DELETE_REQUESTED state -// immediately, and is deleted approximately 30 days later. This method may -// only be called on an empty Folder in the -// [ACTIVE][google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE (at http://google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE)] state, where a Folder is empty if -// it doesn’t contain any Folders or Projects in the -// [ACTIVE][google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE (at http://google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE)] state. -// The caller must have resourcemanager.folders.delete permission on the -// identified folder. -func (c *FoldersClient) DeleteFolder(ctx context.Context, req *resourcemanagerpb.DeleteFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { +func (c *foldersGRPCClient) DeleteFolder(ctx context.Context, req *resourcemanagerpb.DeleteFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteFolder[0:len(c.CallOptions.DeleteFolder):len(c.CallOptions.DeleteFolder)], opts...) + opts = append((*c.CallOptions).DeleteFolder[0:len((*c.CallOptions).DeleteFolder):len((*c.CallOptions).DeleteFolder)], opts...) var resp *resourcemanagerpb.Folder err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -426,20 +572,10 @@ func (c *FoldersClient) DeleteFolder(ctx context.Context, req *resourcemanagerpb return resp, nil } -// UndeleteFolder cancels the deletion request for a Folder. This method may only be -// called on a Folder in the -// DELETE_REQUESTED state. -// In order to succeed, the Folder’s parent must be in the -// [ACTIVE][google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE (at http://google.cloud.resourcemanager.v2.Folder.LifecycleState.ACTIVE)] state. -// In addition, reintroducing the folder into the tree must not violate -// folder naming, height and fanout constraints described in the -// CreateFolder documentation. -// The caller must have resourcemanager.folders.undelete permission on the -// identified folder. -func (c *FoldersClient) UndeleteFolder(ctx context.Context, req *resourcemanagerpb.UndeleteFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { +func (c *foldersGRPCClient) UndeleteFolder(ctx context.Context, req *resourcemanagerpb.UndeleteFolderRequest, opts ...gax.CallOption) (*resourcemanagerpb.Folder, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UndeleteFolder[0:len(c.CallOptions.UndeleteFolder):len(c.CallOptions.UndeleteFolder)], opts...) + opts = append((*c.CallOptions).UndeleteFolder[0:len((*c.CallOptions).UndeleteFolder):len((*c.CallOptions).UndeleteFolder)], opts...) var resp *resourcemanagerpb.Folder err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -452,15 +588,10 @@ func (c *FoldersClient) UndeleteFolder(ctx context.Context, req *resourcemanager return resp, nil } -// GetIamPolicy gets the access control policy for a Folder. The returned policy may be -// empty if no such policy or resource exists. The resource field should -// be the Folder’s resource name, e.g. “folders/1234”. -// The caller must have resourcemanager.folders.getIamPolicy permission -// on the identified folder. -func (c *FoldersClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *foldersGRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -473,15 +604,10 @@ func (c *FoldersClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolic return resp, nil } -// SetIamPolicy sets the access control policy on a Folder, replacing any existing policy. -// The resource field should be the Folder’s resource name, e.g. -// “folders/1234”. -// The caller must have resourcemanager.folders.setIamPolicy permission -// on the identified folder. -func (c *FoldersClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *foldersGRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -494,15 +620,10 @@ func (c *FoldersClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolic return resp, nil } -// TestIamPermissions returns permissions that a caller has on the specified Folder. -// The resource field should be the Folder’s resource name, -// e.g. “folders/1234”. -// -// There are no permissions required for making this API call. -func (c *FoldersClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *foldersGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -522,9 +643,9 @@ type CreateFolderOperation struct { // CreateFolderOperation returns a new CreateFolderOperation from a given name. // The name must be that of a previously created CreateFolderOperation, possibly from a different process. -func (c *FoldersClient) CreateFolderOperation(name string) *CreateFolderOperation { +func (c *foldersGRPCClient) CreateFolderOperation(name string) *CreateFolderOperation { return &CreateFolderOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -591,9 +712,9 @@ type MoveFolderOperation struct { // MoveFolderOperation returns a new MoveFolderOperation from a given name. // The name must be that of a previously created MoveFolderOperation, possibly from a different process. -func (c *FoldersClient) MoveFolderOperation(name string) *MoveFolderOperation { +func (c *foldersGRPCClient) MoveFolderOperation(name string) *MoveFolderOperation { return &MoveFolderOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/resourcemanager/apiv2/folders_client_example_test.go b/resourcemanager/apiv2/folders_client_example_test.go index bb6b652cd053..37135637a55e 100644 --- a/resourcemanager/apiv2/folders_client_example_test.go +++ b/resourcemanager/apiv2/folders_client_example_test.go @@ -31,19 +31,19 @@ func ExampleNewFoldersClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleFoldersClient_ListFolders() { - // import resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcemanagerpb.ListFoldersRequest{ // TODO: Fill request struct fields. @@ -63,14 +63,12 @@ func ExampleFoldersClient_ListFolders() { } func ExampleFoldersClient_SearchFolders() { - // import resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcemanagerpb.SearchFoldersRequest{ // TODO: Fill request struct fields. @@ -90,13 +88,12 @@ func ExampleFoldersClient_SearchFolders() { } func ExampleFoldersClient_GetFolder() { - // import resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v2" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcemanagerpb.GetFolderRequest{ // TODO: Fill request struct fields. @@ -110,13 +107,12 @@ func ExampleFoldersClient_GetFolder() { } func ExampleFoldersClient_CreateFolder() { - // import resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v2" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcemanagerpb.CreateFolderRequest{ // TODO: Fill request struct fields. @@ -135,13 +131,12 @@ func ExampleFoldersClient_CreateFolder() { } func ExampleFoldersClient_UpdateFolder() { - // import resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v2" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcemanagerpb.UpdateFolderRequest{ // TODO: Fill request struct fields. @@ -155,13 +150,12 @@ func ExampleFoldersClient_UpdateFolder() { } func ExampleFoldersClient_MoveFolder() { - // import resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v2" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcemanagerpb.MoveFolderRequest{ // TODO: Fill request struct fields. @@ -180,13 +174,12 @@ func ExampleFoldersClient_MoveFolder() { } func ExampleFoldersClient_DeleteFolder() { - // import resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v2" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcemanagerpb.DeleteFolderRequest{ // TODO: Fill request struct fields. @@ -200,13 +193,12 @@ func ExampleFoldersClient_DeleteFolder() { } func ExampleFoldersClient_UndeleteFolder() { - // import resourcemanagerpb "google.golang.org/genproto/googleapis/cloud/resourcemanager/v2" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcemanagerpb.UndeleteFolderRequest{ // TODO: Fill request struct fields. @@ -220,13 +212,12 @@ func ExampleFoldersClient_UndeleteFolder() { } func ExampleFoldersClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -240,13 +231,12 @@ func ExampleFoldersClient_GetIamPolicy() { } func ExampleFoldersClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -260,13 +250,12 @@ func ExampleFoldersClient_SetIamPolicy() { } func ExampleFoldersClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := resourcemanager.NewFoldersClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/resourcesettings/apiv1/doc.go b/resourcesettings/apiv1/doc.go index 71ab0c266888..b6a86d1572cd 100644 --- a/resourcesettings/apiv1/doc.go +++ b/resourcesettings/apiv1/doc.go @@ -21,6 +21,8 @@ // of their GCP resources (e.g., VM, firewall, Project, etc.) across the // Cloud Resource Hierarchy. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -30,7 +32,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package resourcesettings // import "cloud.google.com/go/resourcesettings/apiv1" import ( @@ -50,7 +52,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/resourcesettings/apiv1/resource_settings_client.go b/resourcesettings/apiv1/resource_settings_client.go index d4113d435f1d..a86f74dde1cd 100644 --- a/resourcesettings/apiv1/resource_settings_client.go +++ b/resourcesettings/apiv1/resource_settings_client.go @@ -44,7 +44,7 @@ type CallOptions struct { UpdateSetting []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("resourcesettings.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("resourcesettings.mtls.googleapis.com:443"), @@ -75,27 +75,116 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Resource Settings API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListSettings(context.Context, *resourcesettingspb.ListSettingsRequest, ...gax.CallOption) *SettingIterator + GetSetting(context.Context, *resourcesettingspb.GetSettingRequest, ...gax.CallOption) (*resourcesettingspb.Setting, error) + UpdateSetting(context.Context, *resourcesettingspb.UpdateSettingRequest, ...gax.CallOption) (*resourcesettingspb.Setting, error) +} + // Client is a client for interacting with Resource Settings API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// An interface to interact with resource settings and setting values throughout +// the resource hierarchy. +// +// Services may surface a number of settings for users to control how their +// resources behave. Values of settings applied on a given Cloud resource are +// evaluated hierarchically and inherited by all descendants of that resource. +// +// For all requests, returns a google.rpc.Status with +// google.rpc.Code.PERMISSION_DENIED if the IAM check fails or the parent +// resource is not in a Cloud Organization. +// For all requests, returns a google.rpc.Status with +// google.rpc.Code.INVALID_ARGUMENT if the request is malformed. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListSettings lists all the settings that are available on the Cloud resource parent. +func (c *Client) ListSettings(ctx context.Context, req *resourcesettingspb.ListSettingsRequest, opts ...gax.CallOption) *SettingIterator { + return c.internalClient.ListSettings(ctx, req, opts...) +} + +// GetSetting gets a setting. +// +// Returns a google.rpc.Status with google.rpc.Code.NOT_FOUND if the +// setting does not exist. +func (c *Client) GetSetting(ctx context.Context, req *resourcesettingspb.GetSettingRequest, opts ...gax.CallOption) (*resourcesettingspb.Setting, error) { + return c.internalClient.GetSetting(ctx, req, opts...) +} + +// UpdateSetting updates a setting. +// +// Returns a google.rpc.Status with google.rpc.Code.NOT_FOUND if the +// setting does not exist. +// Returns a google.rpc.Status with google.rpc.Code.FAILED_PRECONDITION if +// the setting is flagged as read only. +// Returns a google.rpc.Status with google.rpc.Code.ABORTED if the etag +// supplied in the request does not match the persisted etag of the setting +// value. +// +// On success, the response will contain only name, local_value and +// etag. The metadata and effective_value cannot be updated through +// this API. +// +// Note: the supplied setting will perform a full overwrite of the +// local_value field. +func (c *Client) UpdateSetting(ctx context.Context, req *resourcesettingspb.UpdateSettingRequest, opts ...gax.CallOption) (*resourcesettingspb.Setting, error) { + return c.internalClient.UpdateSetting(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Resource Settings API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client resourcesettingspb.ResourceSettingsServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new resource settings service client. +// NewClient creates a new resource settings service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // An interface to interact with resource settings and setting values throughout // the resource hierarchy. @@ -110,8 +199,7 @@ type Client struct { // For all requests, returns a google.rpc.Status with // google.rpc.Code.INVALID_ARGUMENT if the request is malformed. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -129,45 +217,47 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: resourcesettingspb.NewResourceSettingsServiceClient(connPool), + client: resourcesettingspb.NewResourceSettingsServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListSettings lists all the settings that are available on the Cloud resource parent. -func (c *Client) ListSettings(ctx context.Context, req *resourcesettingspb.ListSettingsRequest, opts ...gax.CallOption) *SettingIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ListSettings(ctx context.Context, req *resourcesettingspb.ListSettingsRequest, opts ...gax.CallOption) *SettingIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSettings[0:len(c.CallOptions.ListSettings):len(c.CallOptions.ListSettings)], opts...) + opts = append((*c.CallOptions).ListSettings[0:len((*c.CallOptions).ListSettings):len((*c.CallOptions).ListSettings)], opts...) it := &SettingIterator{} req = proto.Clone(req).(*resourcesettingspb.ListSettingsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*resourcesettingspb.Setting, string, error) { @@ -204,14 +294,10 @@ func (c *Client) ListSettings(ctx context.Context, req *resourcesettingspb.ListS return it } -// GetSetting gets a setting. -// -// Returns a google.rpc.Status with google.rpc.Code.NOT_FOUND if the -// setting does not exist. -func (c *Client) GetSetting(ctx context.Context, req *resourcesettingspb.GetSettingRequest, opts ...gax.CallOption) (*resourcesettingspb.Setting, error) { +func (c *gRPCClient) GetSetting(ctx context.Context, req *resourcesettingspb.GetSettingRequest, opts ...gax.CallOption) (*resourcesettingspb.Setting, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSetting[0:len(c.CallOptions.GetSetting):len(c.CallOptions.GetSetting)], opts...) + opts = append((*c.CallOptions).GetSetting[0:len((*c.CallOptions).GetSetting):len((*c.CallOptions).GetSetting)], opts...) var resp *resourcesettingspb.Setting err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -224,26 +310,10 @@ func (c *Client) GetSetting(ctx context.Context, req *resourcesettingspb.GetSett return resp, nil } -// UpdateSetting updates a setting. -// -// Returns a google.rpc.Status with google.rpc.Code.NOT_FOUND if the -// setting does not exist. -// Returns a google.rpc.Status with google.rpc.Code.FAILED_PRECONDITION if -// the setting is flagged as read only. -// Returns a google.rpc.Status with google.rpc.Code.ABORTED if the etag -// supplied in the request does not match the persisted etag of the setting -// value. -// -// On success, the response will contain only name, local_value and -// etag. The metadata and effective_value cannot be updated through -// this API. -// -// Note: the supplied setting will perform a full overwrite of the -// local_value field. -func (c *Client) UpdateSetting(ctx context.Context, req *resourcesettingspb.UpdateSettingRequest, opts ...gax.CallOption) (*resourcesettingspb.Setting, error) { +func (c *gRPCClient) UpdateSetting(ctx context.Context, req *resourcesettingspb.UpdateSettingRequest, opts ...gax.CallOption) (*resourcesettingspb.Setting, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "setting.name", url.QueryEscape(req.GetSetting().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSetting[0:len(c.CallOptions.UpdateSetting):len(c.CallOptions.UpdateSetting)], opts...) + opts = append((*c.CallOptions).UpdateSetting[0:len((*c.CallOptions).UpdateSetting):len((*c.CallOptions).UpdateSetting)], opts...) var resp *resourcesettingspb.Setting err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/resourcesettings/apiv1/resource_settings_client_example_test.go b/resourcesettings/apiv1/resource_settings_client_example_test.go index caefbd75045f..710748e42ec1 100644 --- a/resourcesettings/apiv1/resource_settings_client_example_test.go +++ b/resourcesettings/apiv1/resource_settings_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ListSettings() { - // import resourcesettingspb "google.golang.org/genproto/googleapis/cloud/resourcesettings/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := resourcesettings.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcesettingspb.ListSettingsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleClient_ListSettings() { } func ExampleClient_GetSetting() { - // import resourcesettingspb "google.golang.org/genproto/googleapis/cloud/resourcesettings/v1" - ctx := context.Background() c, err := resourcesettings.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcesettingspb.GetSettingRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleClient_GetSetting() { } func ExampleClient_UpdateSetting() { - // import resourcesettingspb "google.golang.org/genproto/googleapis/cloud/resourcesettings/v1" - ctx := context.Background() c, err := resourcesettings.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &resourcesettingspb.UpdateSettingRequest{ // TODO: Fill request struct fields. diff --git a/retail/apiv2/catalog_client.go b/retail/apiv2/catalog_client.go index cac491c233e3..688376b3ca3b 100644 --- a/retail/apiv2/catalog_client.go +++ b/retail/apiv2/catalog_client.go @@ -43,7 +43,7 @@ type CatalogCallOptions struct { UpdateCatalog []gax.CallOption } -func defaultCatalogClientOptions() []option.ClientOption { +func defaultCatalogGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("retail.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("retail.mtls.googleapis.com:443"), @@ -84,32 +84,86 @@ func defaultCatalogCallOptions() *CatalogCallOptions { } } +// internalCatalogClient is an interface that defines the methods availaible from Retail API. +type internalCatalogClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListCatalogs(context.Context, *retailpb.ListCatalogsRequest, ...gax.CallOption) *CatalogIterator + UpdateCatalog(context.Context, *retailpb.UpdateCatalogRequest, ...gax.CallOption) (*retailpb.Catalog, error) +} + // CatalogClient is a client for interacting with Retail API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for managing catalog configuration. type CatalogClient struct { + // The internal transport-dependent client. + internalClient internalCatalogClient + + // The call options for this service. + CallOptions *CatalogCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CatalogClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CatalogClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CatalogClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListCatalogs lists all the Catalogs associated with +// the project. +func (c *CatalogClient) ListCatalogs(ctx context.Context, req *retailpb.ListCatalogsRequest, opts ...gax.CallOption) *CatalogIterator { + return c.internalClient.ListCatalogs(ctx, req, opts...) +} + +// UpdateCatalog updates the Catalogs. +func (c *CatalogClient) UpdateCatalog(ctx context.Context, req *retailpb.UpdateCatalogRequest, opts ...gax.CallOption) (*retailpb.Catalog, error) { + return c.internalClient.UpdateCatalog(ctx, req, opts...) +} + +// catalogGRPCClient is a client for interacting with Retail API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type catalogGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CatalogClient + CallOptions **CatalogCallOptions + // The gRPC API client. catalogClient retailpb.CatalogServiceClient - // The call options for this service. - CallOptions *CatalogCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCatalogClient creates a new catalog service client. +// NewCatalogClient creates a new catalog service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for managing catalog configuration. func NewCatalogClient(ctx context.Context, opts ...option.ClientOption) (*CatalogClient, error) { - clientOpts := defaultCatalogClientOptions() - + clientOpts := defaultCatalogGRPCClientOptions() if newCatalogClientHook != nil { hookOpts, err := newCatalogClientHook(ctx, clientHookParams{}) if err != nil { @@ -127,46 +181,47 @@ func NewCatalogClient(ctx context.Context, opts ...option.ClientOption) (*Catalo if err != nil { return nil, err } - c := &CatalogClient{ + client := CatalogClient{CallOptions: defaultCatalogCallOptions()} + + c := &catalogGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCatalogCallOptions(), - - catalogClient: retailpb.NewCatalogServiceClient(connPool), + catalogClient: retailpb.NewCatalogServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CatalogClient) Connection() *grpc.ClientConn { +func (c *catalogGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CatalogClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CatalogClient) setGoogleClientInfo(keyval ...string) { +func (c *catalogGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListCatalogs lists all the Catalogs associated with -// the project. -func (c *CatalogClient) ListCatalogs(ctx context.Context, req *retailpb.ListCatalogsRequest, opts ...gax.CallOption) *CatalogIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *catalogGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *catalogGRPCClient) ListCatalogs(ctx context.Context, req *retailpb.ListCatalogsRequest, opts ...gax.CallOption) *CatalogIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCatalogs[0:len(c.CallOptions.ListCatalogs):len(c.CallOptions.ListCatalogs)], opts...) + opts = append((*c.CallOptions).ListCatalogs[0:len((*c.CallOptions).ListCatalogs):len((*c.CallOptions).ListCatalogs)], opts...) it := &CatalogIterator{} req = proto.Clone(req).(*retailpb.ListCatalogsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*retailpb.Catalog, string, error) { @@ -203,8 +258,7 @@ func (c *CatalogClient) ListCatalogs(ctx context.Context, req *retailpb.ListCata return it } -// UpdateCatalog updates the Catalogs. -func (c *CatalogClient) UpdateCatalog(ctx context.Context, req *retailpb.UpdateCatalogRequest, opts ...gax.CallOption) (*retailpb.Catalog, error) { +func (c *catalogGRPCClient) UpdateCatalog(ctx context.Context, req *retailpb.UpdateCatalogRequest, opts ...gax.CallOption) (*retailpb.Catalog, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -212,7 +266,7 @@ func (c *CatalogClient) UpdateCatalog(ctx context.Context, req *retailpb.UpdateC } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "catalog.name", url.QueryEscape(req.GetCatalog().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCatalog[0:len(c.CallOptions.UpdateCatalog):len(c.CallOptions.UpdateCatalog)], opts...) + opts = append((*c.CallOptions).UpdateCatalog[0:len((*c.CallOptions).UpdateCatalog):len((*c.CallOptions).UpdateCatalog)], opts...) var resp *retailpb.Catalog err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/retail/apiv2/catalog_client_example_test.go b/retail/apiv2/catalog_client_example_test.go index 5e50c68a3207..4d6213f757dd 100644 --- a/retail/apiv2/catalog_client_example_test.go +++ b/retail/apiv2/catalog_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewCatalogClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCatalogClient_ListCatalogs() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := retail.NewCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.ListCatalogsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleCatalogClient_ListCatalogs() { } func ExampleCatalogClient_UpdateCatalog() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewCatalogClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.UpdateCatalogRequest{ // TODO: Fill request struct fields. diff --git a/retail/apiv2/doc.go b/retail/apiv2/doc.go index 5bd6863aae00..c2fd29b91570 100644 --- a/retail/apiv2/doc.go +++ b/retail/apiv2/doc.go @@ -30,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package retail // import "cloud.google.com/go/retail/apiv2" import ( @@ -50,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/retail/apiv2/prediction_client.go b/retail/apiv2/prediction_client.go index 52dc2aa273bd..0c2deee8d0f4 100644 --- a/retail/apiv2/prediction_client.go +++ b/retail/apiv2/prediction_client.go @@ -40,7 +40,7 @@ type PredictionCallOptions struct { Predict []gax.CallOption } -func defaultPredictionClientOptions() []option.ClientOption { +func defaultPredictionGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("retail.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("retail.mtls.googleapis.com:443"), @@ -69,32 +69,79 @@ func defaultPredictionCallOptions() *PredictionCallOptions { } } +// internalPredictionClient is an interface that defines the methods availaible from Retail API. +type internalPredictionClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + Predict(context.Context, *retailpb.PredictRequest, ...gax.CallOption) (*retailpb.PredictResponse, error) +} + // PredictionClient is a client for interacting with Retail API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for making recommendation prediction. type PredictionClient struct { + // The internal transport-dependent client. + internalClient internalPredictionClient + + // The call options for this service. + CallOptions *PredictionCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *PredictionClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *PredictionClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *PredictionClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// Predict makes a recommendation prediction. +func (c *PredictionClient) Predict(ctx context.Context, req *retailpb.PredictRequest, opts ...gax.CallOption) (*retailpb.PredictResponse, error) { + return c.internalClient.Predict(ctx, req, opts...) +} + +// predictionGRPCClient is a client for interacting with Retail API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type predictionGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing PredictionClient + CallOptions **PredictionCallOptions + // The gRPC API client. predictionClient retailpb.PredictionServiceClient - // The call options for this service. - CallOptions *PredictionCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewPredictionClient creates a new prediction service client. +// NewPredictionClient creates a new prediction service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for making recommendation prediction. func NewPredictionClient(ctx context.Context, opts ...option.ClientOption) (*PredictionClient, error) { - clientOpts := defaultPredictionClientOptions() - + clientOpts := defaultPredictionGRPCClientOptions() if newPredictionClientHook != nil { hookOpts, err := newPredictionClientHook(ctx, clientHookParams{}) if err != nil { @@ -112,42 +159,44 @@ func NewPredictionClient(ctx context.Context, opts ...option.ClientOption) (*Pre if err != nil { return nil, err } - c := &PredictionClient{ + client := PredictionClient{CallOptions: defaultPredictionCallOptions()} + + c := &predictionGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultPredictionCallOptions(), - predictionClient: retailpb.NewPredictionServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *PredictionClient) Connection() *grpc.ClientConn { +func (c *predictionGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *PredictionClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *PredictionClient) setGoogleClientInfo(keyval ...string) { +func (c *predictionGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// Predict makes a recommendation prediction. -func (c *PredictionClient) Predict(ctx context.Context, req *retailpb.PredictRequest, opts ...gax.CallOption) (*retailpb.PredictResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *predictionGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *predictionGRPCClient) Predict(ctx context.Context, req *retailpb.PredictRequest, opts ...gax.CallOption) (*retailpb.PredictResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -155,7 +204,7 @@ func (c *PredictionClient) Predict(ctx context.Context, req *retailpb.PredictReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "placement", url.QueryEscape(req.GetPlacement()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.Predict[0:len(c.CallOptions.Predict):len(c.CallOptions.Predict)], opts...) + opts = append((*c.CallOptions).Predict[0:len((*c.CallOptions).Predict):len((*c.CallOptions).Predict)], opts...) var resp *retailpb.PredictResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/retail/apiv2/prediction_client_example_test.go b/retail/apiv2/prediction_client_example_test.go index 8ff7685cf87d..c41cc2c5afd1 100644 --- a/retail/apiv2/prediction_client_example_test.go +++ b/retail/apiv2/prediction_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewPredictionClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExamplePredictionClient_Predict() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewPredictionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.PredictRequest{ // TODO: Fill request struct fields. diff --git a/retail/apiv2/product_client.go b/retail/apiv2/product_client.go index 0e063105327b..ed3b3a2f65bc 100644 --- a/retail/apiv2/product_client.go +++ b/retail/apiv2/product_client.go @@ -47,7 +47,7 @@ type ProductCallOptions struct { ImportProducts []gax.CallOption } -func defaultProductClientOptions() []option.ClientOption { +func defaultProductGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("retail.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("retail.mtls.googleapis.com:443"), @@ -124,38 +124,128 @@ func defaultProductCallOptions() *ProductCallOptions { } } +// internalProductClient is an interface that defines the methods availaible from Retail API. +type internalProductClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateProduct(context.Context, *retailpb.CreateProductRequest, ...gax.CallOption) (*retailpb.Product, error) + GetProduct(context.Context, *retailpb.GetProductRequest, ...gax.CallOption) (*retailpb.Product, error) + UpdateProduct(context.Context, *retailpb.UpdateProductRequest, ...gax.CallOption) (*retailpb.Product, error) + DeleteProduct(context.Context, *retailpb.DeleteProductRequest, ...gax.CallOption) error + ImportProducts(context.Context, *retailpb.ImportProductsRequest, ...gax.CallOption) (*ImportProductsOperation, error) + ImportProductsOperation(name string) *ImportProductsOperation +} + // ProductClient is a client for interacting with Retail API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for ingesting Product information +// of the customer’s website. type ProductClient struct { + // The internal transport-dependent client. + internalClient internalProductClient + + // The call options for this service. + CallOptions *ProductCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ProductClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ProductClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ProductClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateProduct creates a Product. +func (c *ProductClient) CreateProduct(ctx context.Context, req *retailpb.CreateProductRequest, opts ...gax.CallOption) (*retailpb.Product, error) { + return c.internalClient.CreateProduct(ctx, req, opts...) +} + +// GetProduct gets a Product. +func (c *ProductClient) GetProduct(ctx context.Context, req *retailpb.GetProductRequest, opts ...gax.CallOption) (*retailpb.Product, error) { + return c.internalClient.GetProduct(ctx, req, opts...) +} + +// UpdateProduct updates a Product. +func (c *ProductClient) UpdateProduct(ctx context.Context, req *retailpb.UpdateProductRequest, opts ...gax.CallOption) (*retailpb.Product, error) { + return c.internalClient.UpdateProduct(ctx, req, opts...) +} + +// DeleteProduct deletes a Product. +func (c *ProductClient) DeleteProduct(ctx context.Context, req *retailpb.DeleteProductRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteProduct(ctx, req, opts...) +} + +// ImportProducts bulk import of multiple Products. +// +// Request processing may be synchronous. No partial updating is supported. +// Non-existing items are created. +// +// Note that it is possible for a subset of the +// Products to be successfully updated. +func (c *ProductClient) ImportProducts(ctx context.Context, req *retailpb.ImportProductsRequest, opts ...gax.CallOption) (*ImportProductsOperation, error) { + return c.internalClient.ImportProducts(ctx, req, opts...) +} + +// ImportProductsOperation returns a new ImportProductsOperation from a given name. +// The name must be that of a previously created ImportProductsOperation, possibly from a different process. +func (c *ProductClient) ImportProductsOperation(name string) *ImportProductsOperation { + return c.internalClient.ImportProductsOperation(name) +} + +// productGRPCClient is a client for interacting with Retail API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type productGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ProductClient + CallOptions **ProductCallOptions + // The gRPC API client. productClient retailpb.ProductServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *ProductCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewProductClient creates a new product service client. +// NewProductClient creates a new product service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for ingesting Product information // of the customer’s website. func NewProductClient(ctx context.Context, opts ...option.ClientOption) (*ProductClient, error) { - clientOpts := defaultProductClientOptions() - + clientOpts := defaultProductGRPCClientOptions() if newProductClientHook != nil { hookOpts, err := newProductClientHook(ctx, clientHookParams{}) if err != nil { @@ -173,16 +263,19 @@ func NewProductClient(ctx context.Context, opts ...option.ClientOption) (*Produc if err != nil { return nil, err } - c := &ProductClient{ + client := ProductClient{CallOptions: defaultProductCallOptions()} + + c := &productGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultProductCallOptions(), - - productClient: retailpb.NewProductServiceClient(connPool), + productClient: retailpb.NewProductServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -192,33 +285,33 @@ func NewProductClient(ctx context.Context, opts ...option.ClientOption) (*Produc // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ProductClient) Connection() *grpc.ClientConn { +func (c *productGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ProductClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ProductClient) setGoogleClientInfo(keyval ...string) { +func (c *productGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateProduct creates a Product. -func (c *ProductClient) CreateProduct(ctx context.Context, req *retailpb.CreateProductRequest, opts ...gax.CallOption) (*retailpb.Product, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *productGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *productGRPCClient) CreateProduct(ctx context.Context, req *retailpb.CreateProductRequest, opts ...gax.CallOption) (*retailpb.Product, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -226,7 +319,7 @@ func (c *ProductClient) CreateProduct(ctx context.Context, req *retailpb.CreateP } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateProduct[0:len(c.CallOptions.CreateProduct):len(c.CallOptions.CreateProduct)], opts...) + opts = append((*c.CallOptions).CreateProduct[0:len((*c.CallOptions).CreateProduct):len((*c.CallOptions).CreateProduct)], opts...) var resp *retailpb.Product err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -239,8 +332,7 @@ func (c *ProductClient) CreateProduct(ctx context.Context, req *retailpb.CreateP return resp, nil } -// GetProduct gets a Product. -func (c *ProductClient) GetProduct(ctx context.Context, req *retailpb.GetProductRequest, opts ...gax.CallOption) (*retailpb.Product, error) { +func (c *productGRPCClient) GetProduct(ctx context.Context, req *retailpb.GetProductRequest, opts ...gax.CallOption) (*retailpb.Product, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -248,7 +340,7 @@ func (c *ProductClient) GetProduct(ctx context.Context, req *retailpb.GetProduct } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetProduct[0:len(c.CallOptions.GetProduct):len(c.CallOptions.GetProduct)], opts...) + opts = append((*c.CallOptions).GetProduct[0:len((*c.CallOptions).GetProduct):len((*c.CallOptions).GetProduct)], opts...) var resp *retailpb.Product err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -261,8 +353,7 @@ func (c *ProductClient) GetProduct(ctx context.Context, req *retailpb.GetProduct return resp, nil } -// UpdateProduct updates a Product. -func (c *ProductClient) UpdateProduct(ctx context.Context, req *retailpb.UpdateProductRequest, opts ...gax.CallOption) (*retailpb.Product, error) { +func (c *productGRPCClient) UpdateProduct(ctx context.Context, req *retailpb.UpdateProductRequest, opts ...gax.CallOption) (*retailpb.Product, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -270,7 +361,7 @@ func (c *ProductClient) UpdateProduct(ctx context.Context, req *retailpb.UpdateP } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product.name", url.QueryEscape(req.GetProduct().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateProduct[0:len(c.CallOptions.UpdateProduct):len(c.CallOptions.UpdateProduct)], opts...) + opts = append((*c.CallOptions).UpdateProduct[0:len((*c.CallOptions).UpdateProduct):len((*c.CallOptions).UpdateProduct)], opts...) var resp *retailpb.Product err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -283,8 +374,7 @@ func (c *ProductClient) UpdateProduct(ctx context.Context, req *retailpb.UpdateP return resp, nil } -// DeleteProduct deletes a Product. -func (c *ProductClient) DeleteProduct(ctx context.Context, req *retailpb.DeleteProductRequest, opts ...gax.CallOption) error { +func (c *productGRPCClient) DeleteProduct(ctx context.Context, req *retailpb.DeleteProductRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -292,7 +382,7 @@ func (c *ProductClient) DeleteProduct(ctx context.Context, req *retailpb.DeleteP } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteProduct[0:len(c.CallOptions.DeleteProduct):len(c.CallOptions.DeleteProduct)], opts...) + opts = append((*c.CallOptions).DeleteProduct[0:len((*c.CallOptions).DeleteProduct):len((*c.CallOptions).DeleteProduct)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.productClient.DeleteProduct(ctx, req, settings.GRPC...) @@ -301,14 +391,7 @@ func (c *ProductClient) DeleteProduct(ctx context.Context, req *retailpb.DeleteP return err } -// ImportProducts bulk import of multiple Products. -// -// Request processing may be synchronous. No partial updating is supported. -// Non-existing items are created. -// -// Note that it is possible for a subset of the -// Products to be successfully updated. -func (c *ProductClient) ImportProducts(ctx context.Context, req *retailpb.ImportProductsRequest, opts ...gax.CallOption) (*ImportProductsOperation, error) { +func (c *productGRPCClient) ImportProducts(ctx context.Context, req *retailpb.ImportProductsRequest, opts ...gax.CallOption) (*ImportProductsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -316,7 +399,7 @@ func (c *ProductClient) ImportProducts(ctx context.Context, req *retailpb.Import } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportProducts[0:len(c.CallOptions.ImportProducts):len(c.CallOptions.ImportProducts)], opts...) + opts = append((*c.CallOptions).ImportProducts[0:len((*c.CallOptions).ImportProducts):len((*c.CallOptions).ImportProducts)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -327,7 +410,7 @@ func (c *ProductClient) ImportProducts(ctx context.Context, req *retailpb.Import return nil, err } return &ImportProductsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -338,9 +421,9 @@ type ImportProductsOperation struct { // ImportProductsOperation returns a new ImportProductsOperation from a given name. // The name must be that of a previously created ImportProductsOperation, possibly from a different process. -func (c *ProductClient) ImportProductsOperation(name string) *ImportProductsOperation { +func (c *productGRPCClient) ImportProductsOperation(name string) *ImportProductsOperation { return &ImportProductsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/retail/apiv2/product_client_example_test.go b/retail/apiv2/product_client_example_test.go index d64fdc29831e..f273a8362535 100644 --- a/retail/apiv2/product_client_example_test.go +++ b/retail/apiv2/product_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewProductClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleProductClient_CreateProduct() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewProductClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.CreateProductRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleProductClient_CreateProduct() { } func ExampleProductClient_GetProduct() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewProductClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.GetProductRequest{ // TODO: Fill request struct fields. @@ -74,13 +74,12 @@ func ExampleProductClient_GetProduct() { } func ExampleProductClient_UpdateProduct() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewProductClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.UpdateProductRequest{ // TODO: Fill request struct fields. @@ -99,6 +98,7 @@ func ExampleProductClient_DeleteProduct() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.DeleteProductRequest{ // TODO: Fill request struct fields. @@ -110,13 +110,12 @@ func ExampleProductClient_DeleteProduct() { } func ExampleProductClient_ImportProducts() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewProductClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.ImportProductsRequest{ // TODO: Fill request struct fields. diff --git a/retail/apiv2/user_event_client.go b/retail/apiv2/user_event_client.go index 3dffc1017f9c..70aced67fb9e 100644 --- a/retail/apiv2/user_event_client.go +++ b/retail/apiv2/user_event_client.go @@ -48,7 +48,7 @@ type UserEventCallOptions struct { RejoinUserEvents []gax.CallOption } -func defaultUserEventClientOptions() []option.ClientOption { +func defaultUserEventGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("retail.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("retail.mtls.googleapis.com:443"), @@ -125,37 +125,153 @@ func defaultUserEventCallOptions() *UserEventCallOptions { } } +// internalUserEventClient is an interface that defines the methods availaible from Retail API. +type internalUserEventClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + WriteUserEvent(context.Context, *retailpb.WriteUserEventRequest, ...gax.CallOption) (*retailpb.UserEvent, error) + CollectUserEvent(context.Context, *retailpb.CollectUserEventRequest, ...gax.CallOption) (*httpbodypb.HttpBody, error) + PurgeUserEvents(context.Context, *retailpb.PurgeUserEventsRequest, ...gax.CallOption) (*PurgeUserEventsOperation, error) + PurgeUserEventsOperation(name string) *PurgeUserEventsOperation + ImportUserEvents(context.Context, *retailpb.ImportUserEventsRequest, ...gax.CallOption) (*ImportUserEventsOperation, error) + ImportUserEventsOperation(name string) *ImportUserEventsOperation + RejoinUserEvents(context.Context, *retailpb.RejoinUserEventsRequest, ...gax.CallOption) (*RejoinUserEventsOperation, error) + RejoinUserEventsOperation(name string) *RejoinUserEventsOperation +} + // UserEventClient is a client for interacting with Retail API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service for ingesting end user actions on the customer website. type UserEventClient struct { + // The internal transport-dependent client. + internalClient internalUserEventClient + + // The call options for this service. + CallOptions *UserEventCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *UserEventClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *UserEventClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *UserEventClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// WriteUserEvent writes a single user event. +func (c *UserEventClient) WriteUserEvent(ctx context.Context, req *retailpb.WriteUserEventRequest, opts ...gax.CallOption) (*retailpb.UserEvent, error) { + return c.internalClient.WriteUserEvent(ctx, req, opts...) +} + +// CollectUserEvent writes a single user event from the browser. This uses a GET request to +// due to browser restriction of POST-ing to a 3rd party domain. +// +// This method is used only by the Retail API JavaScript pixel and Google Tag +// Manager. Users should not call this method directly. +func (c *UserEventClient) CollectUserEvent(ctx context.Context, req *retailpb.CollectUserEventRequest, opts ...gax.CallOption) (*httpbodypb.HttpBody, error) { + return c.internalClient.CollectUserEvent(ctx, req, opts...) +} + +// PurgeUserEvents deletes permanently all user events specified by the filter provided. +// Depending on the number of events specified by the filter, this operation +// could take hours or days to complete. To test a filter, use the list +// command first. +func (c *UserEventClient) PurgeUserEvents(ctx context.Context, req *retailpb.PurgeUserEventsRequest, opts ...gax.CallOption) (*PurgeUserEventsOperation, error) { + return c.internalClient.PurgeUserEvents(ctx, req, opts...) +} + +// PurgeUserEventsOperation returns a new PurgeUserEventsOperation from a given name. +// The name must be that of a previously created PurgeUserEventsOperation, possibly from a different process. +func (c *UserEventClient) PurgeUserEventsOperation(name string) *PurgeUserEventsOperation { + return c.internalClient.PurgeUserEventsOperation(name) +} + +// ImportUserEvents bulk import of User events. Request processing might be +// synchronous. Events that already exist are skipped. +// Use this method for backfilling historical user events. +// +// Operation.response is of type ImportResponse. Note that it is +// possible for a subset of the items to be successfully inserted. +// Operation.metadata is of type ImportMetadata. +func (c *UserEventClient) ImportUserEvents(ctx context.Context, req *retailpb.ImportUserEventsRequest, opts ...gax.CallOption) (*ImportUserEventsOperation, error) { + return c.internalClient.ImportUserEvents(ctx, req, opts...) +} + +// ImportUserEventsOperation returns a new ImportUserEventsOperation from a given name. +// The name must be that of a previously created ImportUserEventsOperation, possibly from a different process. +func (c *UserEventClient) ImportUserEventsOperation(name string) *ImportUserEventsOperation { + return c.internalClient.ImportUserEventsOperation(name) +} + +// RejoinUserEvents triggers a user event rejoin operation with latest product catalog. Events +// will not be annotated with detailed product information if product is +// missing from the catalog at the time the user event is ingested, and these +// events are stored as unjoined events with a limited usage on training and +// serving. This API can be used to trigger a ‘join’ operation on specified +// events with latest version of product catalog. It can also be used to +// correct events joined with wrong product catalog. +func (c *UserEventClient) RejoinUserEvents(ctx context.Context, req *retailpb.RejoinUserEventsRequest, opts ...gax.CallOption) (*RejoinUserEventsOperation, error) { + return c.internalClient.RejoinUserEvents(ctx, req, opts...) +} + +// RejoinUserEventsOperation returns a new RejoinUserEventsOperation from a given name. +// The name must be that of a previously created RejoinUserEventsOperation, possibly from a different process. +func (c *UserEventClient) RejoinUserEventsOperation(name string) *RejoinUserEventsOperation { + return c.internalClient.RejoinUserEventsOperation(name) +} + +// userEventGRPCClient is a client for interacting with Retail API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type userEventGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing UserEventClient + CallOptions **UserEventCallOptions + // The gRPC API client. userEventClient retailpb.UserEventServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *UserEventCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewUserEventClient creates a new user event service client. +// NewUserEventClient creates a new user event service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service for ingesting end user actions on the customer website. func NewUserEventClient(ctx context.Context, opts ...option.ClientOption) (*UserEventClient, error) { - clientOpts := defaultUserEventClientOptions() - + clientOpts := defaultUserEventGRPCClientOptions() if newUserEventClientHook != nil { hookOpts, err := newUserEventClientHook(ctx, clientHookParams{}) if err != nil { @@ -173,16 +289,19 @@ func NewUserEventClient(ctx context.Context, opts ...option.ClientOption) (*User if err != nil { return nil, err } - c := &UserEventClient{ + client := UserEventClient{CallOptions: defaultUserEventCallOptions()} + + c := &userEventGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultUserEventCallOptions(), - - userEventClient: retailpb.NewUserEventServiceClient(connPool), + userEventClient: retailpb.NewUserEventServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -192,33 +311,33 @@ func NewUserEventClient(ctx context.Context, opts ...option.ClientOption) (*User // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *UserEventClient) Connection() *grpc.ClientConn { +func (c *userEventGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *UserEventClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *UserEventClient) setGoogleClientInfo(keyval ...string) { +func (c *userEventGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// WriteUserEvent writes a single user event. -func (c *UserEventClient) WriteUserEvent(ctx context.Context, req *retailpb.WriteUserEventRequest, opts ...gax.CallOption) (*retailpb.UserEvent, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *userEventGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *userEventGRPCClient) WriteUserEvent(ctx context.Context, req *retailpb.WriteUserEventRequest, opts ...gax.CallOption) (*retailpb.UserEvent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -226,7 +345,7 @@ func (c *UserEventClient) WriteUserEvent(ctx context.Context, req *retailpb.Writ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.WriteUserEvent[0:len(c.CallOptions.WriteUserEvent):len(c.CallOptions.WriteUserEvent)], opts...) + opts = append((*c.CallOptions).WriteUserEvent[0:len((*c.CallOptions).WriteUserEvent):len((*c.CallOptions).WriteUserEvent)], opts...) var resp *retailpb.UserEvent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -239,12 +358,7 @@ func (c *UserEventClient) WriteUserEvent(ctx context.Context, req *retailpb.Writ return resp, nil } -// CollectUserEvent writes a single user event from the browser. This uses a GET request to -// due to browser restriction of POST-ing to a 3rd party domain. -// -// This method is used only by the Retail API JavaScript pixel and Google Tag -// Manager. Users should not call this method directly. -func (c *UserEventClient) CollectUserEvent(ctx context.Context, req *retailpb.CollectUserEventRequest, opts ...gax.CallOption) (*httpbodypb.HttpBody, error) { +func (c *userEventGRPCClient) CollectUserEvent(ctx context.Context, req *retailpb.CollectUserEventRequest, opts ...gax.CallOption) (*httpbodypb.HttpBody, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -252,7 +366,7 @@ func (c *UserEventClient) CollectUserEvent(ctx context.Context, req *retailpb.Co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CollectUserEvent[0:len(c.CallOptions.CollectUserEvent):len(c.CallOptions.CollectUserEvent)], opts...) + opts = append((*c.CallOptions).CollectUserEvent[0:len((*c.CallOptions).CollectUserEvent):len((*c.CallOptions).CollectUserEvent)], opts...) var resp *httpbodypb.HttpBody err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -265,11 +379,7 @@ func (c *UserEventClient) CollectUserEvent(ctx context.Context, req *retailpb.Co return resp, nil } -// PurgeUserEvents deletes permanently all user events specified by the filter provided. -// Depending on the number of events specified by the filter, this operation -// could take hours or days to complete. To test a filter, use the list -// command first. -func (c *UserEventClient) PurgeUserEvents(ctx context.Context, req *retailpb.PurgeUserEventsRequest, opts ...gax.CallOption) (*PurgeUserEventsOperation, error) { +func (c *userEventGRPCClient) PurgeUserEvents(ctx context.Context, req *retailpb.PurgeUserEventsRequest, opts ...gax.CallOption) (*PurgeUserEventsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -277,7 +387,7 @@ func (c *UserEventClient) PurgeUserEvents(ctx context.Context, req *retailpb.Pur } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PurgeUserEvents[0:len(c.CallOptions.PurgeUserEvents):len(c.CallOptions.PurgeUserEvents)], opts...) + opts = append((*c.CallOptions).PurgeUserEvents[0:len((*c.CallOptions).PurgeUserEvents):len((*c.CallOptions).PurgeUserEvents)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -288,18 +398,11 @@ func (c *UserEventClient) PurgeUserEvents(ctx context.Context, req *retailpb.Pur return nil, err } return &PurgeUserEventsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ImportUserEvents bulk import of User events. Request processing might be -// synchronous. Events that already exist are skipped. -// Use this method for backfilling historical user events. -// -// Operation.response is of type ImportResponse. Note that it is -// possible for a subset of the items to be successfully inserted. -// Operation.metadata is of type ImportMetadata. -func (c *UserEventClient) ImportUserEvents(ctx context.Context, req *retailpb.ImportUserEventsRequest, opts ...gax.CallOption) (*ImportUserEventsOperation, error) { +func (c *userEventGRPCClient) ImportUserEvents(ctx context.Context, req *retailpb.ImportUserEventsRequest, opts ...gax.CallOption) (*ImportUserEventsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -307,7 +410,7 @@ func (c *UserEventClient) ImportUserEvents(ctx context.Context, req *retailpb.Im } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportUserEvents[0:len(c.CallOptions.ImportUserEvents):len(c.CallOptions.ImportUserEvents)], opts...) + opts = append((*c.CallOptions).ImportUserEvents[0:len((*c.CallOptions).ImportUserEvents):len((*c.CallOptions).ImportUserEvents)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -318,18 +421,11 @@ func (c *UserEventClient) ImportUserEvents(ctx context.Context, req *retailpb.Im return nil, err } return &ImportUserEventsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// RejoinUserEvents triggers a user event rejoin operation with latest product catalog. Events -// will not be annotated with detailed product information if product is -// missing from the catalog at the time the user event is ingested, and these -// events are stored as unjoined events with a limited usage on training and -// serving. This API can be used to trigger a ‘join’ operation on specified -// events with latest version of product catalog. It can also be used to -// correct events joined with wrong product catalog. -func (c *UserEventClient) RejoinUserEvents(ctx context.Context, req *retailpb.RejoinUserEventsRequest, opts ...gax.CallOption) (*RejoinUserEventsOperation, error) { +func (c *userEventGRPCClient) RejoinUserEvents(ctx context.Context, req *retailpb.RejoinUserEventsRequest, opts ...gax.CallOption) (*RejoinUserEventsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -337,7 +433,7 @@ func (c *UserEventClient) RejoinUserEvents(ctx context.Context, req *retailpb.Re } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RejoinUserEvents[0:len(c.CallOptions.RejoinUserEvents):len(c.CallOptions.RejoinUserEvents)], opts...) + opts = append((*c.CallOptions).RejoinUserEvents[0:len((*c.CallOptions).RejoinUserEvents):len((*c.CallOptions).RejoinUserEvents)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -348,7 +444,7 @@ func (c *UserEventClient) RejoinUserEvents(ctx context.Context, req *retailpb.Re return nil, err } return &RejoinUserEventsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -359,9 +455,9 @@ type ImportUserEventsOperation struct { // ImportUserEventsOperation returns a new ImportUserEventsOperation from a given name. // The name must be that of a previously created ImportUserEventsOperation, possibly from a different process. -func (c *UserEventClient) ImportUserEventsOperation(name string) *ImportUserEventsOperation { +func (c *userEventGRPCClient) ImportUserEventsOperation(name string) *ImportUserEventsOperation { return &ImportUserEventsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -428,9 +524,9 @@ type PurgeUserEventsOperation struct { // PurgeUserEventsOperation returns a new PurgeUserEventsOperation from a given name. // The name must be that of a previously created PurgeUserEventsOperation, possibly from a different process. -func (c *UserEventClient) PurgeUserEventsOperation(name string) *PurgeUserEventsOperation { +func (c *userEventGRPCClient) PurgeUserEventsOperation(name string) *PurgeUserEventsOperation { return &PurgeUserEventsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -497,9 +593,9 @@ type RejoinUserEventsOperation struct { // RejoinUserEventsOperation returns a new RejoinUserEventsOperation from a given name. // The name must be that of a previously created RejoinUserEventsOperation, possibly from a different process. -func (c *UserEventClient) RejoinUserEventsOperation(name string) *RejoinUserEventsOperation { +func (c *userEventGRPCClient) RejoinUserEventsOperation(name string) *RejoinUserEventsOperation { return &RejoinUserEventsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/retail/apiv2/user_event_client_example_test.go b/retail/apiv2/user_event_client_example_test.go index aaa9ac4dee6e..75b338fc2f3d 100644 --- a/retail/apiv2/user_event_client_example_test.go +++ b/retail/apiv2/user_event_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewUserEventClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleUserEventClient_WriteUserEvent() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.WriteUserEventRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleUserEventClient_WriteUserEvent() { } func ExampleUserEventClient_CollectUserEvent() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.CollectUserEventRequest{ // TODO: Fill request struct fields. @@ -74,13 +74,12 @@ func ExampleUserEventClient_CollectUserEvent() { } func ExampleUserEventClient_PurgeUserEvents() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.PurgeUserEventsRequest{ // TODO: Fill request struct fields. @@ -99,13 +98,12 @@ func ExampleUserEventClient_PurgeUserEvents() { } func ExampleUserEventClient_ImportUserEvents() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.ImportUserEventsRequest{ // TODO: Fill request struct fields. @@ -124,13 +122,12 @@ func ExampleUserEventClient_ImportUserEvents() { } func ExampleUserEventClient_RejoinUserEvents() { - // import retailpb "google.golang.org/genproto/googleapis/cloud/retail/v2" - ctx := context.Background() c, err := retail.NewUserEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &retailpb.RejoinUserEventsRequest{ // TODO: Fill request struct fields. diff --git a/scheduler/apiv1/cloud_scheduler_client.go b/scheduler/apiv1/cloud_scheduler_client.go index 8a55311f2c17..52d39603b569 100644 --- a/scheduler/apiv1/cloud_scheduler_client.go +++ b/scheduler/apiv1/cloud_scheduler_client.go @@ -49,7 +49,7 @@ type CloudSchedulerCallOptions struct { RunJob []gax.CallOption } -func defaultCloudSchedulerClientOptions() []option.ClientOption { +func defaultCloudSchedulerGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudscheduler.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudscheduler.mtls.googleapis.com:443"), @@ -107,33 +107,145 @@ func defaultCloudSchedulerCallOptions() *CloudSchedulerCallOptions { } } +// internalCloudSchedulerClient is an interface that defines the methods availaible from Cloud Scheduler API. +type internalCloudSchedulerClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListJobs(context.Context, *schedulerpb.ListJobsRequest, ...gax.CallOption) *JobIterator + GetJob(context.Context, *schedulerpb.GetJobRequest, ...gax.CallOption) (*schedulerpb.Job, error) + CreateJob(context.Context, *schedulerpb.CreateJobRequest, ...gax.CallOption) (*schedulerpb.Job, error) + UpdateJob(context.Context, *schedulerpb.UpdateJobRequest, ...gax.CallOption) (*schedulerpb.Job, error) + DeleteJob(context.Context, *schedulerpb.DeleteJobRequest, ...gax.CallOption) error + PauseJob(context.Context, *schedulerpb.PauseJobRequest, ...gax.CallOption) (*schedulerpb.Job, error) + ResumeJob(context.Context, *schedulerpb.ResumeJobRequest, ...gax.CallOption) (*schedulerpb.Job, error) + RunJob(context.Context, *schedulerpb.RunJobRequest, ...gax.CallOption) (*schedulerpb.Job, error) +} + // CloudSchedulerClient is a client for interacting with Cloud Scheduler API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The Cloud Scheduler API allows external entities to reliably +// schedule asynchronous jobs. type CloudSchedulerClient struct { + // The internal transport-dependent client. + internalClient internalCloudSchedulerClient + + // The call options for this service. + CallOptions *CloudSchedulerCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CloudSchedulerClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CloudSchedulerClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CloudSchedulerClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListJobs lists jobs. +func (c *CloudSchedulerClient) ListJobs(ctx context.Context, req *schedulerpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { + return c.internalClient.ListJobs(ctx, req, opts...) +} + +// GetJob gets a job. +func (c *CloudSchedulerClient) GetJob(ctx context.Context, req *schedulerpb.GetJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + return c.internalClient.GetJob(ctx, req, opts...) +} + +// CreateJob creates a job. +func (c *CloudSchedulerClient) CreateJob(ctx context.Context, req *schedulerpb.CreateJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + return c.internalClient.CreateJob(ctx, req, opts...) +} + +// UpdateJob updates a job. +// +// If successful, the updated Job is returned. If the job does +// not exist, NOT_FOUND is returned. +// +// If UpdateJob does not successfully return, it is possible for the +// job to be in an Job.State.UPDATE_FAILED state. A job in this state may +// not be executed. If this happens, retry the UpdateJob request +// until a successful response is received. +func (c *CloudSchedulerClient) UpdateJob(ctx context.Context, req *schedulerpb.UpdateJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + return c.internalClient.UpdateJob(ctx, req, opts...) +} + +// DeleteJob deletes a job. +func (c *CloudSchedulerClient) DeleteJob(ctx context.Context, req *schedulerpb.DeleteJobRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteJob(ctx, req, opts...) +} + +// PauseJob pauses a job. +// +// If a job is paused then the system will stop executing the job +// until it is re-enabled via ResumeJob. The +// state of the job is stored in state; if paused it +// will be set to Job.State.PAUSED. A job must be in Job.State.ENABLED +// to be paused. +func (c *CloudSchedulerClient) PauseJob(ctx context.Context, req *schedulerpb.PauseJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + return c.internalClient.PauseJob(ctx, req, opts...) +} + +// ResumeJob resume a job. +// +// This method reenables a job after it has been Job.State.PAUSED. The +// state of a job is stored in Job.state; after calling this method it +// will be set to Job.State.ENABLED. A job must be in +// Job.State.PAUSED to be resumed. +func (c *CloudSchedulerClient) ResumeJob(ctx context.Context, req *schedulerpb.ResumeJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + return c.internalClient.ResumeJob(ctx, req, opts...) +} + +// RunJob forces a job to run now. +// +// When this method is called, Cloud Scheduler will dispatch the job, even +// if the job is already running. +func (c *CloudSchedulerClient) RunJob(ctx context.Context, req *schedulerpb.RunJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + return c.internalClient.RunJob(ctx, req, opts...) +} + +// cloudSchedulerGRPCClient is a client for interacting with Cloud Scheduler API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudSchedulerGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CloudSchedulerClient + CallOptions **CloudSchedulerCallOptions + // The gRPC API client. cloudSchedulerClient schedulerpb.CloudSchedulerClient - // The call options for this service. - CallOptions *CloudSchedulerCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCloudSchedulerClient creates a new cloud scheduler client. +// NewCloudSchedulerClient creates a new cloud scheduler client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The Cloud Scheduler API allows external entities to reliably // schedule asynchronous jobs. func NewCloudSchedulerClient(ctx context.Context, opts ...option.ClientOption) (*CloudSchedulerClient, error) { - clientOpts := defaultCloudSchedulerClientOptions() - + clientOpts := defaultCloudSchedulerGRPCClientOptions() if newCloudSchedulerClientHook != nil { hookOpts, err := newCloudSchedulerClientHook(ctx, clientHookParams{}) if err != nil { @@ -151,45 +263,47 @@ func NewCloudSchedulerClient(ctx context.Context, opts ...option.ClientOption) ( if err != nil { return nil, err } - c := &CloudSchedulerClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultCloudSchedulerCallOptions(), + client := CloudSchedulerClient{CallOptions: defaultCloudSchedulerCallOptions()} + c := &cloudSchedulerGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, cloudSchedulerClient: schedulerpb.NewCloudSchedulerClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CloudSchedulerClient) Connection() *grpc.ClientConn { +func (c *cloudSchedulerGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CloudSchedulerClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CloudSchedulerClient) setGoogleClientInfo(keyval ...string) { +func (c *cloudSchedulerGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListJobs lists jobs. -func (c *CloudSchedulerClient) ListJobs(ctx context.Context, req *schedulerpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudSchedulerGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *cloudSchedulerGRPCClient) ListJobs(ctx context.Context, req *schedulerpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListJobs[0:len(c.CallOptions.ListJobs):len(c.CallOptions.ListJobs)], opts...) + opts = append((*c.CallOptions).ListJobs[0:len((*c.CallOptions).ListJobs):len((*c.CallOptions).ListJobs)], opts...) it := &JobIterator{} req = proto.Clone(req).(*schedulerpb.ListJobsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*schedulerpb.Job, string, error) { @@ -226,8 +340,7 @@ func (c *CloudSchedulerClient) ListJobs(ctx context.Context, req *schedulerpb.Li return it } -// GetJob gets a job. -func (c *CloudSchedulerClient) GetJob(ctx context.Context, req *schedulerpb.GetJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { +func (c *cloudSchedulerGRPCClient) GetJob(ctx context.Context, req *schedulerpb.GetJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -235,7 +348,7 @@ func (c *CloudSchedulerClient) GetJob(ctx context.Context, req *schedulerpb.GetJ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetJob[0:len(c.CallOptions.GetJob):len(c.CallOptions.GetJob)], opts...) + opts = append((*c.CallOptions).GetJob[0:len((*c.CallOptions).GetJob):len((*c.CallOptions).GetJob)], opts...) var resp *schedulerpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -248,8 +361,7 @@ func (c *CloudSchedulerClient) GetJob(ctx context.Context, req *schedulerpb.GetJ return resp, nil } -// CreateJob creates a job. -func (c *CloudSchedulerClient) CreateJob(ctx context.Context, req *schedulerpb.CreateJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { +func (c *cloudSchedulerGRPCClient) CreateJob(ctx context.Context, req *schedulerpb.CreateJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -257,7 +369,7 @@ func (c *CloudSchedulerClient) CreateJob(ctx context.Context, req *schedulerpb.C } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateJob[0:len(c.CallOptions.CreateJob):len(c.CallOptions.CreateJob)], opts...) + opts = append((*c.CallOptions).CreateJob[0:len((*c.CallOptions).CreateJob):len((*c.CallOptions).CreateJob)], opts...) var resp *schedulerpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -270,16 +382,7 @@ func (c *CloudSchedulerClient) CreateJob(ctx context.Context, req *schedulerpb.C return resp, nil } -// UpdateJob updates a job. -// -// If successful, the updated Job is returned. If the job does -// not exist, NOT_FOUND is returned. -// -// If UpdateJob does not successfully return, it is possible for the -// job to be in an Job.State.UPDATE_FAILED state. A job in this state may -// not be executed. If this happens, retry the UpdateJob request -// until a successful response is received. -func (c *CloudSchedulerClient) UpdateJob(ctx context.Context, req *schedulerpb.UpdateJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { +func (c *cloudSchedulerGRPCClient) UpdateJob(ctx context.Context, req *schedulerpb.UpdateJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -287,7 +390,7 @@ func (c *CloudSchedulerClient) UpdateJob(ctx context.Context, req *schedulerpb.U } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "job.name", url.QueryEscape(req.GetJob().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateJob[0:len(c.CallOptions.UpdateJob):len(c.CallOptions.UpdateJob)], opts...) + opts = append((*c.CallOptions).UpdateJob[0:len((*c.CallOptions).UpdateJob):len((*c.CallOptions).UpdateJob)], opts...) var resp *schedulerpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -300,8 +403,7 @@ func (c *CloudSchedulerClient) UpdateJob(ctx context.Context, req *schedulerpb.U return resp, nil } -// DeleteJob deletes a job. -func (c *CloudSchedulerClient) DeleteJob(ctx context.Context, req *schedulerpb.DeleteJobRequest, opts ...gax.CallOption) error { +func (c *cloudSchedulerGRPCClient) DeleteJob(ctx context.Context, req *schedulerpb.DeleteJobRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -309,7 +411,7 @@ func (c *CloudSchedulerClient) DeleteJob(ctx context.Context, req *schedulerpb.D } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteJob[0:len(c.CallOptions.DeleteJob):len(c.CallOptions.DeleteJob)], opts...) + opts = append((*c.CallOptions).DeleteJob[0:len((*c.CallOptions).DeleteJob):len((*c.CallOptions).DeleteJob)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.cloudSchedulerClient.DeleteJob(ctx, req, settings.GRPC...) @@ -318,14 +420,7 @@ func (c *CloudSchedulerClient) DeleteJob(ctx context.Context, req *schedulerpb.D return err } -// PauseJob pauses a job. -// -// If a job is paused then the system will stop executing the job -// until it is re-enabled via ResumeJob. The -// state of the job is stored in state; if paused it -// will be set to Job.State.PAUSED. A job must be in Job.State.ENABLED -// to be paused. -func (c *CloudSchedulerClient) PauseJob(ctx context.Context, req *schedulerpb.PauseJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { +func (c *cloudSchedulerGRPCClient) PauseJob(ctx context.Context, req *schedulerpb.PauseJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -333,7 +428,7 @@ func (c *CloudSchedulerClient) PauseJob(ctx context.Context, req *schedulerpb.Pa } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PauseJob[0:len(c.CallOptions.PauseJob):len(c.CallOptions.PauseJob)], opts...) + opts = append((*c.CallOptions).PauseJob[0:len((*c.CallOptions).PauseJob):len((*c.CallOptions).PauseJob)], opts...) var resp *schedulerpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -346,13 +441,7 @@ func (c *CloudSchedulerClient) PauseJob(ctx context.Context, req *schedulerpb.Pa return resp, nil } -// ResumeJob resume a job. -// -// This method reenables a job after it has been Job.State.PAUSED. The -// state of a job is stored in Job.state; after calling this method it -// will be set to Job.State.ENABLED. A job must be in -// Job.State.PAUSED to be resumed. -func (c *CloudSchedulerClient) ResumeJob(ctx context.Context, req *schedulerpb.ResumeJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { +func (c *cloudSchedulerGRPCClient) ResumeJob(ctx context.Context, req *schedulerpb.ResumeJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -360,7 +449,7 @@ func (c *CloudSchedulerClient) ResumeJob(ctx context.Context, req *schedulerpb.R } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ResumeJob[0:len(c.CallOptions.ResumeJob):len(c.CallOptions.ResumeJob)], opts...) + opts = append((*c.CallOptions).ResumeJob[0:len((*c.CallOptions).ResumeJob):len((*c.CallOptions).ResumeJob)], opts...) var resp *schedulerpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -373,11 +462,7 @@ func (c *CloudSchedulerClient) ResumeJob(ctx context.Context, req *schedulerpb.R return resp, nil } -// RunJob forces a job to run now. -// -// When this method is called, Cloud Scheduler will dispatch the job, even -// if the job is already running. -func (c *CloudSchedulerClient) RunJob(ctx context.Context, req *schedulerpb.RunJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { +func (c *cloudSchedulerGRPCClient) RunJob(ctx context.Context, req *schedulerpb.RunJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -385,7 +470,7 @@ func (c *CloudSchedulerClient) RunJob(ctx context.Context, req *schedulerpb.RunJ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RunJob[0:len(c.CallOptions.RunJob):len(c.CallOptions.RunJob)], opts...) + opts = append((*c.CallOptions).RunJob[0:len((*c.CallOptions).RunJob):len((*c.CallOptions).RunJob)], opts...) var resp *schedulerpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/scheduler/apiv1/cloud_scheduler_client_example_test.go b/scheduler/apiv1/cloud_scheduler_client_example_test.go index 6af58dfd12e3..202fc07f5104 100644 --- a/scheduler/apiv1/cloud_scheduler_client_example_test.go +++ b/scheduler/apiv1/cloud_scheduler_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewCloudSchedulerClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCloudSchedulerClient_ListJobs() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.ListJobsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleCloudSchedulerClient_ListJobs() { } func ExampleCloudSchedulerClient_GetJob() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.GetJobRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleCloudSchedulerClient_GetJob() { } func ExampleCloudSchedulerClient_CreateJob() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.CreateJobRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleCloudSchedulerClient_CreateJob() { } func ExampleCloudSchedulerClient_UpdateJob() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.UpdateJobRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleCloudSchedulerClient_DeleteJob() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.DeleteJobRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleCloudSchedulerClient_DeleteJob() { } func ExampleCloudSchedulerClient_PauseJob() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.PauseJobRequest{ // TODO: Fill request struct fields. @@ -158,13 +155,12 @@ func ExampleCloudSchedulerClient_PauseJob() { } func ExampleCloudSchedulerClient_ResumeJob() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.ResumeJobRequest{ // TODO: Fill request struct fields. @@ -178,13 +174,12 @@ func ExampleCloudSchedulerClient_ResumeJob() { } func ExampleCloudSchedulerClient_RunJob() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.RunJobRequest{ // TODO: Fill request struct fields. diff --git a/scheduler/apiv1/doc.go b/scheduler/apiv1/doc.go index 9efb96515d68..d3a2c2685d29 100644 --- a/scheduler/apiv1/doc.go +++ b/scheduler/apiv1/doc.go @@ -28,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package scheduler // import "cloud.google.com/go/scheduler/apiv1" import ( @@ -48,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/scheduler/apiv1beta1/cloud_scheduler_client.go b/scheduler/apiv1beta1/cloud_scheduler_client.go index c09dddabc3dd..2dcabaefb214 100644 --- a/scheduler/apiv1beta1/cloud_scheduler_client.go +++ b/scheduler/apiv1beta1/cloud_scheduler_client.go @@ -49,7 +49,7 @@ type CloudSchedulerCallOptions struct { RunJob []gax.CallOption } -func defaultCloudSchedulerClientOptions() []option.ClientOption { +func defaultCloudSchedulerGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudscheduler.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudscheduler.mtls.googleapis.com:443"), @@ -129,33 +129,145 @@ func defaultCloudSchedulerCallOptions() *CloudSchedulerCallOptions { } } +// internalCloudSchedulerClient is an interface that defines the methods availaible from Cloud Scheduler API. +type internalCloudSchedulerClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListJobs(context.Context, *schedulerpb.ListJobsRequest, ...gax.CallOption) *JobIterator + GetJob(context.Context, *schedulerpb.GetJobRequest, ...gax.CallOption) (*schedulerpb.Job, error) + CreateJob(context.Context, *schedulerpb.CreateJobRequest, ...gax.CallOption) (*schedulerpb.Job, error) + UpdateJob(context.Context, *schedulerpb.UpdateJobRequest, ...gax.CallOption) (*schedulerpb.Job, error) + DeleteJob(context.Context, *schedulerpb.DeleteJobRequest, ...gax.CallOption) error + PauseJob(context.Context, *schedulerpb.PauseJobRequest, ...gax.CallOption) (*schedulerpb.Job, error) + ResumeJob(context.Context, *schedulerpb.ResumeJobRequest, ...gax.CallOption) (*schedulerpb.Job, error) + RunJob(context.Context, *schedulerpb.RunJobRequest, ...gax.CallOption) (*schedulerpb.Job, error) +} + // CloudSchedulerClient is a client for interacting with Cloud Scheduler API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// The Cloud Scheduler API allows external entities to reliably +// schedule asynchronous jobs. type CloudSchedulerClient struct { + // The internal transport-dependent client. + internalClient internalCloudSchedulerClient + + // The call options for this service. + CallOptions *CloudSchedulerCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CloudSchedulerClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CloudSchedulerClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CloudSchedulerClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListJobs lists jobs. +func (c *CloudSchedulerClient) ListJobs(ctx context.Context, req *schedulerpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { + return c.internalClient.ListJobs(ctx, req, opts...) +} + +// GetJob gets a job. +func (c *CloudSchedulerClient) GetJob(ctx context.Context, req *schedulerpb.GetJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + return c.internalClient.GetJob(ctx, req, opts...) +} + +// CreateJob creates a job. +func (c *CloudSchedulerClient) CreateJob(ctx context.Context, req *schedulerpb.CreateJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + return c.internalClient.CreateJob(ctx, req, opts...) +} + +// UpdateJob updates a job. +// +// If successful, the updated Job is returned. If the job does +// not exist, NOT_FOUND is returned. +// +// If UpdateJob does not successfully return, it is possible for the +// job to be in an Job.State.UPDATE_FAILED state. A job in this state may +// not be executed. If this happens, retry the UpdateJob request +// until a successful response is received. +func (c *CloudSchedulerClient) UpdateJob(ctx context.Context, req *schedulerpb.UpdateJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + return c.internalClient.UpdateJob(ctx, req, opts...) +} + +// DeleteJob deletes a job. +func (c *CloudSchedulerClient) DeleteJob(ctx context.Context, req *schedulerpb.DeleteJobRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteJob(ctx, req, opts...) +} + +// PauseJob pauses a job. +// +// If a job is paused then the system will stop executing the job +// until it is re-enabled via ResumeJob. The +// state of the job is stored in state; if paused it +// will be set to Job.State.PAUSED. A job must be in Job.State.ENABLED +// to be paused. +func (c *CloudSchedulerClient) PauseJob(ctx context.Context, req *schedulerpb.PauseJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + return c.internalClient.PauseJob(ctx, req, opts...) +} + +// ResumeJob resume a job. +// +// This method reenables a job after it has been Job.State.PAUSED. The +// state of a job is stored in Job.state; after calling this method it +// will be set to Job.State.ENABLED. A job must be in +// Job.State.PAUSED to be resumed. +func (c *CloudSchedulerClient) ResumeJob(ctx context.Context, req *schedulerpb.ResumeJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + return c.internalClient.ResumeJob(ctx, req, opts...) +} + +// RunJob forces a job to run now. +// +// When this method is called, Cloud Scheduler will dispatch the job, even +// if the job is already running. +func (c *CloudSchedulerClient) RunJob(ctx context.Context, req *schedulerpb.RunJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { + return c.internalClient.RunJob(ctx, req, opts...) +} + +// cloudSchedulerGRPCClient is a client for interacting with Cloud Scheduler API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type cloudSchedulerGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CloudSchedulerClient + CallOptions **CloudSchedulerCallOptions + // The gRPC API client. cloudSchedulerClient schedulerpb.CloudSchedulerClient - // The call options for this service. - CallOptions *CloudSchedulerCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCloudSchedulerClient creates a new cloud scheduler client. +// NewCloudSchedulerClient creates a new cloud scheduler client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // The Cloud Scheduler API allows external entities to reliably // schedule asynchronous jobs. func NewCloudSchedulerClient(ctx context.Context, opts ...option.ClientOption) (*CloudSchedulerClient, error) { - clientOpts := defaultCloudSchedulerClientOptions() - + clientOpts := defaultCloudSchedulerGRPCClientOptions() if newCloudSchedulerClientHook != nil { hookOpts, err := newCloudSchedulerClientHook(ctx, clientHookParams{}) if err != nil { @@ -173,45 +285,47 @@ func NewCloudSchedulerClient(ctx context.Context, opts ...option.ClientOption) ( if err != nil { return nil, err } - c := &CloudSchedulerClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultCloudSchedulerCallOptions(), + client := CloudSchedulerClient{CallOptions: defaultCloudSchedulerCallOptions()} + c := &cloudSchedulerGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, cloudSchedulerClient: schedulerpb.NewCloudSchedulerClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CloudSchedulerClient) Connection() *grpc.ClientConn { +func (c *cloudSchedulerGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CloudSchedulerClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CloudSchedulerClient) setGoogleClientInfo(keyval ...string) { +func (c *cloudSchedulerGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListJobs lists jobs. -func (c *CloudSchedulerClient) ListJobs(ctx context.Context, req *schedulerpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *cloudSchedulerGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *cloudSchedulerGRPCClient) ListJobs(ctx context.Context, req *schedulerpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListJobs[0:len(c.CallOptions.ListJobs):len(c.CallOptions.ListJobs)], opts...) + opts = append((*c.CallOptions).ListJobs[0:len((*c.CallOptions).ListJobs):len((*c.CallOptions).ListJobs)], opts...) it := &JobIterator{} req = proto.Clone(req).(*schedulerpb.ListJobsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*schedulerpb.Job, string, error) { @@ -248,8 +362,7 @@ func (c *CloudSchedulerClient) ListJobs(ctx context.Context, req *schedulerpb.Li return it } -// GetJob gets a job. -func (c *CloudSchedulerClient) GetJob(ctx context.Context, req *schedulerpb.GetJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { +func (c *cloudSchedulerGRPCClient) GetJob(ctx context.Context, req *schedulerpb.GetJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -257,7 +370,7 @@ func (c *CloudSchedulerClient) GetJob(ctx context.Context, req *schedulerpb.GetJ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetJob[0:len(c.CallOptions.GetJob):len(c.CallOptions.GetJob)], opts...) + opts = append((*c.CallOptions).GetJob[0:len((*c.CallOptions).GetJob):len((*c.CallOptions).GetJob)], opts...) var resp *schedulerpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -270,8 +383,7 @@ func (c *CloudSchedulerClient) GetJob(ctx context.Context, req *schedulerpb.GetJ return resp, nil } -// CreateJob creates a job. -func (c *CloudSchedulerClient) CreateJob(ctx context.Context, req *schedulerpb.CreateJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { +func (c *cloudSchedulerGRPCClient) CreateJob(ctx context.Context, req *schedulerpb.CreateJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -279,7 +391,7 @@ func (c *CloudSchedulerClient) CreateJob(ctx context.Context, req *schedulerpb.C } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateJob[0:len(c.CallOptions.CreateJob):len(c.CallOptions.CreateJob)], opts...) + opts = append((*c.CallOptions).CreateJob[0:len((*c.CallOptions).CreateJob):len((*c.CallOptions).CreateJob)], opts...) var resp *schedulerpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -292,16 +404,7 @@ func (c *CloudSchedulerClient) CreateJob(ctx context.Context, req *schedulerpb.C return resp, nil } -// UpdateJob updates a job. -// -// If successful, the updated Job is returned. If the job does -// not exist, NOT_FOUND is returned. -// -// If UpdateJob does not successfully return, it is possible for the -// job to be in an Job.State.UPDATE_FAILED state. A job in this state may -// not be executed. If this happens, retry the UpdateJob request -// until a successful response is received. -func (c *CloudSchedulerClient) UpdateJob(ctx context.Context, req *schedulerpb.UpdateJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { +func (c *cloudSchedulerGRPCClient) UpdateJob(ctx context.Context, req *schedulerpb.UpdateJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -309,7 +412,7 @@ func (c *CloudSchedulerClient) UpdateJob(ctx context.Context, req *schedulerpb.U } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "job.name", url.QueryEscape(req.GetJob().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateJob[0:len(c.CallOptions.UpdateJob):len(c.CallOptions.UpdateJob)], opts...) + opts = append((*c.CallOptions).UpdateJob[0:len((*c.CallOptions).UpdateJob):len((*c.CallOptions).UpdateJob)], opts...) var resp *schedulerpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -322,8 +425,7 @@ func (c *CloudSchedulerClient) UpdateJob(ctx context.Context, req *schedulerpb.U return resp, nil } -// DeleteJob deletes a job. -func (c *CloudSchedulerClient) DeleteJob(ctx context.Context, req *schedulerpb.DeleteJobRequest, opts ...gax.CallOption) error { +func (c *cloudSchedulerGRPCClient) DeleteJob(ctx context.Context, req *schedulerpb.DeleteJobRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -331,7 +433,7 @@ func (c *CloudSchedulerClient) DeleteJob(ctx context.Context, req *schedulerpb.D } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteJob[0:len(c.CallOptions.DeleteJob):len(c.CallOptions.DeleteJob)], opts...) + opts = append((*c.CallOptions).DeleteJob[0:len((*c.CallOptions).DeleteJob):len((*c.CallOptions).DeleteJob)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.cloudSchedulerClient.DeleteJob(ctx, req, settings.GRPC...) @@ -340,14 +442,7 @@ func (c *CloudSchedulerClient) DeleteJob(ctx context.Context, req *schedulerpb.D return err } -// PauseJob pauses a job. -// -// If a job is paused then the system will stop executing the job -// until it is re-enabled via ResumeJob. The -// state of the job is stored in state; if paused it -// will be set to Job.State.PAUSED. A job must be in Job.State.ENABLED -// to be paused. -func (c *CloudSchedulerClient) PauseJob(ctx context.Context, req *schedulerpb.PauseJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { +func (c *cloudSchedulerGRPCClient) PauseJob(ctx context.Context, req *schedulerpb.PauseJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -355,7 +450,7 @@ func (c *CloudSchedulerClient) PauseJob(ctx context.Context, req *schedulerpb.Pa } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PauseJob[0:len(c.CallOptions.PauseJob):len(c.CallOptions.PauseJob)], opts...) + opts = append((*c.CallOptions).PauseJob[0:len((*c.CallOptions).PauseJob):len((*c.CallOptions).PauseJob)], opts...) var resp *schedulerpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -368,13 +463,7 @@ func (c *CloudSchedulerClient) PauseJob(ctx context.Context, req *schedulerpb.Pa return resp, nil } -// ResumeJob resume a job. -// -// This method reenables a job after it has been Job.State.PAUSED. The -// state of a job is stored in Job.state; after calling this method it -// will be set to Job.State.ENABLED. A job must be in -// Job.State.PAUSED to be resumed. -func (c *CloudSchedulerClient) ResumeJob(ctx context.Context, req *schedulerpb.ResumeJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { +func (c *cloudSchedulerGRPCClient) ResumeJob(ctx context.Context, req *schedulerpb.ResumeJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -382,7 +471,7 @@ func (c *CloudSchedulerClient) ResumeJob(ctx context.Context, req *schedulerpb.R } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ResumeJob[0:len(c.CallOptions.ResumeJob):len(c.CallOptions.ResumeJob)], opts...) + opts = append((*c.CallOptions).ResumeJob[0:len((*c.CallOptions).ResumeJob):len((*c.CallOptions).ResumeJob)], opts...) var resp *schedulerpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -395,11 +484,7 @@ func (c *CloudSchedulerClient) ResumeJob(ctx context.Context, req *schedulerpb.R return resp, nil } -// RunJob forces a job to run now. -// -// When this method is called, Cloud Scheduler will dispatch the job, even -// if the job is already running. -func (c *CloudSchedulerClient) RunJob(ctx context.Context, req *schedulerpb.RunJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { +func (c *cloudSchedulerGRPCClient) RunJob(ctx context.Context, req *schedulerpb.RunJobRequest, opts ...gax.CallOption) (*schedulerpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -407,7 +492,7 @@ func (c *CloudSchedulerClient) RunJob(ctx context.Context, req *schedulerpb.RunJ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RunJob[0:len(c.CallOptions.RunJob):len(c.CallOptions.RunJob)], opts...) + opts = append((*c.CallOptions).RunJob[0:len((*c.CallOptions).RunJob):len((*c.CallOptions).RunJob)], opts...) var resp *schedulerpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/scheduler/apiv1beta1/cloud_scheduler_client_example_test.go b/scheduler/apiv1beta1/cloud_scheduler_client_example_test.go index a162079dbe74..17caedef62ba 100644 --- a/scheduler/apiv1beta1/cloud_scheduler_client_example_test.go +++ b/scheduler/apiv1beta1/cloud_scheduler_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewCloudSchedulerClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCloudSchedulerClient_ListJobs() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.ListJobsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleCloudSchedulerClient_ListJobs() { } func ExampleCloudSchedulerClient_GetJob() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1beta1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.GetJobRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleCloudSchedulerClient_GetJob() { } func ExampleCloudSchedulerClient_CreateJob() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1beta1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.CreateJobRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleCloudSchedulerClient_CreateJob() { } func ExampleCloudSchedulerClient_UpdateJob() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1beta1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.UpdateJobRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleCloudSchedulerClient_DeleteJob() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.DeleteJobRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleCloudSchedulerClient_DeleteJob() { } func ExampleCloudSchedulerClient_PauseJob() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1beta1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.PauseJobRequest{ // TODO: Fill request struct fields. @@ -158,13 +155,12 @@ func ExampleCloudSchedulerClient_PauseJob() { } func ExampleCloudSchedulerClient_ResumeJob() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1beta1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.ResumeJobRequest{ // TODO: Fill request struct fields. @@ -178,13 +174,12 @@ func ExampleCloudSchedulerClient_ResumeJob() { } func ExampleCloudSchedulerClient_RunJob() { - // import schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1beta1" - ctx := context.Background() c, err := scheduler.NewCloudSchedulerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &schedulerpb.RunJobRequest{ // TODO: Fill request struct fields. diff --git a/scheduler/apiv1beta1/doc.go b/scheduler/apiv1beta1/doc.go index 47736a7cf800..8d69aeeda992 100644 --- a/scheduler/apiv1beta1/doc.go +++ b/scheduler/apiv1beta1/doc.go @@ -19,6 +19,8 @@ // // Creates and manages jobs run on a regular recurring schedule. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -28,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package scheduler // import "cloud.google.com/go/scheduler/apiv1beta1" import ( @@ -48,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/secretmanager/apiv1/doc.go b/secretmanager/apiv1/doc.go index 706ed54b9da3..5aa24bf24c51 100644 --- a/secretmanager/apiv1/doc.go +++ b/secretmanager/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package secretmanager // import "cloud.google.com/go/secretmanager/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/secretmanager/apiv1/iam.go b/secretmanager/apiv1/iam.go index e3d78a54cd8a..43bb32c6391d 100644 --- a/secretmanager/apiv1/iam.go +++ b/secretmanager/apiv1/iam.go @@ -22,5 +22,8 @@ import ( // indicated by the given resource path. Name should be of the format // `projects/my-project/secrets/my-secret`. func (c *Client) IAM(name string) *iam.Handle { - return iam.InternalNewHandleGRPCClient(c.client, name) + if grpcClient, ok := c.internalClient.(*gRPCClient); ok { + return iam.InternalNewHandleGRPCClient(grpcClient.client, name) + } + return iam.InternalNewHandleGRPCClient(nil, name) } diff --git a/secretmanager/apiv1/secret_manager_client.go b/secretmanager/apiv1/secret_manager_client.go index 8e53a5af5bbe..4f721cbdeac7 100644 --- a/secretmanager/apiv1/secret_manager_client.go +++ b/secretmanager/apiv1/secret_manager_client.go @@ -57,7 +57,7 @@ type CallOptions struct { TestIamPermissions []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("secretmanager.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("secretmanager.mtls.googleapis.com:443"), @@ -100,27 +100,195 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Secret Manager API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListSecrets(context.Context, *secretmanagerpb.ListSecretsRequest, ...gax.CallOption) *SecretIterator + CreateSecret(context.Context, *secretmanagerpb.CreateSecretRequest, ...gax.CallOption) (*secretmanagerpb.Secret, error) + AddSecretVersion(context.Context, *secretmanagerpb.AddSecretVersionRequest, ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) + GetSecret(context.Context, *secretmanagerpb.GetSecretRequest, ...gax.CallOption) (*secretmanagerpb.Secret, error) + UpdateSecret(context.Context, *secretmanagerpb.UpdateSecretRequest, ...gax.CallOption) (*secretmanagerpb.Secret, error) + DeleteSecret(context.Context, *secretmanagerpb.DeleteSecretRequest, ...gax.CallOption) error + ListSecretVersions(context.Context, *secretmanagerpb.ListSecretVersionsRequest, ...gax.CallOption) *SecretVersionIterator + GetSecretVersion(context.Context, *secretmanagerpb.GetSecretVersionRequest, ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) + AccessSecretVersion(context.Context, *secretmanagerpb.AccessSecretVersionRequest, ...gax.CallOption) (*secretmanagerpb.AccessSecretVersionResponse, error) + DisableSecretVersion(context.Context, *secretmanagerpb.DisableSecretVersionRequest, ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) + EnableSecretVersion(context.Context, *secretmanagerpb.EnableSecretVersionRequest, ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) + DestroySecretVersion(context.Context, *secretmanagerpb.DestroySecretVersionRequest, ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) +} + // Client is a client for interacting with Secret Manager API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Secret Manager Service +// +// Manages secrets and operations using those secrets. Implements a REST +// model with the following objects: +// +// Secret +// +// SecretVersion type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListSecrets lists Secrets. +func (c *Client) ListSecrets(ctx context.Context, req *secretmanagerpb.ListSecretsRequest, opts ...gax.CallOption) *SecretIterator { + return c.internalClient.ListSecrets(ctx, req, opts...) +} + +// CreateSecret creates a new Secret containing no SecretVersions. +func (c *Client) CreateSecret(ctx context.Context, req *secretmanagerpb.CreateSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { + return c.internalClient.CreateSecret(ctx, req, opts...) +} + +// AddSecretVersion creates a new SecretVersion containing secret data and attaches +// it to an existing Secret. +func (c *Client) AddSecretVersion(ctx context.Context, req *secretmanagerpb.AddSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { + return c.internalClient.AddSecretVersion(ctx, req, opts...) +} + +// GetSecret gets metadata for a given Secret. +func (c *Client) GetSecret(ctx context.Context, req *secretmanagerpb.GetSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { + return c.internalClient.GetSecret(ctx, req, opts...) +} + +// UpdateSecret updates metadata of an existing Secret. +func (c *Client) UpdateSecret(ctx context.Context, req *secretmanagerpb.UpdateSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { + return c.internalClient.UpdateSecret(ctx, req, opts...) +} + +// DeleteSecret deletes a Secret. +func (c *Client) DeleteSecret(ctx context.Context, req *secretmanagerpb.DeleteSecretRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteSecret(ctx, req, opts...) +} + +// ListSecretVersions lists SecretVersions. This call does not return secret +// data. +func (c *Client) ListSecretVersions(ctx context.Context, req *secretmanagerpb.ListSecretVersionsRequest, opts ...gax.CallOption) *SecretVersionIterator { + return c.internalClient.ListSecretVersions(ctx, req, opts...) +} + +// GetSecretVersion gets metadata for a SecretVersion. +// +// projects/*/secrets/*/versions/latest is an alias to the most recently +// created SecretVersion. +func (c *Client) GetSecretVersion(ctx context.Context, req *secretmanagerpb.GetSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { + return c.internalClient.GetSecretVersion(ctx, req, opts...) +} + +// AccessSecretVersion accesses a SecretVersion. This call returns the secret data. +// +// projects/*/secrets/*/versions/latest is an alias to the most recently +// created SecretVersion. +func (c *Client) AccessSecretVersion(ctx context.Context, req *secretmanagerpb.AccessSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.AccessSecretVersionResponse, error) { + return c.internalClient.AccessSecretVersion(ctx, req, opts...) +} + +// DisableSecretVersion disables a SecretVersion. +// +// Sets the state of the SecretVersion to +// DISABLED. +func (c *Client) DisableSecretVersion(ctx context.Context, req *secretmanagerpb.DisableSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { + return c.internalClient.DisableSecretVersion(ctx, req, opts...) +} + +// EnableSecretVersion enables a SecretVersion. +// +// Sets the state of the SecretVersion to +// ENABLED. +func (c *Client) EnableSecretVersion(ctx context.Context, req *secretmanagerpb.EnableSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { + return c.internalClient.EnableSecretVersion(ctx, req, opts...) +} + +// DestroySecretVersion destroys a SecretVersion. +// +// Sets the state of the SecretVersion to +// DESTROYED and irrevocably destroys the +// secret data. +func (c *Client) DestroySecretVersion(ctx context.Context, req *secretmanagerpb.DestroySecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { + return c.internalClient.DestroySecretVersion(ctx, req, opts...) +} + +// SetIamPolicy sets the access control policy on the specified secret. Replaces any +// existing policy. +// +// Permissions on SecretVersions are enforced according +// to the policy set on the associated Secret. +func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy for a secret. +// Returns empty policy if the secret exists and does not have a policy set. +func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns permissions that a caller has for the specified secret. +// If the secret does not exist, this call returns an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building permission-aware +// UIs and command-line tools, not for authorization checking. This operation +// may “fail open” without warning. +func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Secret Manager API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client secretmanagerpb.SecretManagerServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new secret manager service client. +// NewClient creates a new secret manager service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Secret Manager Service // @@ -131,8 +299,7 @@ type Client struct { // // SecretVersion func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -150,45 +317,47 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: secretmanagerpb.NewSecretManagerServiceClient(connPool), + client: secretmanagerpb.NewSecretManagerServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListSecrets lists Secrets. -func (c *Client) ListSecrets(ctx context.Context, req *secretmanagerpb.ListSecretsRequest, opts ...gax.CallOption) *SecretIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ListSecrets(ctx context.Context, req *secretmanagerpb.ListSecretsRequest, opts ...gax.CallOption) *SecretIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSecrets[0:len(c.CallOptions.ListSecrets):len(c.CallOptions.ListSecrets)], opts...) + opts = append((*c.CallOptions).ListSecrets[0:len((*c.CallOptions).ListSecrets):len((*c.CallOptions).ListSecrets)], opts...) it := &SecretIterator{} req = proto.Clone(req).(*secretmanagerpb.ListSecretsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*secretmanagerpb.Secret, string, error) { @@ -225,8 +394,7 @@ func (c *Client) ListSecrets(ctx context.Context, req *secretmanagerpb.ListSecre return it } -// CreateSecret creates a new Secret containing no SecretVersions. -func (c *Client) CreateSecret(ctx context.Context, req *secretmanagerpb.CreateSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { +func (c *gRPCClient) CreateSecret(ctx context.Context, req *secretmanagerpb.CreateSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -234,7 +402,7 @@ func (c *Client) CreateSecret(ctx context.Context, req *secretmanagerpb.CreateSe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSecret[0:len(c.CallOptions.CreateSecret):len(c.CallOptions.CreateSecret)], opts...) + opts = append((*c.CallOptions).CreateSecret[0:len((*c.CallOptions).CreateSecret):len((*c.CallOptions).CreateSecret)], opts...) var resp *secretmanagerpb.Secret err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -247,9 +415,7 @@ func (c *Client) CreateSecret(ctx context.Context, req *secretmanagerpb.CreateSe return resp, nil } -// AddSecretVersion creates a new SecretVersion containing secret data and attaches -// it to an existing Secret. -func (c *Client) AddSecretVersion(ctx context.Context, req *secretmanagerpb.AddSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { +func (c *gRPCClient) AddSecretVersion(ctx context.Context, req *secretmanagerpb.AddSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -257,7 +423,7 @@ func (c *Client) AddSecretVersion(ctx context.Context, req *secretmanagerpb.AddS } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AddSecretVersion[0:len(c.CallOptions.AddSecretVersion):len(c.CallOptions.AddSecretVersion)], opts...) + opts = append((*c.CallOptions).AddSecretVersion[0:len((*c.CallOptions).AddSecretVersion):len((*c.CallOptions).AddSecretVersion)], opts...) var resp *secretmanagerpb.SecretVersion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -270,8 +436,7 @@ func (c *Client) AddSecretVersion(ctx context.Context, req *secretmanagerpb.AddS return resp, nil } -// GetSecret gets metadata for a given Secret. -func (c *Client) GetSecret(ctx context.Context, req *secretmanagerpb.GetSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { +func (c *gRPCClient) GetSecret(ctx context.Context, req *secretmanagerpb.GetSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -279,7 +444,7 @@ func (c *Client) GetSecret(ctx context.Context, req *secretmanagerpb.GetSecretRe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSecret[0:len(c.CallOptions.GetSecret):len(c.CallOptions.GetSecret)], opts...) + opts = append((*c.CallOptions).GetSecret[0:len((*c.CallOptions).GetSecret):len((*c.CallOptions).GetSecret)], opts...) var resp *secretmanagerpb.Secret err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -292,8 +457,7 @@ func (c *Client) GetSecret(ctx context.Context, req *secretmanagerpb.GetSecretRe return resp, nil } -// UpdateSecret updates metadata of an existing Secret. -func (c *Client) UpdateSecret(ctx context.Context, req *secretmanagerpb.UpdateSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { +func (c *gRPCClient) UpdateSecret(ctx context.Context, req *secretmanagerpb.UpdateSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -301,7 +465,7 @@ func (c *Client) UpdateSecret(ctx context.Context, req *secretmanagerpb.UpdateSe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "secret.name", url.QueryEscape(req.GetSecret().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSecret[0:len(c.CallOptions.UpdateSecret):len(c.CallOptions.UpdateSecret)], opts...) + opts = append((*c.CallOptions).UpdateSecret[0:len((*c.CallOptions).UpdateSecret):len((*c.CallOptions).UpdateSecret)], opts...) var resp *secretmanagerpb.Secret err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -314,8 +478,7 @@ func (c *Client) UpdateSecret(ctx context.Context, req *secretmanagerpb.UpdateSe return resp, nil } -// DeleteSecret deletes a Secret. -func (c *Client) DeleteSecret(ctx context.Context, req *secretmanagerpb.DeleteSecretRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteSecret(ctx context.Context, req *secretmanagerpb.DeleteSecretRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -323,7 +486,7 @@ func (c *Client) DeleteSecret(ctx context.Context, req *secretmanagerpb.DeleteSe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteSecret[0:len(c.CallOptions.DeleteSecret):len(c.CallOptions.DeleteSecret)], opts...) + opts = append((*c.CallOptions).DeleteSecret[0:len((*c.CallOptions).DeleteSecret):len((*c.CallOptions).DeleteSecret)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteSecret(ctx, req, settings.GRPC...) @@ -332,12 +495,10 @@ func (c *Client) DeleteSecret(ctx context.Context, req *secretmanagerpb.DeleteSe return err } -// ListSecretVersions lists SecretVersions. This call does not return secret -// data. -func (c *Client) ListSecretVersions(ctx context.Context, req *secretmanagerpb.ListSecretVersionsRequest, opts ...gax.CallOption) *SecretVersionIterator { +func (c *gRPCClient) ListSecretVersions(ctx context.Context, req *secretmanagerpb.ListSecretVersionsRequest, opts ...gax.CallOption) *SecretVersionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSecretVersions[0:len(c.CallOptions.ListSecretVersions):len(c.CallOptions.ListSecretVersions)], opts...) + opts = append((*c.CallOptions).ListSecretVersions[0:len((*c.CallOptions).ListSecretVersions):len((*c.CallOptions).ListSecretVersions)], opts...) it := &SecretVersionIterator{} req = proto.Clone(req).(*secretmanagerpb.ListSecretVersionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*secretmanagerpb.SecretVersion, string, error) { @@ -374,11 +535,7 @@ func (c *Client) ListSecretVersions(ctx context.Context, req *secretmanagerpb.Li return it } -// GetSecretVersion gets metadata for a SecretVersion. -// -// projects/*/secrets/*/versions/latest is an alias to the most recently -// created SecretVersion. -func (c *Client) GetSecretVersion(ctx context.Context, req *secretmanagerpb.GetSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { +func (c *gRPCClient) GetSecretVersion(ctx context.Context, req *secretmanagerpb.GetSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -386,7 +543,7 @@ func (c *Client) GetSecretVersion(ctx context.Context, req *secretmanagerpb.GetS } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSecretVersion[0:len(c.CallOptions.GetSecretVersion):len(c.CallOptions.GetSecretVersion)], opts...) + opts = append((*c.CallOptions).GetSecretVersion[0:len((*c.CallOptions).GetSecretVersion):len((*c.CallOptions).GetSecretVersion)], opts...) var resp *secretmanagerpb.SecretVersion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -399,11 +556,7 @@ func (c *Client) GetSecretVersion(ctx context.Context, req *secretmanagerpb.GetS return resp, nil } -// AccessSecretVersion accesses a SecretVersion. This call returns the secret data. -// -// projects/*/secrets/*/versions/latest is an alias to the most recently -// created SecretVersion. -func (c *Client) AccessSecretVersion(ctx context.Context, req *secretmanagerpb.AccessSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.AccessSecretVersionResponse, error) { +func (c *gRPCClient) AccessSecretVersion(ctx context.Context, req *secretmanagerpb.AccessSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.AccessSecretVersionResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -411,7 +564,7 @@ func (c *Client) AccessSecretVersion(ctx context.Context, req *secretmanagerpb.A } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AccessSecretVersion[0:len(c.CallOptions.AccessSecretVersion):len(c.CallOptions.AccessSecretVersion)], opts...) + opts = append((*c.CallOptions).AccessSecretVersion[0:len((*c.CallOptions).AccessSecretVersion):len((*c.CallOptions).AccessSecretVersion)], opts...) var resp *secretmanagerpb.AccessSecretVersionResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -424,11 +577,7 @@ func (c *Client) AccessSecretVersion(ctx context.Context, req *secretmanagerpb.A return resp, nil } -// DisableSecretVersion disables a SecretVersion. -// -// Sets the state of the SecretVersion to -// DISABLED. -func (c *Client) DisableSecretVersion(ctx context.Context, req *secretmanagerpb.DisableSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { +func (c *gRPCClient) DisableSecretVersion(ctx context.Context, req *secretmanagerpb.DisableSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -436,7 +585,7 @@ func (c *Client) DisableSecretVersion(ctx context.Context, req *secretmanagerpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DisableSecretVersion[0:len(c.CallOptions.DisableSecretVersion):len(c.CallOptions.DisableSecretVersion)], opts...) + opts = append((*c.CallOptions).DisableSecretVersion[0:len((*c.CallOptions).DisableSecretVersion):len((*c.CallOptions).DisableSecretVersion)], opts...) var resp *secretmanagerpb.SecretVersion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -449,11 +598,7 @@ func (c *Client) DisableSecretVersion(ctx context.Context, req *secretmanagerpb. return resp, nil } -// EnableSecretVersion enables a SecretVersion. -// -// Sets the state of the SecretVersion to -// ENABLED. -func (c *Client) EnableSecretVersion(ctx context.Context, req *secretmanagerpb.EnableSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { +func (c *gRPCClient) EnableSecretVersion(ctx context.Context, req *secretmanagerpb.EnableSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -461,7 +606,7 @@ func (c *Client) EnableSecretVersion(ctx context.Context, req *secretmanagerpb.E } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.EnableSecretVersion[0:len(c.CallOptions.EnableSecretVersion):len(c.CallOptions.EnableSecretVersion)], opts...) + opts = append((*c.CallOptions).EnableSecretVersion[0:len((*c.CallOptions).EnableSecretVersion):len((*c.CallOptions).EnableSecretVersion)], opts...) var resp *secretmanagerpb.SecretVersion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -474,12 +619,7 @@ func (c *Client) EnableSecretVersion(ctx context.Context, req *secretmanagerpb.E return resp, nil } -// DestroySecretVersion destroys a SecretVersion. -// -// Sets the state of the SecretVersion to -// DESTROYED and irrevocably destroys the -// secret data. -func (c *Client) DestroySecretVersion(ctx context.Context, req *secretmanagerpb.DestroySecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { +func (c *gRPCClient) DestroySecretVersion(ctx context.Context, req *secretmanagerpb.DestroySecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -487,7 +627,7 @@ func (c *Client) DestroySecretVersion(ctx context.Context, req *secretmanagerpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DestroySecretVersion[0:len(c.CallOptions.DestroySecretVersion):len(c.CallOptions.DestroySecretVersion)], opts...) + opts = append((*c.CallOptions).DestroySecretVersion[0:len((*c.CallOptions).DestroySecretVersion):len((*c.CallOptions).DestroySecretVersion)], opts...) var resp *secretmanagerpb.SecretVersion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -500,12 +640,7 @@ func (c *Client) DestroySecretVersion(ctx context.Context, req *secretmanagerpb. return resp, nil } -// SetIamPolicy sets the access control policy on the specified secret. Replaces any -// existing policy. -// -// Permissions on SecretVersions are enforced according -// to the policy set on the associated Secret. -func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -513,7 +648,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -526,9 +661,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques return resp, nil } -// GetIamPolicy gets the access control policy for a secret. -// Returns empty policy if the secret exists and does not have a policy set. -func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -536,7 +669,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -549,14 +682,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques return resp, nil } -// TestIamPermissions returns permissions that a caller has for the specified secret. -// If the secret does not exist, this call returns an empty set of -// permissions, not a NOT_FOUND error. -// -// Note: This operation is designed to be used for building permission-aware -// UIs and command-line tools, not for authorization checking. This operation -// may “fail open” without warning. -func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *gRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -564,7 +690,7 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/secretmanager/apiv1/secret_manager_client_example_test.go b/secretmanager/apiv1/secret_manager_client_example_test.go index d543874031b8..cdaaf8f3d73c 100644 --- a/secretmanager/apiv1/secret_manager_client_example_test.go +++ b/secretmanager/apiv1/secret_manager_client_example_test.go @@ -31,19 +31,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ListSecrets() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.ListSecretsRequest{ // TODO: Fill request struct fields. @@ -63,13 +63,12 @@ func ExampleClient_ListSecrets() { } func ExampleClient_CreateSecret() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.CreateSecretRequest{ // TODO: Fill request struct fields. @@ -83,13 +82,12 @@ func ExampleClient_CreateSecret() { } func ExampleClient_AddSecretVersion() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.AddSecretVersionRequest{ // TODO: Fill request struct fields. @@ -103,13 +101,12 @@ func ExampleClient_AddSecretVersion() { } func ExampleClient_GetSecret() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.GetSecretRequest{ // TODO: Fill request struct fields. @@ -123,13 +120,12 @@ func ExampleClient_GetSecret() { } func ExampleClient_UpdateSecret() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.UpdateSecretRequest{ // TODO: Fill request struct fields. @@ -148,6 +144,7 @@ func ExampleClient_DeleteSecret() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.DeleteSecretRequest{ // TODO: Fill request struct fields. @@ -159,14 +156,12 @@ func ExampleClient_DeleteSecret() { } func ExampleClient_ListSecretVersions() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.ListSecretVersionsRequest{ // TODO: Fill request struct fields. @@ -186,13 +181,12 @@ func ExampleClient_ListSecretVersions() { } func ExampleClient_GetSecretVersion() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.GetSecretVersionRequest{ // TODO: Fill request struct fields. @@ -206,13 +200,12 @@ func ExampleClient_GetSecretVersion() { } func ExampleClient_AccessSecretVersion() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.AccessSecretVersionRequest{ // TODO: Fill request struct fields. @@ -226,13 +219,12 @@ func ExampleClient_AccessSecretVersion() { } func ExampleClient_DisableSecretVersion() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.DisableSecretVersionRequest{ // TODO: Fill request struct fields. @@ -246,13 +238,12 @@ func ExampleClient_DisableSecretVersion() { } func ExampleClient_EnableSecretVersion() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.EnableSecretVersionRequest{ // TODO: Fill request struct fields. @@ -266,13 +257,12 @@ func ExampleClient_EnableSecretVersion() { } func ExampleClient_DestroySecretVersion() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.DestroySecretVersionRequest{ // TODO: Fill request struct fields. @@ -286,13 +276,12 @@ func ExampleClient_DestroySecretVersion() { } func ExampleClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -306,13 +295,12 @@ func ExampleClient_SetIamPolicy() { } func ExampleClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -326,13 +314,12 @@ func ExampleClient_GetIamPolicy() { } func ExampleClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/secretmanager/apiv1beta1/doc.go b/secretmanager/apiv1beta1/doc.go index cda42c512b30..7400718be15b 100644 --- a/secretmanager/apiv1beta1/doc.go +++ b/secretmanager/apiv1beta1/doc.go @@ -20,6 +20,8 @@ // Stores sensitive data such as API keys, passwords, and certificates. // Provides convenience while improving security. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package secretmanager // import "cloud.google.com/go/secretmanager/apiv1beta1" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/secretmanager/apiv1beta1/iam.go b/secretmanager/apiv1beta1/iam.go index 9d5fd4bf7651..f3625b0cb56f 100644 --- a/secretmanager/apiv1beta1/iam.go +++ b/secretmanager/apiv1beta1/iam.go @@ -22,5 +22,8 @@ import ( // indicated by the given resource path. Name should be of the format // `projects/my-project/secrets/my-secret`. func (c *Client) IAM(name string) *iam.Handle { - return iam.InternalNewHandleGRPCClient(c.client, name) + if grpcClient, ok := c.internalClient.(*gRPCClient); ok { + return iam.InternalNewHandleGRPCClient(grpcClient.client, name) + } + return iam.InternalNewHandleGRPCClient(nil, name) } diff --git a/secretmanager/apiv1beta1/secret_manager_client.go b/secretmanager/apiv1beta1/secret_manager_client.go index 8a37accab305..1afc8f05bf59 100644 --- a/secretmanager/apiv1beta1/secret_manager_client.go +++ b/secretmanager/apiv1beta1/secret_manager_client.go @@ -57,7 +57,7 @@ type CallOptions struct { TestIamPermissions []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("secretmanager.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("secretmanager.mtls.googleapis.com:443"), @@ -100,27 +100,195 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Secret Manager API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListSecrets(context.Context, *secretmanagerpb.ListSecretsRequest, ...gax.CallOption) *SecretIterator + CreateSecret(context.Context, *secretmanagerpb.CreateSecretRequest, ...gax.CallOption) (*secretmanagerpb.Secret, error) + AddSecretVersion(context.Context, *secretmanagerpb.AddSecretVersionRequest, ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) + GetSecret(context.Context, *secretmanagerpb.GetSecretRequest, ...gax.CallOption) (*secretmanagerpb.Secret, error) + UpdateSecret(context.Context, *secretmanagerpb.UpdateSecretRequest, ...gax.CallOption) (*secretmanagerpb.Secret, error) + DeleteSecret(context.Context, *secretmanagerpb.DeleteSecretRequest, ...gax.CallOption) error + ListSecretVersions(context.Context, *secretmanagerpb.ListSecretVersionsRequest, ...gax.CallOption) *SecretVersionIterator + GetSecretVersion(context.Context, *secretmanagerpb.GetSecretVersionRequest, ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) + AccessSecretVersion(context.Context, *secretmanagerpb.AccessSecretVersionRequest, ...gax.CallOption) (*secretmanagerpb.AccessSecretVersionResponse, error) + DisableSecretVersion(context.Context, *secretmanagerpb.DisableSecretVersionRequest, ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) + EnableSecretVersion(context.Context, *secretmanagerpb.EnableSecretVersionRequest, ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) + DestroySecretVersion(context.Context, *secretmanagerpb.DestroySecretVersionRequest, ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) +} + // Client is a client for interacting with Secret Manager API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Secret Manager Service +// +// Manages secrets and operations using those secrets. Implements a REST +// model with the following objects: +// +// Secret +// +// SecretVersion type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListSecrets lists Secrets. +func (c *Client) ListSecrets(ctx context.Context, req *secretmanagerpb.ListSecretsRequest, opts ...gax.CallOption) *SecretIterator { + return c.internalClient.ListSecrets(ctx, req, opts...) +} + +// CreateSecret creates a new Secret containing no SecretVersions. +func (c *Client) CreateSecret(ctx context.Context, req *secretmanagerpb.CreateSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { + return c.internalClient.CreateSecret(ctx, req, opts...) +} + +// AddSecretVersion creates a new SecretVersion containing secret data and attaches +// it to an existing Secret. +func (c *Client) AddSecretVersion(ctx context.Context, req *secretmanagerpb.AddSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { + return c.internalClient.AddSecretVersion(ctx, req, opts...) +} + +// GetSecret gets metadata for a given Secret. +func (c *Client) GetSecret(ctx context.Context, req *secretmanagerpb.GetSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { + return c.internalClient.GetSecret(ctx, req, opts...) +} + +// UpdateSecret updates metadata of an existing Secret. +func (c *Client) UpdateSecret(ctx context.Context, req *secretmanagerpb.UpdateSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { + return c.internalClient.UpdateSecret(ctx, req, opts...) +} + +// DeleteSecret deletes a Secret. +func (c *Client) DeleteSecret(ctx context.Context, req *secretmanagerpb.DeleteSecretRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteSecret(ctx, req, opts...) +} + +// ListSecretVersions lists SecretVersions. This call does not return secret +// data. +func (c *Client) ListSecretVersions(ctx context.Context, req *secretmanagerpb.ListSecretVersionsRequest, opts ...gax.CallOption) *SecretVersionIterator { + return c.internalClient.ListSecretVersions(ctx, req, opts...) +} + +// GetSecretVersion gets metadata for a SecretVersion. +// +// projects/*/secrets/*/versions/latest is an alias to the latest +// SecretVersion. +func (c *Client) GetSecretVersion(ctx context.Context, req *secretmanagerpb.GetSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { + return c.internalClient.GetSecretVersion(ctx, req, opts...) +} + +// AccessSecretVersion accesses a SecretVersion. This call returns the secret data. +// +// projects/*/secrets/*/versions/latest is an alias to the latest +// SecretVersion. +func (c *Client) AccessSecretVersion(ctx context.Context, req *secretmanagerpb.AccessSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.AccessSecretVersionResponse, error) { + return c.internalClient.AccessSecretVersion(ctx, req, opts...) +} + +// DisableSecretVersion disables a SecretVersion. +// +// Sets the state of the SecretVersion to +// DISABLED. +func (c *Client) DisableSecretVersion(ctx context.Context, req *secretmanagerpb.DisableSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { + return c.internalClient.DisableSecretVersion(ctx, req, opts...) +} + +// EnableSecretVersion enables a SecretVersion. +// +// Sets the state of the SecretVersion to +// ENABLED. +func (c *Client) EnableSecretVersion(ctx context.Context, req *secretmanagerpb.EnableSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { + return c.internalClient.EnableSecretVersion(ctx, req, opts...) +} + +// DestroySecretVersion destroys a SecretVersion. +// +// Sets the state of the SecretVersion to +// DESTROYED and irrevocably destroys the +// secret data. +func (c *Client) DestroySecretVersion(ctx context.Context, req *secretmanagerpb.DestroySecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { + return c.internalClient.DestroySecretVersion(ctx, req, opts...) +} + +// SetIamPolicy sets the access control policy on the specified secret. Replaces any +// existing policy. +// +// Permissions on SecretVersions are enforced according +// to the policy set on the associated Secret. +func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy for a secret. +// Returns empty policy if the secret exists and does not have a policy set. +func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns permissions that a caller has for the specified secret. +// If the secret does not exist, this call returns an empty set of +// permissions, not a NOT_FOUND error. +// +// Note: This operation is designed to be used for building permission-aware +// UIs and command-line tools, not for authorization checking. This operation +// may “fail open” without warning. +func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Secret Manager API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client secretmanagerpb.SecretManagerServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new secret manager service client. +// NewClient creates a new secret manager service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Secret Manager Service // @@ -131,8 +299,7 @@ type Client struct { // // SecretVersion func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -150,45 +317,47 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: secretmanagerpb.NewSecretManagerServiceClient(connPool), + client: secretmanagerpb.NewSecretManagerServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListSecrets lists Secrets. -func (c *Client) ListSecrets(ctx context.Context, req *secretmanagerpb.ListSecretsRequest, opts ...gax.CallOption) *SecretIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ListSecrets(ctx context.Context, req *secretmanagerpb.ListSecretsRequest, opts ...gax.CallOption) *SecretIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSecrets[0:len(c.CallOptions.ListSecrets):len(c.CallOptions.ListSecrets)], opts...) + opts = append((*c.CallOptions).ListSecrets[0:len((*c.CallOptions).ListSecrets):len((*c.CallOptions).ListSecrets)], opts...) it := &SecretIterator{} req = proto.Clone(req).(*secretmanagerpb.ListSecretsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*secretmanagerpb.Secret, string, error) { @@ -225,8 +394,7 @@ func (c *Client) ListSecrets(ctx context.Context, req *secretmanagerpb.ListSecre return it } -// CreateSecret creates a new Secret containing no SecretVersions. -func (c *Client) CreateSecret(ctx context.Context, req *secretmanagerpb.CreateSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { +func (c *gRPCClient) CreateSecret(ctx context.Context, req *secretmanagerpb.CreateSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -234,7 +402,7 @@ func (c *Client) CreateSecret(ctx context.Context, req *secretmanagerpb.CreateSe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSecret[0:len(c.CallOptions.CreateSecret):len(c.CallOptions.CreateSecret)], opts...) + opts = append((*c.CallOptions).CreateSecret[0:len((*c.CallOptions).CreateSecret):len((*c.CallOptions).CreateSecret)], opts...) var resp *secretmanagerpb.Secret err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -247,9 +415,7 @@ func (c *Client) CreateSecret(ctx context.Context, req *secretmanagerpb.CreateSe return resp, nil } -// AddSecretVersion creates a new SecretVersion containing secret data and attaches -// it to an existing Secret. -func (c *Client) AddSecretVersion(ctx context.Context, req *secretmanagerpb.AddSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { +func (c *gRPCClient) AddSecretVersion(ctx context.Context, req *secretmanagerpb.AddSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -257,7 +423,7 @@ func (c *Client) AddSecretVersion(ctx context.Context, req *secretmanagerpb.AddS } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AddSecretVersion[0:len(c.CallOptions.AddSecretVersion):len(c.CallOptions.AddSecretVersion)], opts...) + opts = append((*c.CallOptions).AddSecretVersion[0:len((*c.CallOptions).AddSecretVersion):len((*c.CallOptions).AddSecretVersion)], opts...) var resp *secretmanagerpb.SecretVersion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -270,8 +436,7 @@ func (c *Client) AddSecretVersion(ctx context.Context, req *secretmanagerpb.AddS return resp, nil } -// GetSecret gets metadata for a given Secret. -func (c *Client) GetSecret(ctx context.Context, req *secretmanagerpb.GetSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { +func (c *gRPCClient) GetSecret(ctx context.Context, req *secretmanagerpb.GetSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -279,7 +444,7 @@ func (c *Client) GetSecret(ctx context.Context, req *secretmanagerpb.GetSecretRe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSecret[0:len(c.CallOptions.GetSecret):len(c.CallOptions.GetSecret)], opts...) + opts = append((*c.CallOptions).GetSecret[0:len((*c.CallOptions).GetSecret):len((*c.CallOptions).GetSecret)], opts...) var resp *secretmanagerpb.Secret err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -292,8 +457,7 @@ func (c *Client) GetSecret(ctx context.Context, req *secretmanagerpb.GetSecretRe return resp, nil } -// UpdateSecret updates metadata of an existing Secret. -func (c *Client) UpdateSecret(ctx context.Context, req *secretmanagerpb.UpdateSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { +func (c *gRPCClient) UpdateSecret(ctx context.Context, req *secretmanagerpb.UpdateSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -301,7 +465,7 @@ func (c *Client) UpdateSecret(ctx context.Context, req *secretmanagerpb.UpdateSe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "secret.name", url.QueryEscape(req.GetSecret().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSecret[0:len(c.CallOptions.UpdateSecret):len(c.CallOptions.UpdateSecret)], opts...) + opts = append((*c.CallOptions).UpdateSecret[0:len((*c.CallOptions).UpdateSecret):len((*c.CallOptions).UpdateSecret)], opts...) var resp *secretmanagerpb.Secret err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -314,8 +478,7 @@ func (c *Client) UpdateSecret(ctx context.Context, req *secretmanagerpb.UpdateSe return resp, nil } -// DeleteSecret deletes a Secret. -func (c *Client) DeleteSecret(ctx context.Context, req *secretmanagerpb.DeleteSecretRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteSecret(ctx context.Context, req *secretmanagerpb.DeleteSecretRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -323,7 +486,7 @@ func (c *Client) DeleteSecret(ctx context.Context, req *secretmanagerpb.DeleteSe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteSecret[0:len(c.CallOptions.DeleteSecret):len(c.CallOptions.DeleteSecret)], opts...) + opts = append((*c.CallOptions).DeleteSecret[0:len((*c.CallOptions).DeleteSecret):len((*c.CallOptions).DeleteSecret)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteSecret(ctx, req, settings.GRPC...) @@ -332,12 +495,10 @@ func (c *Client) DeleteSecret(ctx context.Context, req *secretmanagerpb.DeleteSe return err } -// ListSecretVersions lists SecretVersions. This call does not return secret -// data. -func (c *Client) ListSecretVersions(ctx context.Context, req *secretmanagerpb.ListSecretVersionsRequest, opts ...gax.CallOption) *SecretVersionIterator { +func (c *gRPCClient) ListSecretVersions(ctx context.Context, req *secretmanagerpb.ListSecretVersionsRequest, opts ...gax.CallOption) *SecretVersionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSecretVersions[0:len(c.CallOptions.ListSecretVersions):len(c.CallOptions.ListSecretVersions)], opts...) + opts = append((*c.CallOptions).ListSecretVersions[0:len((*c.CallOptions).ListSecretVersions):len((*c.CallOptions).ListSecretVersions)], opts...) it := &SecretVersionIterator{} req = proto.Clone(req).(*secretmanagerpb.ListSecretVersionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*secretmanagerpb.SecretVersion, string, error) { @@ -374,11 +535,7 @@ func (c *Client) ListSecretVersions(ctx context.Context, req *secretmanagerpb.Li return it } -// GetSecretVersion gets metadata for a SecretVersion. -// -// projects/*/secrets/*/versions/latest is an alias to the latest -// SecretVersion. -func (c *Client) GetSecretVersion(ctx context.Context, req *secretmanagerpb.GetSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { +func (c *gRPCClient) GetSecretVersion(ctx context.Context, req *secretmanagerpb.GetSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -386,7 +543,7 @@ func (c *Client) GetSecretVersion(ctx context.Context, req *secretmanagerpb.GetS } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSecretVersion[0:len(c.CallOptions.GetSecretVersion):len(c.CallOptions.GetSecretVersion)], opts...) + opts = append((*c.CallOptions).GetSecretVersion[0:len((*c.CallOptions).GetSecretVersion):len((*c.CallOptions).GetSecretVersion)], opts...) var resp *secretmanagerpb.SecretVersion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -399,11 +556,7 @@ func (c *Client) GetSecretVersion(ctx context.Context, req *secretmanagerpb.GetS return resp, nil } -// AccessSecretVersion accesses a SecretVersion. This call returns the secret data. -// -// projects/*/secrets/*/versions/latest is an alias to the latest -// SecretVersion. -func (c *Client) AccessSecretVersion(ctx context.Context, req *secretmanagerpb.AccessSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.AccessSecretVersionResponse, error) { +func (c *gRPCClient) AccessSecretVersion(ctx context.Context, req *secretmanagerpb.AccessSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.AccessSecretVersionResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -411,7 +564,7 @@ func (c *Client) AccessSecretVersion(ctx context.Context, req *secretmanagerpb.A } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AccessSecretVersion[0:len(c.CallOptions.AccessSecretVersion):len(c.CallOptions.AccessSecretVersion)], opts...) + opts = append((*c.CallOptions).AccessSecretVersion[0:len((*c.CallOptions).AccessSecretVersion):len((*c.CallOptions).AccessSecretVersion)], opts...) var resp *secretmanagerpb.AccessSecretVersionResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -424,11 +577,7 @@ func (c *Client) AccessSecretVersion(ctx context.Context, req *secretmanagerpb.A return resp, nil } -// DisableSecretVersion disables a SecretVersion. -// -// Sets the state of the SecretVersion to -// DISABLED. -func (c *Client) DisableSecretVersion(ctx context.Context, req *secretmanagerpb.DisableSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { +func (c *gRPCClient) DisableSecretVersion(ctx context.Context, req *secretmanagerpb.DisableSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -436,7 +585,7 @@ func (c *Client) DisableSecretVersion(ctx context.Context, req *secretmanagerpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DisableSecretVersion[0:len(c.CallOptions.DisableSecretVersion):len(c.CallOptions.DisableSecretVersion)], opts...) + opts = append((*c.CallOptions).DisableSecretVersion[0:len((*c.CallOptions).DisableSecretVersion):len((*c.CallOptions).DisableSecretVersion)], opts...) var resp *secretmanagerpb.SecretVersion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -449,11 +598,7 @@ func (c *Client) DisableSecretVersion(ctx context.Context, req *secretmanagerpb. return resp, nil } -// EnableSecretVersion enables a SecretVersion. -// -// Sets the state of the SecretVersion to -// ENABLED. -func (c *Client) EnableSecretVersion(ctx context.Context, req *secretmanagerpb.EnableSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { +func (c *gRPCClient) EnableSecretVersion(ctx context.Context, req *secretmanagerpb.EnableSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -461,7 +606,7 @@ func (c *Client) EnableSecretVersion(ctx context.Context, req *secretmanagerpb.E } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.EnableSecretVersion[0:len(c.CallOptions.EnableSecretVersion):len(c.CallOptions.EnableSecretVersion)], opts...) + opts = append((*c.CallOptions).EnableSecretVersion[0:len((*c.CallOptions).EnableSecretVersion):len((*c.CallOptions).EnableSecretVersion)], opts...) var resp *secretmanagerpb.SecretVersion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -474,12 +619,7 @@ func (c *Client) EnableSecretVersion(ctx context.Context, req *secretmanagerpb.E return resp, nil } -// DestroySecretVersion destroys a SecretVersion. -// -// Sets the state of the SecretVersion to -// DESTROYED and irrevocably destroys the -// secret data. -func (c *Client) DestroySecretVersion(ctx context.Context, req *secretmanagerpb.DestroySecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { +func (c *gRPCClient) DestroySecretVersion(ctx context.Context, req *secretmanagerpb.DestroySecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -487,7 +627,7 @@ func (c *Client) DestroySecretVersion(ctx context.Context, req *secretmanagerpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DestroySecretVersion[0:len(c.CallOptions.DestroySecretVersion):len(c.CallOptions.DestroySecretVersion)], opts...) + opts = append((*c.CallOptions).DestroySecretVersion[0:len((*c.CallOptions).DestroySecretVersion):len((*c.CallOptions).DestroySecretVersion)], opts...) var resp *secretmanagerpb.SecretVersion err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -500,12 +640,7 @@ func (c *Client) DestroySecretVersion(ctx context.Context, req *secretmanagerpb. return resp, nil } -// SetIamPolicy sets the access control policy on the specified secret. Replaces any -// existing policy. -// -// Permissions on SecretVersions are enforced according -// to the policy set on the associated Secret. -func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -513,7 +648,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -526,9 +661,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques return resp, nil } -// GetIamPolicy gets the access control policy for a secret. -// Returns empty policy if the secret exists and does not have a policy set. -func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -536,7 +669,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -549,14 +682,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques return resp, nil } -// TestIamPermissions returns permissions that a caller has for the specified secret. -// If the secret does not exist, this call returns an empty set of -// permissions, not a NOT_FOUND error. -// -// Note: This operation is designed to be used for building permission-aware -// UIs and command-line tools, not for authorization checking. This operation -// may “fail open” without warning. -func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *gRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -564,7 +690,7 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/secretmanager/apiv1beta1/secret_manager_client_example_test.go b/secretmanager/apiv1beta1/secret_manager_client_example_test.go index 3a8f8f55c5b6..4847f4eab58f 100644 --- a/secretmanager/apiv1beta1/secret_manager_client_example_test.go +++ b/secretmanager/apiv1beta1/secret_manager_client_example_test.go @@ -31,19 +31,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ListSecrets() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.ListSecretsRequest{ // TODO: Fill request struct fields. @@ -63,13 +63,12 @@ func ExampleClient_ListSecrets() { } func ExampleClient_CreateSecret() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.CreateSecretRequest{ // TODO: Fill request struct fields. @@ -83,13 +82,12 @@ func ExampleClient_CreateSecret() { } func ExampleClient_AddSecretVersion() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.AddSecretVersionRequest{ // TODO: Fill request struct fields. @@ -103,13 +101,12 @@ func ExampleClient_AddSecretVersion() { } func ExampleClient_GetSecret() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.GetSecretRequest{ // TODO: Fill request struct fields. @@ -123,13 +120,12 @@ func ExampleClient_GetSecret() { } func ExampleClient_UpdateSecret() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.UpdateSecretRequest{ // TODO: Fill request struct fields. @@ -148,6 +144,7 @@ func ExampleClient_DeleteSecret() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.DeleteSecretRequest{ // TODO: Fill request struct fields. @@ -159,14 +156,12 @@ func ExampleClient_DeleteSecret() { } func ExampleClient_ListSecretVersions() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.ListSecretVersionsRequest{ // TODO: Fill request struct fields. @@ -186,13 +181,12 @@ func ExampleClient_ListSecretVersions() { } func ExampleClient_GetSecretVersion() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.GetSecretVersionRequest{ // TODO: Fill request struct fields. @@ -206,13 +200,12 @@ func ExampleClient_GetSecretVersion() { } func ExampleClient_AccessSecretVersion() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.AccessSecretVersionRequest{ // TODO: Fill request struct fields. @@ -226,13 +219,12 @@ func ExampleClient_AccessSecretVersion() { } func ExampleClient_DisableSecretVersion() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.DisableSecretVersionRequest{ // TODO: Fill request struct fields. @@ -246,13 +238,12 @@ func ExampleClient_DisableSecretVersion() { } func ExampleClient_EnableSecretVersion() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.EnableSecretVersionRequest{ // TODO: Fill request struct fields. @@ -266,13 +257,12 @@ func ExampleClient_EnableSecretVersion() { } func ExampleClient_DestroySecretVersion() { - // import secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1beta1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &secretmanagerpb.DestroySecretVersionRequest{ // TODO: Fill request struct fields. @@ -286,13 +276,12 @@ func ExampleClient_DestroySecretVersion() { } func ExampleClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -306,13 +295,12 @@ func ExampleClient_SetIamPolicy() { } func ExampleClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -326,13 +314,12 @@ func ExampleClient_GetIamPolicy() { } func ExampleClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := secretmanager.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/security/privateca/apiv1/certificate_authority_client.go b/security/privateca/apiv1/certificate_authority_client.go index c8647e01272a..05637c547a1a 100644 --- a/security/privateca/apiv1/certificate_authority_client.go +++ b/security/privateca/apiv1/certificate_authority_client.go @@ -73,7 +73,7 @@ type CertificateAuthorityCallOptions struct { UpdateCertificateTemplate []gax.CallOption } -func defaultCertificateAuthorityClientOptions() []option.ClientOption { +func defaultCertificateAuthorityGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("privateca.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("privateca.mtls.googleapis.com:443"), @@ -467,38 +467,372 @@ func defaultCertificateAuthorityCallOptions() *CertificateAuthorityCallOptions { } } +// internalCertificateAuthorityClient is an interface that defines the methods availaible from Certificate Authority API. +type internalCertificateAuthorityClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateCertificate(context.Context, *privatecapb.CreateCertificateRequest, ...gax.CallOption) (*privatecapb.Certificate, error) + GetCertificate(context.Context, *privatecapb.GetCertificateRequest, ...gax.CallOption) (*privatecapb.Certificate, error) + ListCertificates(context.Context, *privatecapb.ListCertificatesRequest, ...gax.CallOption) *CertificateIterator + RevokeCertificate(context.Context, *privatecapb.RevokeCertificateRequest, ...gax.CallOption) (*privatecapb.Certificate, error) + UpdateCertificate(context.Context, *privatecapb.UpdateCertificateRequest, ...gax.CallOption) (*privatecapb.Certificate, error) + ActivateCertificateAuthority(context.Context, *privatecapb.ActivateCertificateAuthorityRequest, ...gax.CallOption) (*ActivateCertificateAuthorityOperation, error) + ActivateCertificateAuthorityOperation(name string) *ActivateCertificateAuthorityOperation + CreateCertificateAuthority(context.Context, *privatecapb.CreateCertificateAuthorityRequest, ...gax.CallOption) (*CreateCertificateAuthorityOperation, error) + CreateCertificateAuthorityOperation(name string) *CreateCertificateAuthorityOperation + DisableCertificateAuthority(context.Context, *privatecapb.DisableCertificateAuthorityRequest, ...gax.CallOption) (*DisableCertificateAuthorityOperation, error) + DisableCertificateAuthorityOperation(name string) *DisableCertificateAuthorityOperation + EnableCertificateAuthority(context.Context, *privatecapb.EnableCertificateAuthorityRequest, ...gax.CallOption) (*EnableCertificateAuthorityOperation, error) + EnableCertificateAuthorityOperation(name string) *EnableCertificateAuthorityOperation + FetchCertificateAuthorityCsr(context.Context, *privatecapb.FetchCertificateAuthorityCsrRequest, ...gax.CallOption) (*privatecapb.FetchCertificateAuthorityCsrResponse, error) + GetCertificateAuthority(context.Context, *privatecapb.GetCertificateAuthorityRequest, ...gax.CallOption) (*privatecapb.CertificateAuthority, error) + ListCertificateAuthorities(context.Context, *privatecapb.ListCertificateAuthoritiesRequest, ...gax.CallOption) *CertificateAuthorityIterator + UndeleteCertificateAuthority(context.Context, *privatecapb.UndeleteCertificateAuthorityRequest, ...gax.CallOption) (*UndeleteCertificateAuthorityOperation, error) + UndeleteCertificateAuthorityOperation(name string) *UndeleteCertificateAuthorityOperation + DeleteCertificateAuthority(context.Context, *privatecapb.DeleteCertificateAuthorityRequest, ...gax.CallOption) (*DeleteCertificateAuthorityOperation, error) + DeleteCertificateAuthorityOperation(name string) *DeleteCertificateAuthorityOperation + UpdateCertificateAuthority(context.Context, *privatecapb.UpdateCertificateAuthorityRequest, ...gax.CallOption) (*UpdateCertificateAuthorityOperation, error) + UpdateCertificateAuthorityOperation(name string) *UpdateCertificateAuthorityOperation + CreateCaPool(context.Context, *privatecapb.CreateCaPoolRequest, ...gax.CallOption) (*CreateCaPoolOperation, error) + CreateCaPoolOperation(name string) *CreateCaPoolOperation + UpdateCaPool(context.Context, *privatecapb.UpdateCaPoolRequest, ...gax.CallOption) (*UpdateCaPoolOperation, error) + UpdateCaPoolOperation(name string) *UpdateCaPoolOperation + GetCaPool(context.Context, *privatecapb.GetCaPoolRequest, ...gax.CallOption) (*privatecapb.CaPool, error) + ListCaPools(context.Context, *privatecapb.ListCaPoolsRequest, ...gax.CallOption) *CaPoolIterator + DeleteCaPool(context.Context, *privatecapb.DeleteCaPoolRequest, ...gax.CallOption) (*DeleteCaPoolOperation, error) + DeleteCaPoolOperation(name string) *DeleteCaPoolOperation + FetchCaCerts(context.Context, *privatecapb.FetchCaCertsRequest, ...gax.CallOption) (*privatecapb.FetchCaCertsResponse, error) + GetCertificateRevocationList(context.Context, *privatecapb.GetCertificateRevocationListRequest, ...gax.CallOption) (*privatecapb.CertificateRevocationList, error) + ListCertificateRevocationLists(context.Context, *privatecapb.ListCertificateRevocationListsRequest, ...gax.CallOption) *CertificateRevocationListIterator + UpdateCertificateRevocationList(context.Context, *privatecapb.UpdateCertificateRevocationListRequest, ...gax.CallOption) (*UpdateCertificateRevocationListOperation, error) + UpdateCertificateRevocationListOperation(name string) *UpdateCertificateRevocationListOperation + CreateCertificateTemplate(context.Context, *privatecapb.CreateCertificateTemplateRequest, ...gax.CallOption) (*CreateCertificateTemplateOperation, error) + CreateCertificateTemplateOperation(name string) *CreateCertificateTemplateOperation + DeleteCertificateTemplate(context.Context, *privatecapb.DeleteCertificateTemplateRequest, ...gax.CallOption) (*DeleteCertificateTemplateOperation, error) + DeleteCertificateTemplateOperation(name string) *DeleteCertificateTemplateOperation + GetCertificateTemplate(context.Context, *privatecapb.GetCertificateTemplateRequest, ...gax.CallOption) (*privatecapb.CertificateTemplate, error) + ListCertificateTemplates(context.Context, *privatecapb.ListCertificateTemplatesRequest, ...gax.CallOption) *CertificateTemplateIterator + UpdateCertificateTemplate(context.Context, *privatecapb.UpdateCertificateTemplateRequest, ...gax.CallOption) (*UpdateCertificateTemplateOperation, error) + UpdateCertificateTemplateOperation(name string) *UpdateCertificateTemplateOperation +} + // CertificateAuthorityClient is a client for interacting with Certificate Authority API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// [Certificate Authority Service][google.cloud.security.privateca.v1.CertificateAuthorityService] manages private +// certificate authorities and issued certificates. type CertificateAuthorityClient struct { + // The internal transport-dependent client. + internalClient internalCertificateAuthorityClient + + // The call options for this service. + CallOptions *CertificateAuthorityCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CertificateAuthorityClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CertificateAuthorityClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CertificateAuthorityClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateCertificate create a new Certificate in a given Project, Location from a particular +// CaPool. +func (c *CertificateAuthorityClient) CreateCertificate(ctx context.Context, req *privatecapb.CreateCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { + return c.internalClient.CreateCertificate(ctx, req, opts...) +} + +// GetCertificate returns a Certificate. +func (c *CertificateAuthorityClient) GetCertificate(ctx context.Context, req *privatecapb.GetCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { + return c.internalClient.GetCertificate(ctx, req, opts...) +} + +// ListCertificates lists Certificates. +func (c *CertificateAuthorityClient) ListCertificates(ctx context.Context, req *privatecapb.ListCertificatesRequest, opts ...gax.CallOption) *CertificateIterator { + return c.internalClient.ListCertificates(ctx, req, opts...) +} + +// RevokeCertificate revoke a Certificate. +func (c *CertificateAuthorityClient) RevokeCertificate(ctx context.Context, req *privatecapb.RevokeCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { + return c.internalClient.RevokeCertificate(ctx, req, opts...) +} + +// UpdateCertificate update a Certificate. Currently, the only field you can update is the +// labels field. +func (c *CertificateAuthorityClient) UpdateCertificate(ctx context.Context, req *privatecapb.UpdateCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { + return c.internalClient.UpdateCertificate(ctx, req, opts...) +} + +// ActivateCertificateAuthority activate a CertificateAuthority that is in state +// AWAITING_USER_ACTIVATION +// and is of type SUBORDINATE. After +// the parent Certificate Authority signs a certificate signing request from +// FetchCertificateAuthorityCsr, this method can complete the activation +// process. +func (c *CertificateAuthorityClient) ActivateCertificateAuthority(ctx context.Context, req *privatecapb.ActivateCertificateAuthorityRequest, opts ...gax.CallOption) (*ActivateCertificateAuthorityOperation, error) { + return c.internalClient.ActivateCertificateAuthority(ctx, req, opts...) +} + +// ActivateCertificateAuthorityOperation returns a new ActivateCertificateAuthorityOperation from a given name. +// The name must be that of a previously created ActivateCertificateAuthorityOperation, possibly from a different process. +func (c *CertificateAuthorityClient) ActivateCertificateAuthorityOperation(name string) *ActivateCertificateAuthorityOperation { + return c.internalClient.ActivateCertificateAuthorityOperation(name) +} + +// CreateCertificateAuthority create a new CertificateAuthority in a given Project and Location. +func (c *CertificateAuthorityClient) CreateCertificateAuthority(ctx context.Context, req *privatecapb.CreateCertificateAuthorityRequest, opts ...gax.CallOption) (*CreateCertificateAuthorityOperation, error) { + return c.internalClient.CreateCertificateAuthority(ctx, req, opts...) +} + +// CreateCertificateAuthorityOperation returns a new CreateCertificateAuthorityOperation from a given name. +// The name must be that of a previously created CreateCertificateAuthorityOperation, possibly from a different process. +func (c *CertificateAuthorityClient) CreateCertificateAuthorityOperation(name string) *CreateCertificateAuthorityOperation { + return c.internalClient.CreateCertificateAuthorityOperation(name) +} + +// DisableCertificateAuthority disable a CertificateAuthority. +func (c *CertificateAuthorityClient) DisableCertificateAuthority(ctx context.Context, req *privatecapb.DisableCertificateAuthorityRequest, opts ...gax.CallOption) (*DisableCertificateAuthorityOperation, error) { + return c.internalClient.DisableCertificateAuthority(ctx, req, opts...) +} + +// DisableCertificateAuthorityOperation returns a new DisableCertificateAuthorityOperation from a given name. +// The name must be that of a previously created DisableCertificateAuthorityOperation, possibly from a different process. +func (c *CertificateAuthorityClient) DisableCertificateAuthorityOperation(name string) *DisableCertificateAuthorityOperation { + return c.internalClient.DisableCertificateAuthorityOperation(name) +} + +// EnableCertificateAuthority enable a CertificateAuthority. +func (c *CertificateAuthorityClient) EnableCertificateAuthority(ctx context.Context, req *privatecapb.EnableCertificateAuthorityRequest, opts ...gax.CallOption) (*EnableCertificateAuthorityOperation, error) { + return c.internalClient.EnableCertificateAuthority(ctx, req, opts...) +} + +// EnableCertificateAuthorityOperation returns a new EnableCertificateAuthorityOperation from a given name. +// The name must be that of a previously created EnableCertificateAuthorityOperation, possibly from a different process. +func (c *CertificateAuthorityClient) EnableCertificateAuthorityOperation(name string) *EnableCertificateAuthorityOperation { + return c.internalClient.EnableCertificateAuthorityOperation(name) +} + +// FetchCertificateAuthorityCsr fetch a certificate signing request (CSR) from a CertificateAuthority +// that is in state +// AWAITING_USER_ACTIVATION +// and is of type SUBORDINATE. The +// CSR must then be signed by the desired parent Certificate Authority, which +// could be another CertificateAuthority resource, or could be an on-prem +// certificate authority. See also ActivateCertificateAuthority. +func (c *CertificateAuthorityClient) FetchCertificateAuthorityCsr(ctx context.Context, req *privatecapb.FetchCertificateAuthorityCsrRequest, opts ...gax.CallOption) (*privatecapb.FetchCertificateAuthorityCsrResponse, error) { + return c.internalClient.FetchCertificateAuthorityCsr(ctx, req, opts...) +} + +// GetCertificateAuthority returns a CertificateAuthority. +func (c *CertificateAuthorityClient) GetCertificateAuthority(ctx context.Context, req *privatecapb.GetCertificateAuthorityRequest, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { + return c.internalClient.GetCertificateAuthority(ctx, req, opts...) +} + +// ListCertificateAuthorities lists CertificateAuthorities. +func (c *CertificateAuthorityClient) ListCertificateAuthorities(ctx context.Context, req *privatecapb.ListCertificateAuthoritiesRequest, opts ...gax.CallOption) *CertificateAuthorityIterator { + return c.internalClient.ListCertificateAuthorities(ctx, req, opts...) +} + +// UndeleteCertificateAuthority undelete a CertificateAuthority that has been deleted. +func (c *CertificateAuthorityClient) UndeleteCertificateAuthority(ctx context.Context, req *privatecapb.UndeleteCertificateAuthorityRequest, opts ...gax.CallOption) (*UndeleteCertificateAuthorityOperation, error) { + return c.internalClient.UndeleteCertificateAuthority(ctx, req, opts...) +} + +// UndeleteCertificateAuthorityOperation returns a new UndeleteCertificateAuthorityOperation from a given name. +// The name must be that of a previously created UndeleteCertificateAuthorityOperation, possibly from a different process. +func (c *CertificateAuthorityClient) UndeleteCertificateAuthorityOperation(name string) *UndeleteCertificateAuthorityOperation { + return c.internalClient.UndeleteCertificateAuthorityOperation(name) +} + +// DeleteCertificateAuthority delete a CertificateAuthority. +func (c *CertificateAuthorityClient) DeleteCertificateAuthority(ctx context.Context, req *privatecapb.DeleteCertificateAuthorityRequest, opts ...gax.CallOption) (*DeleteCertificateAuthorityOperation, error) { + return c.internalClient.DeleteCertificateAuthority(ctx, req, opts...) +} + +// DeleteCertificateAuthorityOperation returns a new DeleteCertificateAuthorityOperation from a given name. +// The name must be that of a previously created DeleteCertificateAuthorityOperation, possibly from a different process. +func (c *CertificateAuthorityClient) DeleteCertificateAuthorityOperation(name string) *DeleteCertificateAuthorityOperation { + return c.internalClient.DeleteCertificateAuthorityOperation(name) +} + +// UpdateCertificateAuthority update a CertificateAuthority. +func (c *CertificateAuthorityClient) UpdateCertificateAuthority(ctx context.Context, req *privatecapb.UpdateCertificateAuthorityRequest, opts ...gax.CallOption) (*UpdateCertificateAuthorityOperation, error) { + return c.internalClient.UpdateCertificateAuthority(ctx, req, opts...) +} + +// UpdateCertificateAuthorityOperation returns a new UpdateCertificateAuthorityOperation from a given name. +// The name must be that of a previously created UpdateCertificateAuthorityOperation, possibly from a different process. +func (c *CertificateAuthorityClient) UpdateCertificateAuthorityOperation(name string) *UpdateCertificateAuthorityOperation { + return c.internalClient.UpdateCertificateAuthorityOperation(name) +} + +// CreateCaPool create a CaPool. +func (c *CertificateAuthorityClient) CreateCaPool(ctx context.Context, req *privatecapb.CreateCaPoolRequest, opts ...gax.CallOption) (*CreateCaPoolOperation, error) { + return c.internalClient.CreateCaPool(ctx, req, opts...) +} + +// CreateCaPoolOperation returns a new CreateCaPoolOperation from a given name. +// The name must be that of a previously created CreateCaPoolOperation, possibly from a different process. +func (c *CertificateAuthorityClient) CreateCaPoolOperation(name string) *CreateCaPoolOperation { + return c.internalClient.CreateCaPoolOperation(name) +} + +// UpdateCaPool update a CaPool. +func (c *CertificateAuthorityClient) UpdateCaPool(ctx context.Context, req *privatecapb.UpdateCaPoolRequest, opts ...gax.CallOption) (*UpdateCaPoolOperation, error) { + return c.internalClient.UpdateCaPool(ctx, req, opts...) +} + +// UpdateCaPoolOperation returns a new UpdateCaPoolOperation from a given name. +// The name must be that of a previously created UpdateCaPoolOperation, possibly from a different process. +func (c *CertificateAuthorityClient) UpdateCaPoolOperation(name string) *UpdateCaPoolOperation { + return c.internalClient.UpdateCaPoolOperation(name) +} + +// GetCaPool returns a CaPool. +func (c *CertificateAuthorityClient) GetCaPool(ctx context.Context, req *privatecapb.GetCaPoolRequest, opts ...gax.CallOption) (*privatecapb.CaPool, error) { + return c.internalClient.GetCaPool(ctx, req, opts...) +} + +// ListCaPools lists CaPools. +func (c *CertificateAuthorityClient) ListCaPools(ctx context.Context, req *privatecapb.ListCaPoolsRequest, opts ...gax.CallOption) *CaPoolIterator { + return c.internalClient.ListCaPools(ctx, req, opts...) +} + +// DeleteCaPool delete a CaPool. +func (c *CertificateAuthorityClient) DeleteCaPool(ctx context.Context, req *privatecapb.DeleteCaPoolRequest, opts ...gax.CallOption) (*DeleteCaPoolOperation, error) { + return c.internalClient.DeleteCaPool(ctx, req, opts...) +} + +// DeleteCaPoolOperation returns a new DeleteCaPoolOperation from a given name. +// The name must be that of a previously created DeleteCaPoolOperation, possibly from a different process. +func (c *CertificateAuthorityClient) DeleteCaPoolOperation(name string) *DeleteCaPoolOperation { + return c.internalClient.DeleteCaPoolOperation(name) +} + +// FetchCaCerts fetchCaCerts returns the current trust anchor for the CaPool. This will +// include CA certificate chains for all ACTIVE CertificateAuthority +// resources in the CaPool. +func (c *CertificateAuthorityClient) FetchCaCerts(ctx context.Context, req *privatecapb.FetchCaCertsRequest, opts ...gax.CallOption) (*privatecapb.FetchCaCertsResponse, error) { + return c.internalClient.FetchCaCerts(ctx, req, opts...) +} + +// GetCertificateRevocationList returns a CertificateRevocationList. +func (c *CertificateAuthorityClient) GetCertificateRevocationList(ctx context.Context, req *privatecapb.GetCertificateRevocationListRequest, opts ...gax.CallOption) (*privatecapb.CertificateRevocationList, error) { + return c.internalClient.GetCertificateRevocationList(ctx, req, opts...) +} + +// ListCertificateRevocationLists lists CertificateRevocationLists. +func (c *CertificateAuthorityClient) ListCertificateRevocationLists(ctx context.Context, req *privatecapb.ListCertificateRevocationListsRequest, opts ...gax.CallOption) *CertificateRevocationListIterator { + return c.internalClient.ListCertificateRevocationLists(ctx, req, opts...) +} + +// UpdateCertificateRevocationList update a CertificateRevocationList. +func (c *CertificateAuthorityClient) UpdateCertificateRevocationList(ctx context.Context, req *privatecapb.UpdateCertificateRevocationListRequest, opts ...gax.CallOption) (*UpdateCertificateRevocationListOperation, error) { + return c.internalClient.UpdateCertificateRevocationList(ctx, req, opts...) +} + +// UpdateCertificateRevocationListOperation returns a new UpdateCertificateRevocationListOperation from a given name. +// The name must be that of a previously created UpdateCertificateRevocationListOperation, possibly from a different process. +func (c *CertificateAuthorityClient) UpdateCertificateRevocationListOperation(name string) *UpdateCertificateRevocationListOperation { + return c.internalClient.UpdateCertificateRevocationListOperation(name) +} + +// CreateCertificateTemplate create a new CertificateTemplate in a given Project and Location. +func (c *CertificateAuthorityClient) CreateCertificateTemplate(ctx context.Context, req *privatecapb.CreateCertificateTemplateRequest, opts ...gax.CallOption) (*CreateCertificateTemplateOperation, error) { + return c.internalClient.CreateCertificateTemplate(ctx, req, opts...) +} + +// CreateCertificateTemplateOperation returns a new CreateCertificateTemplateOperation from a given name. +// The name must be that of a previously created CreateCertificateTemplateOperation, possibly from a different process. +func (c *CertificateAuthorityClient) CreateCertificateTemplateOperation(name string) *CreateCertificateTemplateOperation { + return c.internalClient.CreateCertificateTemplateOperation(name) +} + +// DeleteCertificateTemplate deleteCertificateTemplate deletes a CertificateTemplate. +func (c *CertificateAuthorityClient) DeleteCertificateTemplate(ctx context.Context, req *privatecapb.DeleteCertificateTemplateRequest, opts ...gax.CallOption) (*DeleteCertificateTemplateOperation, error) { + return c.internalClient.DeleteCertificateTemplate(ctx, req, opts...) +} + +// DeleteCertificateTemplateOperation returns a new DeleteCertificateTemplateOperation from a given name. +// The name must be that of a previously created DeleteCertificateTemplateOperation, possibly from a different process. +func (c *CertificateAuthorityClient) DeleteCertificateTemplateOperation(name string) *DeleteCertificateTemplateOperation { + return c.internalClient.DeleteCertificateTemplateOperation(name) +} + +// GetCertificateTemplate returns a CertificateTemplate. +func (c *CertificateAuthorityClient) GetCertificateTemplate(ctx context.Context, req *privatecapb.GetCertificateTemplateRequest, opts ...gax.CallOption) (*privatecapb.CertificateTemplate, error) { + return c.internalClient.GetCertificateTemplate(ctx, req, opts...) +} + +// ListCertificateTemplates lists CertificateTemplates. +func (c *CertificateAuthorityClient) ListCertificateTemplates(ctx context.Context, req *privatecapb.ListCertificateTemplatesRequest, opts ...gax.CallOption) *CertificateTemplateIterator { + return c.internalClient.ListCertificateTemplates(ctx, req, opts...) +} + +// UpdateCertificateTemplate update a CertificateTemplate. +func (c *CertificateAuthorityClient) UpdateCertificateTemplate(ctx context.Context, req *privatecapb.UpdateCertificateTemplateRequest, opts ...gax.CallOption) (*UpdateCertificateTemplateOperation, error) { + return c.internalClient.UpdateCertificateTemplate(ctx, req, opts...) +} + +// UpdateCertificateTemplateOperation returns a new UpdateCertificateTemplateOperation from a given name. +// The name must be that of a previously created UpdateCertificateTemplateOperation, possibly from a different process. +func (c *CertificateAuthorityClient) UpdateCertificateTemplateOperation(name string) *UpdateCertificateTemplateOperation { + return c.internalClient.UpdateCertificateTemplateOperation(name) +} + +// certificateAuthorityGRPCClient is a client for interacting with Certificate Authority API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type certificateAuthorityGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CertificateAuthorityClient + CallOptions **CertificateAuthorityCallOptions + // The gRPC API client. certificateAuthorityClient privatecapb.CertificateAuthorityServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CertificateAuthorityCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCertificateAuthorityClient creates a new certificate authority service client. +// NewCertificateAuthorityClient creates a new certificate authority service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // [Certificate Authority Service][google.cloud.security.privateca.v1.CertificateAuthorityService] manages private // certificate authorities and issued certificates. func NewCertificateAuthorityClient(ctx context.Context, opts ...option.ClientOption) (*CertificateAuthorityClient, error) { - clientOpts := defaultCertificateAuthorityClientOptions() - + clientOpts := defaultCertificateAuthorityGRPCClientOptions() if newCertificateAuthorityClientHook != nil { hookOpts, err := newCertificateAuthorityClientHook(ctx, clientHookParams{}) if err != nil { @@ -516,16 +850,19 @@ func NewCertificateAuthorityClient(ctx context.Context, opts ...option.ClientOpt if err != nil { return nil, err } - c := &CertificateAuthorityClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultCertificateAuthorityCallOptions(), + client := CertificateAuthorityClient{CallOptions: defaultCertificateAuthorityCallOptions()} + c := &certificateAuthorityGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, certificateAuthorityClient: privatecapb.NewCertificateAuthorityServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -535,34 +872,33 @@ func NewCertificateAuthorityClient(ctx context.Context, opts ...option.ClientOpt // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CertificateAuthorityClient) Connection() *grpc.ClientConn { +func (c *certificateAuthorityGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CertificateAuthorityClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CertificateAuthorityClient) setGoogleClientInfo(keyval ...string) { +func (c *certificateAuthorityGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateCertificate create a new Certificate in a given Project, Location from a particular -// CaPool. -func (c *CertificateAuthorityClient) CreateCertificate(ctx context.Context, req *privatecapb.CreateCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *certificateAuthorityGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *certificateAuthorityGRPCClient) CreateCertificate(ctx context.Context, req *privatecapb.CreateCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -570,7 +906,7 @@ func (c *CertificateAuthorityClient) CreateCertificate(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCertificate[0:len(c.CallOptions.CreateCertificate):len(c.CallOptions.CreateCertificate)], opts...) + opts = append((*c.CallOptions).CreateCertificate[0:len((*c.CallOptions).CreateCertificate):len((*c.CallOptions).CreateCertificate)], opts...) var resp *privatecapb.Certificate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -583,8 +919,7 @@ func (c *CertificateAuthorityClient) CreateCertificate(ctx context.Context, req return resp, nil } -// GetCertificate returns a Certificate. -func (c *CertificateAuthorityClient) GetCertificate(ctx context.Context, req *privatecapb.GetCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { +func (c *certificateAuthorityGRPCClient) GetCertificate(ctx context.Context, req *privatecapb.GetCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -592,7 +927,7 @@ func (c *CertificateAuthorityClient) GetCertificate(ctx context.Context, req *pr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCertificate[0:len(c.CallOptions.GetCertificate):len(c.CallOptions.GetCertificate)], opts...) + opts = append((*c.CallOptions).GetCertificate[0:len((*c.CallOptions).GetCertificate):len((*c.CallOptions).GetCertificate)], opts...) var resp *privatecapb.Certificate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -605,11 +940,10 @@ func (c *CertificateAuthorityClient) GetCertificate(ctx context.Context, req *pr return resp, nil } -// ListCertificates lists Certificates. -func (c *CertificateAuthorityClient) ListCertificates(ctx context.Context, req *privatecapb.ListCertificatesRequest, opts ...gax.CallOption) *CertificateIterator { +func (c *certificateAuthorityGRPCClient) ListCertificates(ctx context.Context, req *privatecapb.ListCertificatesRequest, opts ...gax.CallOption) *CertificateIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCertificates[0:len(c.CallOptions.ListCertificates):len(c.CallOptions.ListCertificates)], opts...) + opts = append((*c.CallOptions).ListCertificates[0:len((*c.CallOptions).ListCertificates):len((*c.CallOptions).ListCertificates)], opts...) it := &CertificateIterator{} req = proto.Clone(req).(*privatecapb.ListCertificatesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*privatecapb.Certificate, string, error) { @@ -646,8 +980,7 @@ func (c *CertificateAuthorityClient) ListCertificates(ctx context.Context, req * return it } -// RevokeCertificate revoke a Certificate. -func (c *CertificateAuthorityClient) RevokeCertificate(ctx context.Context, req *privatecapb.RevokeCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { +func (c *certificateAuthorityGRPCClient) RevokeCertificate(ctx context.Context, req *privatecapb.RevokeCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -655,7 +988,7 @@ func (c *CertificateAuthorityClient) RevokeCertificate(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RevokeCertificate[0:len(c.CallOptions.RevokeCertificate):len(c.CallOptions.RevokeCertificate)], opts...) + opts = append((*c.CallOptions).RevokeCertificate[0:len((*c.CallOptions).RevokeCertificate):len((*c.CallOptions).RevokeCertificate)], opts...) var resp *privatecapb.Certificate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -668,9 +1001,7 @@ func (c *CertificateAuthorityClient) RevokeCertificate(ctx context.Context, req return resp, nil } -// UpdateCertificate update a Certificate. Currently, the only field you can update is the -// labels field. -func (c *CertificateAuthorityClient) UpdateCertificate(ctx context.Context, req *privatecapb.UpdateCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { +func (c *certificateAuthorityGRPCClient) UpdateCertificate(ctx context.Context, req *privatecapb.UpdateCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -678,7 +1009,7 @@ func (c *CertificateAuthorityClient) UpdateCertificate(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "certificate.name", url.QueryEscape(req.GetCertificate().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCertificate[0:len(c.CallOptions.UpdateCertificate):len(c.CallOptions.UpdateCertificate)], opts...) + opts = append((*c.CallOptions).UpdateCertificate[0:len((*c.CallOptions).UpdateCertificate):len((*c.CallOptions).UpdateCertificate)], opts...) var resp *privatecapb.Certificate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -691,13 +1022,7 @@ func (c *CertificateAuthorityClient) UpdateCertificate(ctx context.Context, req return resp, nil } -// ActivateCertificateAuthority activate a CertificateAuthority that is in state -// AWAITING_USER_ACTIVATION -// and is of type SUBORDINATE. After -// the parent Certificate Authority signs a certificate signing request from -// FetchCertificateAuthorityCsr, this method can complete the activation -// process. -func (c *CertificateAuthorityClient) ActivateCertificateAuthority(ctx context.Context, req *privatecapb.ActivateCertificateAuthorityRequest, opts ...gax.CallOption) (*ActivateCertificateAuthorityOperation, error) { +func (c *certificateAuthorityGRPCClient) ActivateCertificateAuthority(ctx context.Context, req *privatecapb.ActivateCertificateAuthorityRequest, opts ...gax.CallOption) (*ActivateCertificateAuthorityOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -705,7 +1030,7 @@ func (c *CertificateAuthorityClient) ActivateCertificateAuthority(ctx context.Co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ActivateCertificateAuthority[0:len(c.CallOptions.ActivateCertificateAuthority):len(c.CallOptions.ActivateCertificateAuthority)], opts...) + opts = append((*c.CallOptions).ActivateCertificateAuthority[0:len((*c.CallOptions).ActivateCertificateAuthority):len((*c.CallOptions).ActivateCertificateAuthority)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -716,12 +1041,11 @@ func (c *CertificateAuthorityClient) ActivateCertificateAuthority(ctx context.Co return nil, err } return &ActivateCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// CreateCertificateAuthority create a new CertificateAuthority in a given Project and Location. -func (c *CertificateAuthorityClient) CreateCertificateAuthority(ctx context.Context, req *privatecapb.CreateCertificateAuthorityRequest, opts ...gax.CallOption) (*CreateCertificateAuthorityOperation, error) { +func (c *certificateAuthorityGRPCClient) CreateCertificateAuthority(ctx context.Context, req *privatecapb.CreateCertificateAuthorityRequest, opts ...gax.CallOption) (*CreateCertificateAuthorityOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -729,7 +1053,7 @@ func (c *CertificateAuthorityClient) CreateCertificateAuthority(ctx context.Cont } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCertificateAuthority[0:len(c.CallOptions.CreateCertificateAuthority):len(c.CallOptions.CreateCertificateAuthority)], opts...) + opts = append((*c.CallOptions).CreateCertificateAuthority[0:len((*c.CallOptions).CreateCertificateAuthority):len((*c.CallOptions).CreateCertificateAuthority)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -740,12 +1064,11 @@ func (c *CertificateAuthorityClient) CreateCertificateAuthority(ctx context.Cont return nil, err } return &CreateCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DisableCertificateAuthority disable a CertificateAuthority. -func (c *CertificateAuthorityClient) DisableCertificateAuthority(ctx context.Context, req *privatecapb.DisableCertificateAuthorityRequest, opts ...gax.CallOption) (*DisableCertificateAuthorityOperation, error) { +func (c *certificateAuthorityGRPCClient) DisableCertificateAuthority(ctx context.Context, req *privatecapb.DisableCertificateAuthorityRequest, opts ...gax.CallOption) (*DisableCertificateAuthorityOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -753,7 +1076,7 @@ func (c *CertificateAuthorityClient) DisableCertificateAuthority(ctx context.Con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DisableCertificateAuthority[0:len(c.CallOptions.DisableCertificateAuthority):len(c.CallOptions.DisableCertificateAuthority)], opts...) + opts = append((*c.CallOptions).DisableCertificateAuthority[0:len((*c.CallOptions).DisableCertificateAuthority):len((*c.CallOptions).DisableCertificateAuthority)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -764,12 +1087,11 @@ func (c *CertificateAuthorityClient) DisableCertificateAuthority(ctx context.Con return nil, err } return &DisableCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// EnableCertificateAuthority enable a CertificateAuthority. -func (c *CertificateAuthorityClient) EnableCertificateAuthority(ctx context.Context, req *privatecapb.EnableCertificateAuthorityRequest, opts ...gax.CallOption) (*EnableCertificateAuthorityOperation, error) { +func (c *certificateAuthorityGRPCClient) EnableCertificateAuthority(ctx context.Context, req *privatecapb.EnableCertificateAuthorityRequest, opts ...gax.CallOption) (*EnableCertificateAuthorityOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -777,7 +1099,7 @@ func (c *CertificateAuthorityClient) EnableCertificateAuthority(ctx context.Cont } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.EnableCertificateAuthority[0:len(c.CallOptions.EnableCertificateAuthority):len(c.CallOptions.EnableCertificateAuthority)], opts...) + opts = append((*c.CallOptions).EnableCertificateAuthority[0:len((*c.CallOptions).EnableCertificateAuthority):len((*c.CallOptions).EnableCertificateAuthority)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -788,18 +1110,11 @@ func (c *CertificateAuthorityClient) EnableCertificateAuthority(ctx context.Cont return nil, err } return &EnableCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// FetchCertificateAuthorityCsr fetch a certificate signing request (CSR) from a CertificateAuthority -// that is in state -// AWAITING_USER_ACTIVATION -// and is of type SUBORDINATE. The -// CSR must then be signed by the desired parent Certificate Authority, which -// could be another CertificateAuthority resource, or could be an on-prem -// certificate authority. See also ActivateCertificateAuthority. -func (c *CertificateAuthorityClient) FetchCertificateAuthorityCsr(ctx context.Context, req *privatecapb.FetchCertificateAuthorityCsrRequest, opts ...gax.CallOption) (*privatecapb.FetchCertificateAuthorityCsrResponse, error) { +func (c *certificateAuthorityGRPCClient) FetchCertificateAuthorityCsr(ctx context.Context, req *privatecapb.FetchCertificateAuthorityCsrRequest, opts ...gax.CallOption) (*privatecapb.FetchCertificateAuthorityCsrResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -807,7 +1122,7 @@ func (c *CertificateAuthorityClient) FetchCertificateAuthorityCsr(ctx context.Co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.FetchCertificateAuthorityCsr[0:len(c.CallOptions.FetchCertificateAuthorityCsr):len(c.CallOptions.FetchCertificateAuthorityCsr)], opts...) + opts = append((*c.CallOptions).FetchCertificateAuthorityCsr[0:len((*c.CallOptions).FetchCertificateAuthorityCsr):len((*c.CallOptions).FetchCertificateAuthorityCsr)], opts...) var resp *privatecapb.FetchCertificateAuthorityCsrResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -820,8 +1135,7 @@ func (c *CertificateAuthorityClient) FetchCertificateAuthorityCsr(ctx context.Co return resp, nil } -// GetCertificateAuthority returns a CertificateAuthority. -func (c *CertificateAuthorityClient) GetCertificateAuthority(ctx context.Context, req *privatecapb.GetCertificateAuthorityRequest, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { +func (c *certificateAuthorityGRPCClient) GetCertificateAuthority(ctx context.Context, req *privatecapb.GetCertificateAuthorityRequest, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -829,7 +1143,7 @@ func (c *CertificateAuthorityClient) GetCertificateAuthority(ctx context.Context } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCertificateAuthority[0:len(c.CallOptions.GetCertificateAuthority):len(c.CallOptions.GetCertificateAuthority)], opts...) + opts = append((*c.CallOptions).GetCertificateAuthority[0:len((*c.CallOptions).GetCertificateAuthority):len((*c.CallOptions).GetCertificateAuthority)], opts...) var resp *privatecapb.CertificateAuthority err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -842,11 +1156,10 @@ func (c *CertificateAuthorityClient) GetCertificateAuthority(ctx context.Context return resp, nil } -// ListCertificateAuthorities lists CertificateAuthorities. -func (c *CertificateAuthorityClient) ListCertificateAuthorities(ctx context.Context, req *privatecapb.ListCertificateAuthoritiesRequest, opts ...gax.CallOption) *CertificateAuthorityIterator { +func (c *certificateAuthorityGRPCClient) ListCertificateAuthorities(ctx context.Context, req *privatecapb.ListCertificateAuthoritiesRequest, opts ...gax.CallOption) *CertificateAuthorityIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCertificateAuthorities[0:len(c.CallOptions.ListCertificateAuthorities):len(c.CallOptions.ListCertificateAuthorities)], opts...) + opts = append((*c.CallOptions).ListCertificateAuthorities[0:len((*c.CallOptions).ListCertificateAuthorities):len((*c.CallOptions).ListCertificateAuthorities)], opts...) it := &CertificateAuthorityIterator{} req = proto.Clone(req).(*privatecapb.ListCertificateAuthoritiesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*privatecapb.CertificateAuthority, string, error) { @@ -883,8 +1196,7 @@ func (c *CertificateAuthorityClient) ListCertificateAuthorities(ctx context.Cont return it } -// UndeleteCertificateAuthority undelete a CertificateAuthority that has been deleted. -func (c *CertificateAuthorityClient) UndeleteCertificateAuthority(ctx context.Context, req *privatecapb.UndeleteCertificateAuthorityRequest, opts ...gax.CallOption) (*UndeleteCertificateAuthorityOperation, error) { +func (c *certificateAuthorityGRPCClient) UndeleteCertificateAuthority(ctx context.Context, req *privatecapb.UndeleteCertificateAuthorityRequest, opts ...gax.CallOption) (*UndeleteCertificateAuthorityOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -892,7 +1204,7 @@ func (c *CertificateAuthorityClient) UndeleteCertificateAuthority(ctx context.Co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UndeleteCertificateAuthority[0:len(c.CallOptions.UndeleteCertificateAuthority):len(c.CallOptions.UndeleteCertificateAuthority)], opts...) + opts = append((*c.CallOptions).UndeleteCertificateAuthority[0:len((*c.CallOptions).UndeleteCertificateAuthority):len((*c.CallOptions).UndeleteCertificateAuthority)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -903,12 +1215,11 @@ func (c *CertificateAuthorityClient) UndeleteCertificateAuthority(ctx context.Co return nil, err } return &UndeleteCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteCertificateAuthority delete a CertificateAuthority. -func (c *CertificateAuthorityClient) DeleteCertificateAuthority(ctx context.Context, req *privatecapb.DeleteCertificateAuthorityRequest, opts ...gax.CallOption) (*DeleteCertificateAuthorityOperation, error) { +func (c *certificateAuthorityGRPCClient) DeleteCertificateAuthority(ctx context.Context, req *privatecapb.DeleteCertificateAuthorityRequest, opts ...gax.CallOption) (*DeleteCertificateAuthorityOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -916,7 +1227,7 @@ func (c *CertificateAuthorityClient) DeleteCertificateAuthority(ctx context.Cont } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteCertificateAuthority[0:len(c.CallOptions.DeleteCertificateAuthority):len(c.CallOptions.DeleteCertificateAuthority)], opts...) + opts = append((*c.CallOptions).DeleteCertificateAuthority[0:len((*c.CallOptions).DeleteCertificateAuthority):len((*c.CallOptions).DeleteCertificateAuthority)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -927,12 +1238,11 @@ func (c *CertificateAuthorityClient) DeleteCertificateAuthority(ctx context.Cont return nil, err } return &DeleteCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateCertificateAuthority update a CertificateAuthority. -func (c *CertificateAuthorityClient) UpdateCertificateAuthority(ctx context.Context, req *privatecapb.UpdateCertificateAuthorityRequest, opts ...gax.CallOption) (*UpdateCertificateAuthorityOperation, error) { +func (c *certificateAuthorityGRPCClient) UpdateCertificateAuthority(ctx context.Context, req *privatecapb.UpdateCertificateAuthorityRequest, opts ...gax.CallOption) (*UpdateCertificateAuthorityOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -940,7 +1250,7 @@ func (c *CertificateAuthorityClient) UpdateCertificateAuthority(ctx context.Cont } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "certificate_authority.name", url.QueryEscape(req.GetCertificateAuthority().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCertificateAuthority[0:len(c.CallOptions.UpdateCertificateAuthority):len(c.CallOptions.UpdateCertificateAuthority)], opts...) + opts = append((*c.CallOptions).UpdateCertificateAuthority[0:len((*c.CallOptions).UpdateCertificateAuthority):len((*c.CallOptions).UpdateCertificateAuthority)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -951,12 +1261,11 @@ func (c *CertificateAuthorityClient) UpdateCertificateAuthority(ctx context.Cont return nil, err } return &UpdateCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// CreateCaPool create a CaPool. -func (c *CertificateAuthorityClient) CreateCaPool(ctx context.Context, req *privatecapb.CreateCaPoolRequest, opts ...gax.CallOption) (*CreateCaPoolOperation, error) { +func (c *certificateAuthorityGRPCClient) CreateCaPool(ctx context.Context, req *privatecapb.CreateCaPoolRequest, opts ...gax.CallOption) (*CreateCaPoolOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -964,7 +1273,7 @@ func (c *CertificateAuthorityClient) CreateCaPool(ctx context.Context, req *priv } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCaPool[0:len(c.CallOptions.CreateCaPool):len(c.CallOptions.CreateCaPool)], opts...) + opts = append((*c.CallOptions).CreateCaPool[0:len((*c.CallOptions).CreateCaPool):len((*c.CallOptions).CreateCaPool)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -975,12 +1284,11 @@ func (c *CertificateAuthorityClient) CreateCaPool(ctx context.Context, req *priv return nil, err } return &CreateCaPoolOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateCaPool update a CaPool. -func (c *CertificateAuthorityClient) UpdateCaPool(ctx context.Context, req *privatecapb.UpdateCaPoolRequest, opts ...gax.CallOption) (*UpdateCaPoolOperation, error) { +func (c *certificateAuthorityGRPCClient) UpdateCaPool(ctx context.Context, req *privatecapb.UpdateCaPoolRequest, opts ...gax.CallOption) (*UpdateCaPoolOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -988,7 +1296,7 @@ func (c *CertificateAuthorityClient) UpdateCaPool(ctx context.Context, req *priv } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "ca_pool.name", url.QueryEscape(req.GetCaPool().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCaPool[0:len(c.CallOptions.UpdateCaPool):len(c.CallOptions.UpdateCaPool)], opts...) + opts = append((*c.CallOptions).UpdateCaPool[0:len((*c.CallOptions).UpdateCaPool):len((*c.CallOptions).UpdateCaPool)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -999,12 +1307,11 @@ func (c *CertificateAuthorityClient) UpdateCaPool(ctx context.Context, req *priv return nil, err } return &UpdateCaPoolOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetCaPool returns a CaPool. -func (c *CertificateAuthorityClient) GetCaPool(ctx context.Context, req *privatecapb.GetCaPoolRequest, opts ...gax.CallOption) (*privatecapb.CaPool, error) { +func (c *certificateAuthorityGRPCClient) GetCaPool(ctx context.Context, req *privatecapb.GetCaPoolRequest, opts ...gax.CallOption) (*privatecapb.CaPool, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1012,7 +1319,7 @@ func (c *CertificateAuthorityClient) GetCaPool(ctx context.Context, req *private } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCaPool[0:len(c.CallOptions.GetCaPool):len(c.CallOptions.GetCaPool)], opts...) + opts = append((*c.CallOptions).GetCaPool[0:len((*c.CallOptions).GetCaPool):len((*c.CallOptions).GetCaPool)], opts...) var resp *privatecapb.CaPool err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1025,11 +1332,10 @@ func (c *CertificateAuthorityClient) GetCaPool(ctx context.Context, req *private return resp, nil } -// ListCaPools lists CaPools. -func (c *CertificateAuthorityClient) ListCaPools(ctx context.Context, req *privatecapb.ListCaPoolsRequest, opts ...gax.CallOption) *CaPoolIterator { +func (c *certificateAuthorityGRPCClient) ListCaPools(ctx context.Context, req *privatecapb.ListCaPoolsRequest, opts ...gax.CallOption) *CaPoolIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCaPools[0:len(c.CallOptions.ListCaPools):len(c.CallOptions.ListCaPools)], opts...) + opts = append((*c.CallOptions).ListCaPools[0:len((*c.CallOptions).ListCaPools):len((*c.CallOptions).ListCaPools)], opts...) it := &CaPoolIterator{} req = proto.Clone(req).(*privatecapb.ListCaPoolsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*privatecapb.CaPool, string, error) { @@ -1066,8 +1372,7 @@ func (c *CertificateAuthorityClient) ListCaPools(ctx context.Context, req *priva return it } -// DeleteCaPool delete a CaPool. -func (c *CertificateAuthorityClient) DeleteCaPool(ctx context.Context, req *privatecapb.DeleteCaPoolRequest, opts ...gax.CallOption) (*DeleteCaPoolOperation, error) { +func (c *certificateAuthorityGRPCClient) DeleteCaPool(ctx context.Context, req *privatecapb.DeleteCaPoolRequest, opts ...gax.CallOption) (*DeleteCaPoolOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1075,7 +1380,7 @@ func (c *CertificateAuthorityClient) DeleteCaPool(ctx context.Context, req *priv } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteCaPool[0:len(c.CallOptions.DeleteCaPool):len(c.CallOptions.DeleteCaPool)], opts...) + opts = append((*c.CallOptions).DeleteCaPool[0:len((*c.CallOptions).DeleteCaPool):len((*c.CallOptions).DeleteCaPool)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1086,14 +1391,11 @@ func (c *CertificateAuthorityClient) DeleteCaPool(ctx context.Context, req *priv return nil, err } return &DeleteCaPoolOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// FetchCaCerts fetchCaCerts returns the current trust anchor for the CaPool. This will -// include CA certificate chains for all ACTIVE CertificateAuthority -// resources in the CaPool. -func (c *CertificateAuthorityClient) FetchCaCerts(ctx context.Context, req *privatecapb.FetchCaCertsRequest, opts ...gax.CallOption) (*privatecapb.FetchCaCertsResponse, error) { +func (c *certificateAuthorityGRPCClient) FetchCaCerts(ctx context.Context, req *privatecapb.FetchCaCertsRequest, opts ...gax.CallOption) (*privatecapb.FetchCaCertsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1101,7 +1403,7 @@ func (c *CertificateAuthorityClient) FetchCaCerts(ctx context.Context, req *priv } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "ca_pool", url.QueryEscape(req.GetCaPool()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.FetchCaCerts[0:len(c.CallOptions.FetchCaCerts):len(c.CallOptions.FetchCaCerts)], opts...) + opts = append((*c.CallOptions).FetchCaCerts[0:len((*c.CallOptions).FetchCaCerts):len((*c.CallOptions).FetchCaCerts)], opts...) var resp *privatecapb.FetchCaCertsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1114,8 +1416,7 @@ func (c *CertificateAuthorityClient) FetchCaCerts(ctx context.Context, req *priv return resp, nil } -// GetCertificateRevocationList returns a CertificateRevocationList. -func (c *CertificateAuthorityClient) GetCertificateRevocationList(ctx context.Context, req *privatecapb.GetCertificateRevocationListRequest, opts ...gax.CallOption) (*privatecapb.CertificateRevocationList, error) { +func (c *certificateAuthorityGRPCClient) GetCertificateRevocationList(ctx context.Context, req *privatecapb.GetCertificateRevocationListRequest, opts ...gax.CallOption) (*privatecapb.CertificateRevocationList, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1123,7 +1424,7 @@ func (c *CertificateAuthorityClient) GetCertificateRevocationList(ctx context.Co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCertificateRevocationList[0:len(c.CallOptions.GetCertificateRevocationList):len(c.CallOptions.GetCertificateRevocationList)], opts...) + opts = append((*c.CallOptions).GetCertificateRevocationList[0:len((*c.CallOptions).GetCertificateRevocationList):len((*c.CallOptions).GetCertificateRevocationList)], opts...) var resp *privatecapb.CertificateRevocationList err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1136,11 +1437,10 @@ func (c *CertificateAuthorityClient) GetCertificateRevocationList(ctx context.Co return resp, nil } -// ListCertificateRevocationLists lists CertificateRevocationLists. -func (c *CertificateAuthorityClient) ListCertificateRevocationLists(ctx context.Context, req *privatecapb.ListCertificateRevocationListsRequest, opts ...gax.CallOption) *CertificateRevocationListIterator { +func (c *certificateAuthorityGRPCClient) ListCertificateRevocationLists(ctx context.Context, req *privatecapb.ListCertificateRevocationListsRequest, opts ...gax.CallOption) *CertificateRevocationListIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCertificateRevocationLists[0:len(c.CallOptions.ListCertificateRevocationLists):len(c.CallOptions.ListCertificateRevocationLists)], opts...) + opts = append((*c.CallOptions).ListCertificateRevocationLists[0:len((*c.CallOptions).ListCertificateRevocationLists):len((*c.CallOptions).ListCertificateRevocationLists)], opts...) it := &CertificateRevocationListIterator{} req = proto.Clone(req).(*privatecapb.ListCertificateRevocationListsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*privatecapb.CertificateRevocationList, string, error) { @@ -1177,8 +1477,7 @@ func (c *CertificateAuthorityClient) ListCertificateRevocationLists(ctx context. return it } -// UpdateCertificateRevocationList update a CertificateRevocationList. -func (c *CertificateAuthorityClient) UpdateCertificateRevocationList(ctx context.Context, req *privatecapb.UpdateCertificateRevocationListRequest, opts ...gax.CallOption) (*UpdateCertificateRevocationListOperation, error) { +func (c *certificateAuthorityGRPCClient) UpdateCertificateRevocationList(ctx context.Context, req *privatecapb.UpdateCertificateRevocationListRequest, opts ...gax.CallOption) (*UpdateCertificateRevocationListOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1186,7 +1485,7 @@ func (c *CertificateAuthorityClient) UpdateCertificateRevocationList(ctx context } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "certificate_revocation_list.name", url.QueryEscape(req.GetCertificateRevocationList().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCertificateRevocationList[0:len(c.CallOptions.UpdateCertificateRevocationList):len(c.CallOptions.UpdateCertificateRevocationList)], opts...) + opts = append((*c.CallOptions).UpdateCertificateRevocationList[0:len((*c.CallOptions).UpdateCertificateRevocationList):len((*c.CallOptions).UpdateCertificateRevocationList)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1197,12 +1496,11 @@ func (c *CertificateAuthorityClient) UpdateCertificateRevocationList(ctx context return nil, err } return &UpdateCertificateRevocationListOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// CreateCertificateTemplate create a new CertificateTemplate in a given Project and Location. -func (c *CertificateAuthorityClient) CreateCertificateTemplate(ctx context.Context, req *privatecapb.CreateCertificateTemplateRequest, opts ...gax.CallOption) (*CreateCertificateTemplateOperation, error) { +func (c *certificateAuthorityGRPCClient) CreateCertificateTemplate(ctx context.Context, req *privatecapb.CreateCertificateTemplateRequest, opts ...gax.CallOption) (*CreateCertificateTemplateOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1210,7 +1508,7 @@ func (c *CertificateAuthorityClient) CreateCertificateTemplate(ctx context.Conte } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCertificateTemplate[0:len(c.CallOptions.CreateCertificateTemplate):len(c.CallOptions.CreateCertificateTemplate)], opts...) + opts = append((*c.CallOptions).CreateCertificateTemplate[0:len((*c.CallOptions).CreateCertificateTemplate):len((*c.CallOptions).CreateCertificateTemplate)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1221,12 +1519,11 @@ func (c *CertificateAuthorityClient) CreateCertificateTemplate(ctx context.Conte return nil, err } return &CreateCertificateTemplateOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteCertificateTemplate deleteCertificateTemplate deletes a CertificateTemplate. -func (c *CertificateAuthorityClient) DeleteCertificateTemplate(ctx context.Context, req *privatecapb.DeleteCertificateTemplateRequest, opts ...gax.CallOption) (*DeleteCertificateTemplateOperation, error) { +func (c *certificateAuthorityGRPCClient) DeleteCertificateTemplate(ctx context.Context, req *privatecapb.DeleteCertificateTemplateRequest, opts ...gax.CallOption) (*DeleteCertificateTemplateOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1234,7 +1531,7 @@ func (c *CertificateAuthorityClient) DeleteCertificateTemplate(ctx context.Conte } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteCertificateTemplate[0:len(c.CallOptions.DeleteCertificateTemplate):len(c.CallOptions.DeleteCertificateTemplate)], opts...) + opts = append((*c.CallOptions).DeleteCertificateTemplate[0:len((*c.CallOptions).DeleteCertificateTemplate):len((*c.CallOptions).DeleteCertificateTemplate)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1245,12 +1542,11 @@ func (c *CertificateAuthorityClient) DeleteCertificateTemplate(ctx context.Conte return nil, err } return &DeleteCertificateTemplateOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetCertificateTemplate returns a CertificateTemplate. -func (c *CertificateAuthorityClient) GetCertificateTemplate(ctx context.Context, req *privatecapb.GetCertificateTemplateRequest, opts ...gax.CallOption) (*privatecapb.CertificateTemplate, error) { +func (c *certificateAuthorityGRPCClient) GetCertificateTemplate(ctx context.Context, req *privatecapb.GetCertificateTemplateRequest, opts ...gax.CallOption) (*privatecapb.CertificateTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1258,7 +1554,7 @@ func (c *CertificateAuthorityClient) GetCertificateTemplate(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCertificateTemplate[0:len(c.CallOptions.GetCertificateTemplate):len(c.CallOptions.GetCertificateTemplate)], opts...) + opts = append((*c.CallOptions).GetCertificateTemplate[0:len((*c.CallOptions).GetCertificateTemplate):len((*c.CallOptions).GetCertificateTemplate)], opts...) var resp *privatecapb.CertificateTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1271,11 +1567,10 @@ func (c *CertificateAuthorityClient) GetCertificateTemplate(ctx context.Context, return resp, nil } -// ListCertificateTemplates lists CertificateTemplates. -func (c *CertificateAuthorityClient) ListCertificateTemplates(ctx context.Context, req *privatecapb.ListCertificateTemplatesRequest, opts ...gax.CallOption) *CertificateTemplateIterator { +func (c *certificateAuthorityGRPCClient) ListCertificateTemplates(ctx context.Context, req *privatecapb.ListCertificateTemplatesRequest, opts ...gax.CallOption) *CertificateTemplateIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCertificateTemplates[0:len(c.CallOptions.ListCertificateTemplates):len(c.CallOptions.ListCertificateTemplates)], opts...) + opts = append((*c.CallOptions).ListCertificateTemplates[0:len((*c.CallOptions).ListCertificateTemplates):len((*c.CallOptions).ListCertificateTemplates)], opts...) it := &CertificateTemplateIterator{} req = proto.Clone(req).(*privatecapb.ListCertificateTemplatesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*privatecapb.CertificateTemplate, string, error) { @@ -1312,8 +1607,7 @@ func (c *CertificateAuthorityClient) ListCertificateTemplates(ctx context.Contex return it } -// UpdateCertificateTemplate update a CertificateTemplate. -func (c *CertificateAuthorityClient) UpdateCertificateTemplate(ctx context.Context, req *privatecapb.UpdateCertificateTemplateRequest, opts ...gax.CallOption) (*UpdateCertificateTemplateOperation, error) { +func (c *certificateAuthorityGRPCClient) UpdateCertificateTemplate(ctx context.Context, req *privatecapb.UpdateCertificateTemplateRequest, opts ...gax.CallOption) (*UpdateCertificateTemplateOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -1321,7 +1615,7 @@ func (c *CertificateAuthorityClient) UpdateCertificateTemplate(ctx context.Conte } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "certificate_template.name", url.QueryEscape(req.GetCertificateTemplate().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCertificateTemplate[0:len(c.CallOptions.UpdateCertificateTemplate):len(c.CallOptions.UpdateCertificateTemplate)], opts...) + opts = append((*c.CallOptions).UpdateCertificateTemplate[0:len((*c.CallOptions).UpdateCertificateTemplate):len((*c.CallOptions).UpdateCertificateTemplate)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1332,7 +1626,7 @@ func (c *CertificateAuthorityClient) UpdateCertificateTemplate(ctx context.Conte return nil, err } return &UpdateCertificateTemplateOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -1343,9 +1637,9 @@ type ActivateCertificateAuthorityOperation struct { // ActivateCertificateAuthorityOperation returns a new ActivateCertificateAuthorityOperation from a given name. // The name must be that of a previously created ActivateCertificateAuthorityOperation, possibly from a different process. -func (c *CertificateAuthorityClient) ActivateCertificateAuthorityOperation(name string) *ActivateCertificateAuthorityOperation { +func (c *certificateAuthorityGRPCClient) ActivateCertificateAuthorityOperation(name string) *ActivateCertificateAuthorityOperation { return &ActivateCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1412,9 +1706,9 @@ type CreateCaPoolOperation struct { // CreateCaPoolOperation returns a new CreateCaPoolOperation from a given name. // The name must be that of a previously created CreateCaPoolOperation, possibly from a different process. -func (c *CertificateAuthorityClient) CreateCaPoolOperation(name string) *CreateCaPoolOperation { +func (c *certificateAuthorityGRPCClient) CreateCaPoolOperation(name string) *CreateCaPoolOperation { return &CreateCaPoolOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1481,9 +1775,9 @@ type CreateCertificateAuthorityOperation struct { // CreateCertificateAuthorityOperation returns a new CreateCertificateAuthorityOperation from a given name. // The name must be that of a previously created CreateCertificateAuthorityOperation, possibly from a different process. -func (c *CertificateAuthorityClient) CreateCertificateAuthorityOperation(name string) *CreateCertificateAuthorityOperation { +func (c *certificateAuthorityGRPCClient) CreateCertificateAuthorityOperation(name string) *CreateCertificateAuthorityOperation { return &CreateCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1550,9 +1844,9 @@ type CreateCertificateTemplateOperation struct { // CreateCertificateTemplateOperation returns a new CreateCertificateTemplateOperation from a given name. // The name must be that of a previously created CreateCertificateTemplateOperation, possibly from a different process. -func (c *CertificateAuthorityClient) CreateCertificateTemplateOperation(name string) *CreateCertificateTemplateOperation { +func (c *certificateAuthorityGRPCClient) CreateCertificateTemplateOperation(name string) *CreateCertificateTemplateOperation { return &CreateCertificateTemplateOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1619,9 +1913,9 @@ type DeleteCaPoolOperation struct { // DeleteCaPoolOperation returns a new DeleteCaPoolOperation from a given name. // The name must be that of a previously created DeleteCaPoolOperation, possibly from a different process. -func (c *CertificateAuthorityClient) DeleteCaPoolOperation(name string) *DeleteCaPoolOperation { +func (c *certificateAuthorityGRPCClient) DeleteCaPoolOperation(name string) *DeleteCaPoolOperation { return &DeleteCaPoolOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1688,9 +1982,9 @@ type DeleteCertificateAuthorityOperation struct { // DeleteCertificateAuthorityOperation returns a new DeleteCertificateAuthorityOperation from a given name. // The name must be that of a previously created DeleteCertificateAuthorityOperation, possibly from a different process. -func (c *CertificateAuthorityClient) DeleteCertificateAuthorityOperation(name string) *DeleteCertificateAuthorityOperation { +func (c *certificateAuthorityGRPCClient) DeleteCertificateAuthorityOperation(name string) *DeleteCertificateAuthorityOperation { return &DeleteCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1757,9 +2051,9 @@ type DeleteCertificateTemplateOperation struct { // DeleteCertificateTemplateOperation returns a new DeleteCertificateTemplateOperation from a given name. // The name must be that of a previously created DeleteCertificateTemplateOperation, possibly from a different process. -func (c *CertificateAuthorityClient) DeleteCertificateTemplateOperation(name string) *DeleteCertificateTemplateOperation { +func (c *certificateAuthorityGRPCClient) DeleteCertificateTemplateOperation(name string) *DeleteCertificateTemplateOperation { return &DeleteCertificateTemplateOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1815,9 +2109,9 @@ type DisableCertificateAuthorityOperation struct { // DisableCertificateAuthorityOperation returns a new DisableCertificateAuthorityOperation from a given name. // The name must be that of a previously created DisableCertificateAuthorityOperation, possibly from a different process. -func (c *CertificateAuthorityClient) DisableCertificateAuthorityOperation(name string) *DisableCertificateAuthorityOperation { +func (c *certificateAuthorityGRPCClient) DisableCertificateAuthorityOperation(name string) *DisableCertificateAuthorityOperation { return &DisableCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1884,9 +2178,9 @@ type EnableCertificateAuthorityOperation struct { // EnableCertificateAuthorityOperation returns a new EnableCertificateAuthorityOperation from a given name. // The name must be that of a previously created EnableCertificateAuthorityOperation, possibly from a different process. -func (c *CertificateAuthorityClient) EnableCertificateAuthorityOperation(name string) *EnableCertificateAuthorityOperation { +func (c *certificateAuthorityGRPCClient) EnableCertificateAuthorityOperation(name string) *EnableCertificateAuthorityOperation { return &EnableCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1953,9 +2247,9 @@ type UndeleteCertificateAuthorityOperation struct { // UndeleteCertificateAuthorityOperation returns a new UndeleteCertificateAuthorityOperation from a given name. // The name must be that of a previously created UndeleteCertificateAuthorityOperation, possibly from a different process. -func (c *CertificateAuthorityClient) UndeleteCertificateAuthorityOperation(name string) *UndeleteCertificateAuthorityOperation { +func (c *certificateAuthorityGRPCClient) UndeleteCertificateAuthorityOperation(name string) *UndeleteCertificateAuthorityOperation { return &UndeleteCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -2022,9 +2316,9 @@ type UpdateCaPoolOperation struct { // UpdateCaPoolOperation returns a new UpdateCaPoolOperation from a given name. // The name must be that of a previously created UpdateCaPoolOperation, possibly from a different process. -func (c *CertificateAuthorityClient) UpdateCaPoolOperation(name string) *UpdateCaPoolOperation { +func (c *certificateAuthorityGRPCClient) UpdateCaPoolOperation(name string) *UpdateCaPoolOperation { return &UpdateCaPoolOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -2091,9 +2385,9 @@ type UpdateCertificateAuthorityOperation struct { // UpdateCertificateAuthorityOperation returns a new UpdateCertificateAuthorityOperation from a given name. // The name must be that of a previously created UpdateCertificateAuthorityOperation, possibly from a different process. -func (c *CertificateAuthorityClient) UpdateCertificateAuthorityOperation(name string) *UpdateCertificateAuthorityOperation { +func (c *certificateAuthorityGRPCClient) UpdateCertificateAuthorityOperation(name string) *UpdateCertificateAuthorityOperation { return &UpdateCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -2160,9 +2454,9 @@ type UpdateCertificateRevocationListOperation struct { // UpdateCertificateRevocationListOperation returns a new UpdateCertificateRevocationListOperation from a given name. // The name must be that of a previously created UpdateCertificateRevocationListOperation, possibly from a different process. -func (c *CertificateAuthorityClient) UpdateCertificateRevocationListOperation(name string) *UpdateCertificateRevocationListOperation { +func (c *certificateAuthorityGRPCClient) UpdateCertificateRevocationListOperation(name string) *UpdateCertificateRevocationListOperation { return &UpdateCertificateRevocationListOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -2229,9 +2523,9 @@ type UpdateCertificateTemplateOperation struct { // UpdateCertificateTemplateOperation returns a new UpdateCertificateTemplateOperation from a given name. // The name must be that of a previously created UpdateCertificateTemplateOperation, possibly from a different process. -func (c *CertificateAuthorityClient) UpdateCertificateTemplateOperation(name string) *UpdateCertificateTemplateOperation { +func (c *certificateAuthorityGRPCClient) UpdateCertificateTemplateOperation(name string) *UpdateCertificateTemplateOperation { return &UpdateCertificateTemplateOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/security/privateca/apiv1/certificate_authority_client_example_test.go b/security/privateca/apiv1/certificate_authority_client_example_test.go index 4f3ae6c33c66..06def982684d 100644 --- a/security/privateca/apiv1/certificate_authority_client_example_test.go +++ b/security/privateca/apiv1/certificate_authority_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewCertificateAuthorityClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCertificateAuthorityClient_CreateCertificate() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.CreateCertificateRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleCertificateAuthorityClient_CreateCertificate() { } func ExampleCertificateAuthorityClient_GetCertificate() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetCertificateRequest{ // TODO: Fill request struct fields. @@ -75,14 +75,12 @@ func ExampleCertificateAuthorityClient_GetCertificate() { } func ExampleCertificateAuthorityClient_ListCertificates() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListCertificatesRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleCertificateAuthorityClient_ListCertificates() { } func ExampleCertificateAuthorityClient_RevokeCertificate() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.RevokeCertificateRequest{ // TODO: Fill request struct fields. @@ -122,13 +119,12 @@ func ExampleCertificateAuthorityClient_RevokeCertificate() { } func ExampleCertificateAuthorityClient_UpdateCertificate() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UpdateCertificateRequest{ // TODO: Fill request struct fields. @@ -142,13 +138,12 @@ func ExampleCertificateAuthorityClient_UpdateCertificate() { } func ExampleCertificateAuthorityClient_ActivateCertificateAuthority() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ActivateCertificateAuthorityRequest{ // TODO: Fill request struct fields. @@ -167,13 +162,12 @@ func ExampleCertificateAuthorityClient_ActivateCertificateAuthority() { } func ExampleCertificateAuthorityClient_CreateCertificateAuthority() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.CreateCertificateAuthorityRequest{ // TODO: Fill request struct fields. @@ -192,13 +186,12 @@ func ExampleCertificateAuthorityClient_CreateCertificateAuthority() { } func ExampleCertificateAuthorityClient_DisableCertificateAuthority() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.DisableCertificateAuthorityRequest{ // TODO: Fill request struct fields. @@ -217,13 +210,12 @@ func ExampleCertificateAuthorityClient_DisableCertificateAuthority() { } func ExampleCertificateAuthorityClient_EnableCertificateAuthority() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.EnableCertificateAuthorityRequest{ // TODO: Fill request struct fields. @@ -242,13 +234,12 @@ func ExampleCertificateAuthorityClient_EnableCertificateAuthority() { } func ExampleCertificateAuthorityClient_FetchCertificateAuthorityCsr() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.FetchCertificateAuthorityCsrRequest{ // TODO: Fill request struct fields. @@ -262,13 +253,12 @@ func ExampleCertificateAuthorityClient_FetchCertificateAuthorityCsr() { } func ExampleCertificateAuthorityClient_GetCertificateAuthority() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetCertificateAuthorityRequest{ // TODO: Fill request struct fields. @@ -282,14 +272,12 @@ func ExampleCertificateAuthorityClient_GetCertificateAuthority() { } func ExampleCertificateAuthorityClient_ListCertificateAuthorities() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListCertificateAuthoritiesRequest{ // TODO: Fill request struct fields. @@ -309,13 +297,12 @@ func ExampleCertificateAuthorityClient_ListCertificateAuthorities() { } func ExampleCertificateAuthorityClient_UndeleteCertificateAuthority() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UndeleteCertificateAuthorityRequest{ // TODO: Fill request struct fields. @@ -334,13 +321,12 @@ func ExampleCertificateAuthorityClient_UndeleteCertificateAuthority() { } func ExampleCertificateAuthorityClient_DeleteCertificateAuthority() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.DeleteCertificateAuthorityRequest{ // TODO: Fill request struct fields. @@ -359,13 +345,12 @@ func ExampleCertificateAuthorityClient_DeleteCertificateAuthority() { } func ExampleCertificateAuthorityClient_UpdateCertificateAuthority() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UpdateCertificateAuthorityRequest{ // TODO: Fill request struct fields. @@ -384,13 +369,12 @@ func ExampleCertificateAuthorityClient_UpdateCertificateAuthority() { } func ExampleCertificateAuthorityClient_CreateCaPool() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.CreateCaPoolRequest{ // TODO: Fill request struct fields. @@ -409,13 +393,12 @@ func ExampleCertificateAuthorityClient_CreateCaPool() { } func ExampleCertificateAuthorityClient_UpdateCaPool() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UpdateCaPoolRequest{ // TODO: Fill request struct fields. @@ -434,13 +417,12 @@ func ExampleCertificateAuthorityClient_UpdateCaPool() { } func ExampleCertificateAuthorityClient_GetCaPool() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetCaPoolRequest{ // TODO: Fill request struct fields. @@ -454,14 +436,12 @@ func ExampleCertificateAuthorityClient_GetCaPool() { } func ExampleCertificateAuthorityClient_ListCaPools() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListCaPoolsRequest{ // TODO: Fill request struct fields. @@ -481,13 +461,12 @@ func ExampleCertificateAuthorityClient_ListCaPools() { } func ExampleCertificateAuthorityClient_DeleteCaPool() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.DeleteCaPoolRequest{ // TODO: Fill request struct fields. @@ -506,13 +485,12 @@ func ExampleCertificateAuthorityClient_DeleteCaPool() { } func ExampleCertificateAuthorityClient_FetchCaCerts() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.FetchCaCertsRequest{ // TODO: Fill request struct fields. @@ -526,13 +504,12 @@ func ExampleCertificateAuthorityClient_FetchCaCerts() { } func ExampleCertificateAuthorityClient_GetCertificateRevocationList() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetCertificateRevocationListRequest{ // TODO: Fill request struct fields. @@ -546,14 +523,12 @@ func ExampleCertificateAuthorityClient_GetCertificateRevocationList() { } func ExampleCertificateAuthorityClient_ListCertificateRevocationLists() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListCertificateRevocationListsRequest{ // TODO: Fill request struct fields. @@ -573,13 +548,12 @@ func ExampleCertificateAuthorityClient_ListCertificateRevocationLists() { } func ExampleCertificateAuthorityClient_UpdateCertificateRevocationList() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UpdateCertificateRevocationListRequest{ // TODO: Fill request struct fields. @@ -598,13 +572,12 @@ func ExampleCertificateAuthorityClient_UpdateCertificateRevocationList() { } func ExampleCertificateAuthorityClient_CreateCertificateTemplate() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.CreateCertificateTemplateRequest{ // TODO: Fill request struct fields. @@ -623,13 +596,12 @@ func ExampleCertificateAuthorityClient_CreateCertificateTemplate() { } func ExampleCertificateAuthorityClient_DeleteCertificateTemplate() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.DeleteCertificateTemplateRequest{ // TODO: Fill request struct fields. @@ -646,13 +618,12 @@ func ExampleCertificateAuthorityClient_DeleteCertificateTemplate() { } func ExampleCertificateAuthorityClient_GetCertificateTemplate() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetCertificateTemplateRequest{ // TODO: Fill request struct fields. @@ -666,14 +637,12 @@ func ExampleCertificateAuthorityClient_GetCertificateTemplate() { } func ExampleCertificateAuthorityClient_ListCertificateTemplates() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListCertificateTemplatesRequest{ // TODO: Fill request struct fields. @@ -693,13 +662,12 @@ func ExampleCertificateAuthorityClient_ListCertificateTemplates() { } func ExampleCertificateAuthorityClient_UpdateCertificateTemplate() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UpdateCertificateTemplateRequest{ // TODO: Fill request struct fields. diff --git a/security/privateca/apiv1/doc.go b/security/privateca/apiv1/doc.go index 6530c7152212..50466f807791 100644 --- a/security/privateca/apiv1/doc.go +++ b/security/privateca/apiv1/doc.go @@ -22,6 +22,8 @@ // private certificate authorities (CAs) while staying in control of your // private keys." // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -31,7 +33,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package privateca // import "cloud.google.com/go/security/privateca/apiv1" import ( @@ -51,7 +53,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/security/privateca/apiv1beta1/certificate_authority_client.go b/security/privateca/apiv1beta1/certificate_authority_client.go index fa8f312ce455..4059262df127 100644 --- a/security/privateca/apiv1beta1/certificate_authority_client.go +++ b/security/privateca/apiv1beta1/certificate_authority_client.go @@ -64,7 +64,7 @@ type CertificateAuthorityCallOptions struct { ListReusableConfigs []gax.CallOption } -func defaultCertificateAuthorityClientOptions() []option.ClientOption { +func defaultCertificateAuthorityGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("privateca.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("privateca.mtls.googleapis.com:443"), @@ -341,38 +341,274 @@ func defaultCertificateAuthorityCallOptions() *CertificateAuthorityCallOptions { } } +// internalCertificateAuthorityClient is an interface that defines the methods availaible from Certificate Authority API. +type internalCertificateAuthorityClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateCertificate(context.Context, *privatecapb.CreateCertificateRequest, ...gax.CallOption) (*privatecapb.Certificate, error) + GetCertificate(context.Context, *privatecapb.GetCertificateRequest, ...gax.CallOption) (*privatecapb.Certificate, error) + ListCertificates(context.Context, *privatecapb.ListCertificatesRequest, ...gax.CallOption) *CertificateIterator + RevokeCertificate(context.Context, *privatecapb.RevokeCertificateRequest, ...gax.CallOption) (*privatecapb.Certificate, error) + UpdateCertificate(context.Context, *privatecapb.UpdateCertificateRequest, ...gax.CallOption) (*privatecapb.Certificate, error) + ActivateCertificateAuthority(context.Context, *privatecapb.ActivateCertificateAuthorityRequest, ...gax.CallOption) (*ActivateCertificateAuthorityOperation, error) + ActivateCertificateAuthorityOperation(name string) *ActivateCertificateAuthorityOperation + CreateCertificateAuthority(context.Context, *privatecapb.CreateCertificateAuthorityRequest, ...gax.CallOption) (*CreateCertificateAuthorityOperation, error) + CreateCertificateAuthorityOperation(name string) *CreateCertificateAuthorityOperation + DisableCertificateAuthority(context.Context, *privatecapb.DisableCertificateAuthorityRequest, ...gax.CallOption) (*DisableCertificateAuthorityOperation, error) + DisableCertificateAuthorityOperation(name string) *DisableCertificateAuthorityOperation + EnableCertificateAuthority(context.Context, *privatecapb.EnableCertificateAuthorityRequest, ...gax.CallOption) (*EnableCertificateAuthorityOperation, error) + EnableCertificateAuthorityOperation(name string) *EnableCertificateAuthorityOperation + FetchCertificateAuthorityCsr(context.Context, *privatecapb.FetchCertificateAuthorityCsrRequest, ...gax.CallOption) (*privatecapb.FetchCertificateAuthorityCsrResponse, error) + GetCertificateAuthority(context.Context, *privatecapb.GetCertificateAuthorityRequest, ...gax.CallOption) (*privatecapb.CertificateAuthority, error) + ListCertificateAuthorities(context.Context, *privatecapb.ListCertificateAuthoritiesRequest, ...gax.CallOption) *CertificateAuthorityIterator + RestoreCertificateAuthority(context.Context, *privatecapb.RestoreCertificateAuthorityRequest, ...gax.CallOption) (*RestoreCertificateAuthorityOperation, error) + RestoreCertificateAuthorityOperation(name string) *RestoreCertificateAuthorityOperation + ScheduleDeleteCertificateAuthority(context.Context, *privatecapb.ScheduleDeleteCertificateAuthorityRequest, ...gax.CallOption) (*ScheduleDeleteCertificateAuthorityOperation, error) + ScheduleDeleteCertificateAuthorityOperation(name string) *ScheduleDeleteCertificateAuthorityOperation + UpdateCertificateAuthority(context.Context, *privatecapb.UpdateCertificateAuthorityRequest, ...gax.CallOption) (*UpdateCertificateAuthorityOperation, error) + UpdateCertificateAuthorityOperation(name string) *UpdateCertificateAuthorityOperation + GetCertificateRevocationList(context.Context, *privatecapb.GetCertificateRevocationListRequest, ...gax.CallOption) (*privatecapb.CertificateRevocationList, error) + ListCertificateRevocationLists(context.Context, *privatecapb.ListCertificateRevocationListsRequest, ...gax.CallOption) *CertificateRevocationListIterator + UpdateCertificateRevocationList(context.Context, *privatecapb.UpdateCertificateRevocationListRequest, ...gax.CallOption) (*UpdateCertificateRevocationListOperation, error) + UpdateCertificateRevocationListOperation(name string) *UpdateCertificateRevocationListOperation + GetReusableConfig(context.Context, *privatecapb.GetReusableConfigRequest, ...gax.CallOption) (*privatecapb.ReusableConfig, error) + ListReusableConfigs(context.Context, *privatecapb.ListReusableConfigsRequest, ...gax.CallOption) *ReusableConfigIterator +} + // CertificateAuthorityClient is a client for interacting with Certificate Authority API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// [Certificate Authority Service][google.cloud.security.privateca.v1beta1.CertificateAuthorityService] manages private +// certificate authorities and issued certificates. type CertificateAuthorityClient struct { + // The internal transport-dependent client. + internalClient internalCertificateAuthorityClient + + // The call options for this service. + CallOptions *CertificateAuthorityCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CertificateAuthorityClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CertificateAuthorityClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CertificateAuthorityClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateCertificate create a new Certificate in a given Project, Location from a particular +// CertificateAuthority. +func (c *CertificateAuthorityClient) CreateCertificate(ctx context.Context, req *privatecapb.CreateCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { + return c.internalClient.CreateCertificate(ctx, req, opts...) +} + +// GetCertificate returns a Certificate. +func (c *CertificateAuthorityClient) GetCertificate(ctx context.Context, req *privatecapb.GetCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { + return c.internalClient.GetCertificate(ctx, req, opts...) +} + +// ListCertificates lists Certificates. +func (c *CertificateAuthorityClient) ListCertificates(ctx context.Context, req *privatecapb.ListCertificatesRequest, opts ...gax.CallOption) *CertificateIterator { + return c.internalClient.ListCertificates(ctx, req, opts...) +} + +// RevokeCertificate revoke a Certificate. +func (c *CertificateAuthorityClient) RevokeCertificate(ctx context.Context, req *privatecapb.RevokeCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { + return c.internalClient.RevokeCertificate(ctx, req, opts...) +} + +// UpdateCertificate update a Certificate. Currently, the only field you can update is the +// labels field. +func (c *CertificateAuthorityClient) UpdateCertificate(ctx context.Context, req *privatecapb.UpdateCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { + return c.internalClient.UpdateCertificate(ctx, req, opts...) +} + +// ActivateCertificateAuthority activate a CertificateAuthority that is in state +// PENDING_ACTIVATION and is +// of type SUBORDINATE. After the +// parent Certificate Authority signs a certificate signing request from +// FetchCertificateAuthorityCsr, this method can complete the activation +// process. +func (c *CertificateAuthorityClient) ActivateCertificateAuthority(ctx context.Context, req *privatecapb.ActivateCertificateAuthorityRequest, opts ...gax.CallOption) (*ActivateCertificateAuthorityOperation, error) { + return c.internalClient.ActivateCertificateAuthority(ctx, req, opts...) +} + +// ActivateCertificateAuthorityOperation returns a new ActivateCertificateAuthorityOperation from a given name. +// The name must be that of a previously created ActivateCertificateAuthorityOperation, possibly from a different process. +func (c *CertificateAuthorityClient) ActivateCertificateAuthorityOperation(name string) *ActivateCertificateAuthorityOperation { + return c.internalClient.ActivateCertificateAuthorityOperation(name) +} + +// CreateCertificateAuthority create a new CertificateAuthority in a given Project and Location. +func (c *CertificateAuthorityClient) CreateCertificateAuthority(ctx context.Context, req *privatecapb.CreateCertificateAuthorityRequest, opts ...gax.CallOption) (*CreateCertificateAuthorityOperation, error) { + return c.internalClient.CreateCertificateAuthority(ctx, req, opts...) +} + +// CreateCertificateAuthorityOperation returns a new CreateCertificateAuthorityOperation from a given name. +// The name must be that of a previously created CreateCertificateAuthorityOperation, possibly from a different process. +func (c *CertificateAuthorityClient) CreateCertificateAuthorityOperation(name string) *CreateCertificateAuthorityOperation { + return c.internalClient.CreateCertificateAuthorityOperation(name) +} + +// DisableCertificateAuthority disable a CertificateAuthority. +func (c *CertificateAuthorityClient) DisableCertificateAuthority(ctx context.Context, req *privatecapb.DisableCertificateAuthorityRequest, opts ...gax.CallOption) (*DisableCertificateAuthorityOperation, error) { + return c.internalClient.DisableCertificateAuthority(ctx, req, opts...) +} + +// DisableCertificateAuthorityOperation returns a new DisableCertificateAuthorityOperation from a given name. +// The name must be that of a previously created DisableCertificateAuthorityOperation, possibly from a different process. +func (c *CertificateAuthorityClient) DisableCertificateAuthorityOperation(name string) *DisableCertificateAuthorityOperation { + return c.internalClient.DisableCertificateAuthorityOperation(name) +} + +// EnableCertificateAuthority enable a CertificateAuthority. +func (c *CertificateAuthorityClient) EnableCertificateAuthority(ctx context.Context, req *privatecapb.EnableCertificateAuthorityRequest, opts ...gax.CallOption) (*EnableCertificateAuthorityOperation, error) { + return c.internalClient.EnableCertificateAuthority(ctx, req, opts...) +} + +// EnableCertificateAuthorityOperation returns a new EnableCertificateAuthorityOperation from a given name. +// The name must be that of a previously created EnableCertificateAuthorityOperation, possibly from a different process. +func (c *CertificateAuthorityClient) EnableCertificateAuthorityOperation(name string) *EnableCertificateAuthorityOperation { + return c.internalClient.EnableCertificateAuthorityOperation(name) +} + +// FetchCertificateAuthorityCsr fetch a certificate signing request (CSR) from a CertificateAuthority +// that is in state +// PENDING_ACTIVATION and is +// of type SUBORDINATE. The CSR must +// then be signed by the desired parent Certificate Authority, which could be +// another CertificateAuthority resource, or could be an on-prem +// certificate authority. See also ActivateCertificateAuthority. +func (c *CertificateAuthorityClient) FetchCertificateAuthorityCsr(ctx context.Context, req *privatecapb.FetchCertificateAuthorityCsrRequest, opts ...gax.CallOption) (*privatecapb.FetchCertificateAuthorityCsrResponse, error) { + return c.internalClient.FetchCertificateAuthorityCsr(ctx, req, opts...) +} + +// GetCertificateAuthority returns a CertificateAuthority. +func (c *CertificateAuthorityClient) GetCertificateAuthority(ctx context.Context, req *privatecapb.GetCertificateAuthorityRequest, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { + return c.internalClient.GetCertificateAuthority(ctx, req, opts...) +} + +// ListCertificateAuthorities lists CertificateAuthorities. +func (c *CertificateAuthorityClient) ListCertificateAuthorities(ctx context.Context, req *privatecapb.ListCertificateAuthoritiesRequest, opts ...gax.CallOption) *CertificateAuthorityIterator { + return c.internalClient.ListCertificateAuthorities(ctx, req, opts...) +} + +// RestoreCertificateAuthority restore a CertificateAuthority that is scheduled for deletion. +func (c *CertificateAuthorityClient) RestoreCertificateAuthority(ctx context.Context, req *privatecapb.RestoreCertificateAuthorityRequest, opts ...gax.CallOption) (*RestoreCertificateAuthorityOperation, error) { + return c.internalClient.RestoreCertificateAuthority(ctx, req, opts...) +} + +// RestoreCertificateAuthorityOperation returns a new RestoreCertificateAuthorityOperation from a given name. +// The name must be that of a previously created RestoreCertificateAuthorityOperation, possibly from a different process. +func (c *CertificateAuthorityClient) RestoreCertificateAuthorityOperation(name string) *RestoreCertificateAuthorityOperation { + return c.internalClient.RestoreCertificateAuthorityOperation(name) +} + +// ScheduleDeleteCertificateAuthority schedule a CertificateAuthority for deletion. +func (c *CertificateAuthorityClient) ScheduleDeleteCertificateAuthority(ctx context.Context, req *privatecapb.ScheduleDeleteCertificateAuthorityRequest, opts ...gax.CallOption) (*ScheduleDeleteCertificateAuthorityOperation, error) { + return c.internalClient.ScheduleDeleteCertificateAuthority(ctx, req, opts...) +} + +// ScheduleDeleteCertificateAuthorityOperation returns a new ScheduleDeleteCertificateAuthorityOperation from a given name. +// The name must be that of a previously created ScheduleDeleteCertificateAuthorityOperation, possibly from a different process. +func (c *CertificateAuthorityClient) ScheduleDeleteCertificateAuthorityOperation(name string) *ScheduleDeleteCertificateAuthorityOperation { + return c.internalClient.ScheduleDeleteCertificateAuthorityOperation(name) +} + +// UpdateCertificateAuthority update a CertificateAuthority. +func (c *CertificateAuthorityClient) UpdateCertificateAuthority(ctx context.Context, req *privatecapb.UpdateCertificateAuthorityRequest, opts ...gax.CallOption) (*UpdateCertificateAuthorityOperation, error) { + return c.internalClient.UpdateCertificateAuthority(ctx, req, opts...) +} + +// UpdateCertificateAuthorityOperation returns a new UpdateCertificateAuthorityOperation from a given name. +// The name must be that of a previously created UpdateCertificateAuthorityOperation, possibly from a different process. +func (c *CertificateAuthorityClient) UpdateCertificateAuthorityOperation(name string) *UpdateCertificateAuthorityOperation { + return c.internalClient.UpdateCertificateAuthorityOperation(name) +} + +// GetCertificateRevocationList returns a CertificateRevocationList. +func (c *CertificateAuthorityClient) GetCertificateRevocationList(ctx context.Context, req *privatecapb.GetCertificateRevocationListRequest, opts ...gax.CallOption) (*privatecapb.CertificateRevocationList, error) { + return c.internalClient.GetCertificateRevocationList(ctx, req, opts...) +} + +// ListCertificateRevocationLists lists CertificateRevocationLists. +func (c *CertificateAuthorityClient) ListCertificateRevocationLists(ctx context.Context, req *privatecapb.ListCertificateRevocationListsRequest, opts ...gax.CallOption) *CertificateRevocationListIterator { + return c.internalClient.ListCertificateRevocationLists(ctx, req, opts...) +} + +// UpdateCertificateRevocationList update a CertificateRevocationList. +func (c *CertificateAuthorityClient) UpdateCertificateRevocationList(ctx context.Context, req *privatecapb.UpdateCertificateRevocationListRequest, opts ...gax.CallOption) (*UpdateCertificateRevocationListOperation, error) { + return c.internalClient.UpdateCertificateRevocationList(ctx, req, opts...) +} + +// UpdateCertificateRevocationListOperation returns a new UpdateCertificateRevocationListOperation from a given name. +// The name must be that of a previously created UpdateCertificateRevocationListOperation, possibly from a different process. +func (c *CertificateAuthorityClient) UpdateCertificateRevocationListOperation(name string) *UpdateCertificateRevocationListOperation { + return c.internalClient.UpdateCertificateRevocationListOperation(name) +} + +// GetReusableConfig returns a ReusableConfig. +func (c *CertificateAuthorityClient) GetReusableConfig(ctx context.Context, req *privatecapb.GetReusableConfigRequest, opts ...gax.CallOption) (*privatecapb.ReusableConfig, error) { + return c.internalClient.GetReusableConfig(ctx, req, opts...) +} + +// ListReusableConfigs lists ReusableConfigs. +func (c *CertificateAuthorityClient) ListReusableConfigs(ctx context.Context, req *privatecapb.ListReusableConfigsRequest, opts ...gax.CallOption) *ReusableConfigIterator { + return c.internalClient.ListReusableConfigs(ctx, req, opts...) +} + +// certificateAuthorityGRPCClient is a client for interacting with Certificate Authority API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type certificateAuthorityGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CertificateAuthorityClient + CallOptions **CertificateAuthorityCallOptions + // The gRPC API client. certificateAuthorityClient privatecapb.CertificateAuthorityServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CertificateAuthorityCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCertificateAuthorityClient creates a new certificate authority service client. +// NewCertificateAuthorityClient creates a new certificate authority service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // [Certificate Authority Service][google.cloud.security.privateca.v1beta1.CertificateAuthorityService] manages private // certificate authorities and issued certificates. func NewCertificateAuthorityClient(ctx context.Context, opts ...option.ClientOption) (*CertificateAuthorityClient, error) { - clientOpts := defaultCertificateAuthorityClientOptions() - + clientOpts := defaultCertificateAuthorityGRPCClientOptions() if newCertificateAuthorityClientHook != nil { hookOpts, err := newCertificateAuthorityClientHook(ctx, clientHookParams{}) if err != nil { @@ -390,16 +626,19 @@ func NewCertificateAuthorityClient(ctx context.Context, opts ...option.ClientOpt if err != nil { return nil, err } - c := &CertificateAuthorityClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultCertificateAuthorityCallOptions(), + client := CertificateAuthorityClient{CallOptions: defaultCertificateAuthorityCallOptions()} + c := &certificateAuthorityGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, certificateAuthorityClient: privatecapb.NewCertificateAuthorityServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -409,34 +648,33 @@ func NewCertificateAuthorityClient(ctx context.Context, opts ...option.ClientOpt // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CertificateAuthorityClient) Connection() *grpc.ClientConn { +func (c *certificateAuthorityGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CertificateAuthorityClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CertificateAuthorityClient) setGoogleClientInfo(keyval ...string) { +func (c *certificateAuthorityGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateCertificate create a new Certificate in a given Project, Location from a particular -// CertificateAuthority. -func (c *CertificateAuthorityClient) CreateCertificate(ctx context.Context, req *privatecapb.CreateCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *certificateAuthorityGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *certificateAuthorityGRPCClient) CreateCertificate(ctx context.Context, req *privatecapb.CreateCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -444,7 +682,7 @@ func (c *CertificateAuthorityClient) CreateCertificate(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCertificate[0:len(c.CallOptions.CreateCertificate):len(c.CallOptions.CreateCertificate)], opts...) + opts = append((*c.CallOptions).CreateCertificate[0:len((*c.CallOptions).CreateCertificate):len((*c.CallOptions).CreateCertificate)], opts...) var resp *privatecapb.Certificate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -457,8 +695,7 @@ func (c *CertificateAuthorityClient) CreateCertificate(ctx context.Context, req return resp, nil } -// GetCertificate returns a Certificate. -func (c *CertificateAuthorityClient) GetCertificate(ctx context.Context, req *privatecapb.GetCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { +func (c *certificateAuthorityGRPCClient) GetCertificate(ctx context.Context, req *privatecapb.GetCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -466,7 +703,7 @@ func (c *CertificateAuthorityClient) GetCertificate(ctx context.Context, req *pr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCertificate[0:len(c.CallOptions.GetCertificate):len(c.CallOptions.GetCertificate)], opts...) + opts = append((*c.CallOptions).GetCertificate[0:len((*c.CallOptions).GetCertificate):len((*c.CallOptions).GetCertificate)], opts...) var resp *privatecapb.Certificate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -479,11 +716,10 @@ func (c *CertificateAuthorityClient) GetCertificate(ctx context.Context, req *pr return resp, nil } -// ListCertificates lists Certificates. -func (c *CertificateAuthorityClient) ListCertificates(ctx context.Context, req *privatecapb.ListCertificatesRequest, opts ...gax.CallOption) *CertificateIterator { +func (c *certificateAuthorityGRPCClient) ListCertificates(ctx context.Context, req *privatecapb.ListCertificatesRequest, opts ...gax.CallOption) *CertificateIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCertificates[0:len(c.CallOptions.ListCertificates):len(c.CallOptions.ListCertificates)], opts...) + opts = append((*c.CallOptions).ListCertificates[0:len((*c.CallOptions).ListCertificates):len((*c.CallOptions).ListCertificates)], opts...) it := &CertificateIterator{} req = proto.Clone(req).(*privatecapb.ListCertificatesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*privatecapb.Certificate, string, error) { @@ -520,8 +756,7 @@ func (c *CertificateAuthorityClient) ListCertificates(ctx context.Context, req * return it } -// RevokeCertificate revoke a Certificate. -func (c *CertificateAuthorityClient) RevokeCertificate(ctx context.Context, req *privatecapb.RevokeCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { +func (c *certificateAuthorityGRPCClient) RevokeCertificate(ctx context.Context, req *privatecapb.RevokeCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -529,7 +764,7 @@ func (c *CertificateAuthorityClient) RevokeCertificate(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RevokeCertificate[0:len(c.CallOptions.RevokeCertificate):len(c.CallOptions.RevokeCertificate)], opts...) + opts = append((*c.CallOptions).RevokeCertificate[0:len((*c.CallOptions).RevokeCertificate):len((*c.CallOptions).RevokeCertificate)], opts...) var resp *privatecapb.Certificate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -542,9 +777,7 @@ func (c *CertificateAuthorityClient) RevokeCertificate(ctx context.Context, req return resp, nil } -// UpdateCertificate update a Certificate. Currently, the only field you can update is the -// labels field. -func (c *CertificateAuthorityClient) UpdateCertificate(ctx context.Context, req *privatecapb.UpdateCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { +func (c *certificateAuthorityGRPCClient) UpdateCertificate(ctx context.Context, req *privatecapb.UpdateCertificateRequest, opts ...gax.CallOption) (*privatecapb.Certificate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -552,7 +785,7 @@ func (c *CertificateAuthorityClient) UpdateCertificate(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "certificate.name", url.QueryEscape(req.GetCertificate().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCertificate[0:len(c.CallOptions.UpdateCertificate):len(c.CallOptions.UpdateCertificate)], opts...) + opts = append((*c.CallOptions).UpdateCertificate[0:len((*c.CallOptions).UpdateCertificate):len((*c.CallOptions).UpdateCertificate)], opts...) var resp *privatecapb.Certificate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -565,13 +798,7 @@ func (c *CertificateAuthorityClient) UpdateCertificate(ctx context.Context, req return resp, nil } -// ActivateCertificateAuthority activate a CertificateAuthority that is in state -// PENDING_ACTIVATION and is -// of type SUBORDINATE. After the -// parent Certificate Authority signs a certificate signing request from -// FetchCertificateAuthorityCsr, this method can complete the activation -// process. -func (c *CertificateAuthorityClient) ActivateCertificateAuthority(ctx context.Context, req *privatecapb.ActivateCertificateAuthorityRequest, opts ...gax.CallOption) (*ActivateCertificateAuthorityOperation, error) { +func (c *certificateAuthorityGRPCClient) ActivateCertificateAuthority(ctx context.Context, req *privatecapb.ActivateCertificateAuthorityRequest, opts ...gax.CallOption) (*ActivateCertificateAuthorityOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -579,7 +806,7 @@ func (c *CertificateAuthorityClient) ActivateCertificateAuthority(ctx context.Co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ActivateCertificateAuthority[0:len(c.CallOptions.ActivateCertificateAuthority):len(c.CallOptions.ActivateCertificateAuthority)], opts...) + opts = append((*c.CallOptions).ActivateCertificateAuthority[0:len((*c.CallOptions).ActivateCertificateAuthority):len((*c.CallOptions).ActivateCertificateAuthority)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -590,12 +817,11 @@ func (c *CertificateAuthorityClient) ActivateCertificateAuthority(ctx context.Co return nil, err } return &ActivateCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// CreateCertificateAuthority create a new CertificateAuthority in a given Project and Location. -func (c *CertificateAuthorityClient) CreateCertificateAuthority(ctx context.Context, req *privatecapb.CreateCertificateAuthorityRequest, opts ...gax.CallOption) (*CreateCertificateAuthorityOperation, error) { +func (c *certificateAuthorityGRPCClient) CreateCertificateAuthority(ctx context.Context, req *privatecapb.CreateCertificateAuthorityRequest, opts ...gax.CallOption) (*CreateCertificateAuthorityOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -603,7 +829,7 @@ func (c *CertificateAuthorityClient) CreateCertificateAuthority(ctx context.Cont } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCertificateAuthority[0:len(c.CallOptions.CreateCertificateAuthority):len(c.CallOptions.CreateCertificateAuthority)], opts...) + opts = append((*c.CallOptions).CreateCertificateAuthority[0:len((*c.CallOptions).CreateCertificateAuthority):len((*c.CallOptions).CreateCertificateAuthority)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -614,12 +840,11 @@ func (c *CertificateAuthorityClient) CreateCertificateAuthority(ctx context.Cont return nil, err } return &CreateCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DisableCertificateAuthority disable a CertificateAuthority. -func (c *CertificateAuthorityClient) DisableCertificateAuthority(ctx context.Context, req *privatecapb.DisableCertificateAuthorityRequest, opts ...gax.CallOption) (*DisableCertificateAuthorityOperation, error) { +func (c *certificateAuthorityGRPCClient) DisableCertificateAuthority(ctx context.Context, req *privatecapb.DisableCertificateAuthorityRequest, opts ...gax.CallOption) (*DisableCertificateAuthorityOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -627,7 +852,7 @@ func (c *CertificateAuthorityClient) DisableCertificateAuthority(ctx context.Con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DisableCertificateAuthority[0:len(c.CallOptions.DisableCertificateAuthority):len(c.CallOptions.DisableCertificateAuthority)], opts...) + opts = append((*c.CallOptions).DisableCertificateAuthority[0:len((*c.CallOptions).DisableCertificateAuthority):len((*c.CallOptions).DisableCertificateAuthority)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -638,12 +863,11 @@ func (c *CertificateAuthorityClient) DisableCertificateAuthority(ctx context.Con return nil, err } return &DisableCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// EnableCertificateAuthority enable a CertificateAuthority. -func (c *CertificateAuthorityClient) EnableCertificateAuthority(ctx context.Context, req *privatecapb.EnableCertificateAuthorityRequest, opts ...gax.CallOption) (*EnableCertificateAuthorityOperation, error) { +func (c *certificateAuthorityGRPCClient) EnableCertificateAuthority(ctx context.Context, req *privatecapb.EnableCertificateAuthorityRequest, opts ...gax.CallOption) (*EnableCertificateAuthorityOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -651,7 +875,7 @@ func (c *CertificateAuthorityClient) EnableCertificateAuthority(ctx context.Cont } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.EnableCertificateAuthority[0:len(c.CallOptions.EnableCertificateAuthority):len(c.CallOptions.EnableCertificateAuthority)], opts...) + opts = append((*c.CallOptions).EnableCertificateAuthority[0:len((*c.CallOptions).EnableCertificateAuthority):len((*c.CallOptions).EnableCertificateAuthority)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -662,18 +886,11 @@ func (c *CertificateAuthorityClient) EnableCertificateAuthority(ctx context.Cont return nil, err } return &EnableCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// FetchCertificateAuthorityCsr fetch a certificate signing request (CSR) from a CertificateAuthority -// that is in state -// PENDING_ACTIVATION and is -// of type SUBORDINATE. The CSR must -// then be signed by the desired parent Certificate Authority, which could be -// another CertificateAuthority resource, or could be an on-prem -// certificate authority. See also ActivateCertificateAuthority. -func (c *CertificateAuthorityClient) FetchCertificateAuthorityCsr(ctx context.Context, req *privatecapb.FetchCertificateAuthorityCsrRequest, opts ...gax.CallOption) (*privatecapb.FetchCertificateAuthorityCsrResponse, error) { +func (c *certificateAuthorityGRPCClient) FetchCertificateAuthorityCsr(ctx context.Context, req *privatecapb.FetchCertificateAuthorityCsrRequest, opts ...gax.CallOption) (*privatecapb.FetchCertificateAuthorityCsrResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -681,7 +898,7 @@ func (c *CertificateAuthorityClient) FetchCertificateAuthorityCsr(ctx context.Co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.FetchCertificateAuthorityCsr[0:len(c.CallOptions.FetchCertificateAuthorityCsr):len(c.CallOptions.FetchCertificateAuthorityCsr)], opts...) + opts = append((*c.CallOptions).FetchCertificateAuthorityCsr[0:len((*c.CallOptions).FetchCertificateAuthorityCsr):len((*c.CallOptions).FetchCertificateAuthorityCsr)], opts...) var resp *privatecapb.FetchCertificateAuthorityCsrResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -694,8 +911,7 @@ func (c *CertificateAuthorityClient) FetchCertificateAuthorityCsr(ctx context.Co return resp, nil } -// GetCertificateAuthority returns a CertificateAuthority. -func (c *CertificateAuthorityClient) GetCertificateAuthority(ctx context.Context, req *privatecapb.GetCertificateAuthorityRequest, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { +func (c *certificateAuthorityGRPCClient) GetCertificateAuthority(ctx context.Context, req *privatecapb.GetCertificateAuthorityRequest, opts ...gax.CallOption) (*privatecapb.CertificateAuthority, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -703,7 +919,7 @@ func (c *CertificateAuthorityClient) GetCertificateAuthority(ctx context.Context } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCertificateAuthority[0:len(c.CallOptions.GetCertificateAuthority):len(c.CallOptions.GetCertificateAuthority)], opts...) + opts = append((*c.CallOptions).GetCertificateAuthority[0:len((*c.CallOptions).GetCertificateAuthority):len((*c.CallOptions).GetCertificateAuthority)], opts...) var resp *privatecapb.CertificateAuthority err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -716,11 +932,10 @@ func (c *CertificateAuthorityClient) GetCertificateAuthority(ctx context.Context return resp, nil } -// ListCertificateAuthorities lists CertificateAuthorities. -func (c *CertificateAuthorityClient) ListCertificateAuthorities(ctx context.Context, req *privatecapb.ListCertificateAuthoritiesRequest, opts ...gax.CallOption) *CertificateAuthorityIterator { +func (c *certificateAuthorityGRPCClient) ListCertificateAuthorities(ctx context.Context, req *privatecapb.ListCertificateAuthoritiesRequest, opts ...gax.CallOption) *CertificateAuthorityIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCertificateAuthorities[0:len(c.CallOptions.ListCertificateAuthorities):len(c.CallOptions.ListCertificateAuthorities)], opts...) + opts = append((*c.CallOptions).ListCertificateAuthorities[0:len((*c.CallOptions).ListCertificateAuthorities):len((*c.CallOptions).ListCertificateAuthorities)], opts...) it := &CertificateAuthorityIterator{} req = proto.Clone(req).(*privatecapb.ListCertificateAuthoritiesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*privatecapb.CertificateAuthority, string, error) { @@ -757,8 +972,7 @@ func (c *CertificateAuthorityClient) ListCertificateAuthorities(ctx context.Cont return it } -// RestoreCertificateAuthority restore a CertificateAuthority that is scheduled for deletion. -func (c *CertificateAuthorityClient) RestoreCertificateAuthority(ctx context.Context, req *privatecapb.RestoreCertificateAuthorityRequest, opts ...gax.CallOption) (*RestoreCertificateAuthorityOperation, error) { +func (c *certificateAuthorityGRPCClient) RestoreCertificateAuthority(ctx context.Context, req *privatecapb.RestoreCertificateAuthorityRequest, opts ...gax.CallOption) (*RestoreCertificateAuthorityOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -766,7 +980,7 @@ func (c *CertificateAuthorityClient) RestoreCertificateAuthority(ctx context.Con } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RestoreCertificateAuthority[0:len(c.CallOptions.RestoreCertificateAuthority):len(c.CallOptions.RestoreCertificateAuthority)], opts...) + opts = append((*c.CallOptions).RestoreCertificateAuthority[0:len((*c.CallOptions).RestoreCertificateAuthority):len((*c.CallOptions).RestoreCertificateAuthority)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -777,12 +991,11 @@ func (c *CertificateAuthorityClient) RestoreCertificateAuthority(ctx context.Con return nil, err } return &RestoreCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ScheduleDeleteCertificateAuthority schedule a CertificateAuthority for deletion. -func (c *CertificateAuthorityClient) ScheduleDeleteCertificateAuthority(ctx context.Context, req *privatecapb.ScheduleDeleteCertificateAuthorityRequest, opts ...gax.CallOption) (*ScheduleDeleteCertificateAuthorityOperation, error) { +func (c *certificateAuthorityGRPCClient) ScheduleDeleteCertificateAuthority(ctx context.Context, req *privatecapb.ScheduleDeleteCertificateAuthorityRequest, opts ...gax.CallOption) (*ScheduleDeleteCertificateAuthorityOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -790,7 +1003,7 @@ func (c *CertificateAuthorityClient) ScheduleDeleteCertificateAuthority(ctx cont } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ScheduleDeleteCertificateAuthority[0:len(c.CallOptions.ScheduleDeleteCertificateAuthority):len(c.CallOptions.ScheduleDeleteCertificateAuthority)], opts...) + opts = append((*c.CallOptions).ScheduleDeleteCertificateAuthority[0:len((*c.CallOptions).ScheduleDeleteCertificateAuthority):len((*c.CallOptions).ScheduleDeleteCertificateAuthority)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -801,12 +1014,11 @@ func (c *CertificateAuthorityClient) ScheduleDeleteCertificateAuthority(ctx cont return nil, err } return &ScheduleDeleteCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateCertificateAuthority update a CertificateAuthority. -func (c *CertificateAuthorityClient) UpdateCertificateAuthority(ctx context.Context, req *privatecapb.UpdateCertificateAuthorityRequest, opts ...gax.CallOption) (*UpdateCertificateAuthorityOperation, error) { +func (c *certificateAuthorityGRPCClient) UpdateCertificateAuthority(ctx context.Context, req *privatecapb.UpdateCertificateAuthorityRequest, opts ...gax.CallOption) (*UpdateCertificateAuthorityOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -814,7 +1026,7 @@ func (c *CertificateAuthorityClient) UpdateCertificateAuthority(ctx context.Cont } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "certificate_authority.name", url.QueryEscape(req.GetCertificateAuthority().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCertificateAuthority[0:len(c.CallOptions.UpdateCertificateAuthority):len(c.CallOptions.UpdateCertificateAuthority)], opts...) + opts = append((*c.CallOptions).UpdateCertificateAuthority[0:len((*c.CallOptions).UpdateCertificateAuthority):len((*c.CallOptions).UpdateCertificateAuthority)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -825,12 +1037,11 @@ func (c *CertificateAuthorityClient) UpdateCertificateAuthority(ctx context.Cont return nil, err } return &UpdateCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetCertificateRevocationList returns a CertificateRevocationList. -func (c *CertificateAuthorityClient) GetCertificateRevocationList(ctx context.Context, req *privatecapb.GetCertificateRevocationListRequest, opts ...gax.CallOption) (*privatecapb.CertificateRevocationList, error) { +func (c *certificateAuthorityGRPCClient) GetCertificateRevocationList(ctx context.Context, req *privatecapb.GetCertificateRevocationListRequest, opts ...gax.CallOption) (*privatecapb.CertificateRevocationList, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -838,7 +1049,7 @@ func (c *CertificateAuthorityClient) GetCertificateRevocationList(ctx context.Co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCertificateRevocationList[0:len(c.CallOptions.GetCertificateRevocationList):len(c.CallOptions.GetCertificateRevocationList)], opts...) + opts = append((*c.CallOptions).GetCertificateRevocationList[0:len((*c.CallOptions).GetCertificateRevocationList):len((*c.CallOptions).GetCertificateRevocationList)], opts...) var resp *privatecapb.CertificateRevocationList err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -851,11 +1062,10 @@ func (c *CertificateAuthorityClient) GetCertificateRevocationList(ctx context.Co return resp, nil } -// ListCertificateRevocationLists lists CertificateRevocationLists. -func (c *CertificateAuthorityClient) ListCertificateRevocationLists(ctx context.Context, req *privatecapb.ListCertificateRevocationListsRequest, opts ...gax.CallOption) *CertificateRevocationListIterator { +func (c *certificateAuthorityGRPCClient) ListCertificateRevocationLists(ctx context.Context, req *privatecapb.ListCertificateRevocationListsRequest, opts ...gax.CallOption) *CertificateRevocationListIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCertificateRevocationLists[0:len(c.CallOptions.ListCertificateRevocationLists):len(c.CallOptions.ListCertificateRevocationLists)], opts...) + opts = append((*c.CallOptions).ListCertificateRevocationLists[0:len((*c.CallOptions).ListCertificateRevocationLists):len((*c.CallOptions).ListCertificateRevocationLists)], opts...) it := &CertificateRevocationListIterator{} req = proto.Clone(req).(*privatecapb.ListCertificateRevocationListsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*privatecapb.CertificateRevocationList, string, error) { @@ -892,8 +1102,7 @@ func (c *CertificateAuthorityClient) ListCertificateRevocationLists(ctx context. return it } -// UpdateCertificateRevocationList update a CertificateRevocationList. -func (c *CertificateAuthorityClient) UpdateCertificateRevocationList(ctx context.Context, req *privatecapb.UpdateCertificateRevocationListRequest, opts ...gax.CallOption) (*UpdateCertificateRevocationListOperation, error) { +func (c *certificateAuthorityGRPCClient) UpdateCertificateRevocationList(ctx context.Context, req *privatecapb.UpdateCertificateRevocationListRequest, opts ...gax.CallOption) (*UpdateCertificateRevocationListOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -901,7 +1110,7 @@ func (c *CertificateAuthorityClient) UpdateCertificateRevocationList(ctx context } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "certificate_revocation_list.name", url.QueryEscape(req.GetCertificateRevocationList().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCertificateRevocationList[0:len(c.CallOptions.UpdateCertificateRevocationList):len(c.CallOptions.UpdateCertificateRevocationList)], opts...) + opts = append((*c.CallOptions).UpdateCertificateRevocationList[0:len((*c.CallOptions).UpdateCertificateRevocationList):len((*c.CallOptions).UpdateCertificateRevocationList)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -912,12 +1121,11 @@ func (c *CertificateAuthorityClient) UpdateCertificateRevocationList(ctx context return nil, err } return &UpdateCertificateRevocationListOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetReusableConfig returns a ReusableConfig. -func (c *CertificateAuthorityClient) GetReusableConfig(ctx context.Context, req *privatecapb.GetReusableConfigRequest, opts ...gax.CallOption) (*privatecapb.ReusableConfig, error) { +func (c *certificateAuthorityGRPCClient) GetReusableConfig(ctx context.Context, req *privatecapb.GetReusableConfigRequest, opts ...gax.CallOption) (*privatecapb.ReusableConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -925,7 +1133,7 @@ func (c *CertificateAuthorityClient) GetReusableConfig(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetReusableConfig[0:len(c.CallOptions.GetReusableConfig):len(c.CallOptions.GetReusableConfig)], opts...) + opts = append((*c.CallOptions).GetReusableConfig[0:len((*c.CallOptions).GetReusableConfig):len((*c.CallOptions).GetReusableConfig)], opts...) var resp *privatecapb.ReusableConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -938,11 +1146,10 @@ func (c *CertificateAuthorityClient) GetReusableConfig(ctx context.Context, req return resp, nil } -// ListReusableConfigs lists ReusableConfigs. -func (c *CertificateAuthorityClient) ListReusableConfigs(ctx context.Context, req *privatecapb.ListReusableConfigsRequest, opts ...gax.CallOption) *ReusableConfigIterator { +func (c *certificateAuthorityGRPCClient) ListReusableConfigs(ctx context.Context, req *privatecapb.ListReusableConfigsRequest, opts ...gax.CallOption) *ReusableConfigIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListReusableConfigs[0:len(c.CallOptions.ListReusableConfigs):len(c.CallOptions.ListReusableConfigs)], opts...) + opts = append((*c.CallOptions).ListReusableConfigs[0:len((*c.CallOptions).ListReusableConfigs):len((*c.CallOptions).ListReusableConfigs)], opts...) it := &ReusableConfigIterator{} req = proto.Clone(req).(*privatecapb.ListReusableConfigsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*privatecapb.ReusableConfig, string, error) { @@ -986,9 +1193,9 @@ type ActivateCertificateAuthorityOperation struct { // ActivateCertificateAuthorityOperation returns a new ActivateCertificateAuthorityOperation from a given name. // The name must be that of a previously created ActivateCertificateAuthorityOperation, possibly from a different process. -func (c *CertificateAuthorityClient) ActivateCertificateAuthorityOperation(name string) *ActivateCertificateAuthorityOperation { +func (c *certificateAuthorityGRPCClient) ActivateCertificateAuthorityOperation(name string) *ActivateCertificateAuthorityOperation { return &ActivateCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1055,9 +1262,9 @@ type CreateCertificateAuthorityOperation struct { // CreateCertificateAuthorityOperation returns a new CreateCertificateAuthorityOperation from a given name. // The name must be that of a previously created CreateCertificateAuthorityOperation, possibly from a different process. -func (c *CertificateAuthorityClient) CreateCertificateAuthorityOperation(name string) *CreateCertificateAuthorityOperation { +func (c *certificateAuthorityGRPCClient) CreateCertificateAuthorityOperation(name string) *CreateCertificateAuthorityOperation { return &CreateCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1124,9 +1331,9 @@ type DisableCertificateAuthorityOperation struct { // DisableCertificateAuthorityOperation returns a new DisableCertificateAuthorityOperation from a given name. // The name must be that of a previously created DisableCertificateAuthorityOperation, possibly from a different process. -func (c *CertificateAuthorityClient) DisableCertificateAuthorityOperation(name string) *DisableCertificateAuthorityOperation { +func (c *certificateAuthorityGRPCClient) DisableCertificateAuthorityOperation(name string) *DisableCertificateAuthorityOperation { return &DisableCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1193,9 +1400,9 @@ type EnableCertificateAuthorityOperation struct { // EnableCertificateAuthorityOperation returns a new EnableCertificateAuthorityOperation from a given name. // The name must be that of a previously created EnableCertificateAuthorityOperation, possibly from a different process. -func (c *CertificateAuthorityClient) EnableCertificateAuthorityOperation(name string) *EnableCertificateAuthorityOperation { +func (c *certificateAuthorityGRPCClient) EnableCertificateAuthorityOperation(name string) *EnableCertificateAuthorityOperation { return &EnableCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1262,9 +1469,9 @@ type RestoreCertificateAuthorityOperation struct { // RestoreCertificateAuthorityOperation returns a new RestoreCertificateAuthorityOperation from a given name. // The name must be that of a previously created RestoreCertificateAuthorityOperation, possibly from a different process. -func (c *CertificateAuthorityClient) RestoreCertificateAuthorityOperation(name string) *RestoreCertificateAuthorityOperation { +func (c *certificateAuthorityGRPCClient) RestoreCertificateAuthorityOperation(name string) *RestoreCertificateAuthorityOperation { return &RestoreCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1331,9 +1538,9 @@ type ScheduleDeleteCertificateAuthorityOperation struct { // ScheduleDeleteCertificateAuthorityOperation returns a new ScheduleDeleteCertificateAuthorityOperation from a given name. // The name must be that of a previously created ScheduleDeleteCertificateAuthorityOperation, possibly from a different process. -func (c *CertificateAuthorityClient) ScheduleDeleteCertificateAuthorityOperation(name string) *ScheduleDeleteCertificateAuthorityOperation { +func (c *certificateAuthorityGRPCClient) ScheduleDeleteCertificateAuthorityOperation(name string) *ScheduleDeleteCertificateAuthorityOperation { return &ScheduleDeleteCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1400,9 +1607,9 @@ type UpdateCertificateAuthorityOperation struct { // UpdateCertificateAuthorityOperation returns a new UpdateCertificateAuthorityOperation from a given name. // The name must be that of a previously created UpdateCertificateAuthorityOperation, possibly from a different process. -func (c *CertificateAuthorityClient) UpdateCertificateAuthorityOperation(name string) *UpdateCertificateAuthorityOperation { +func (c *certificateAuthorityGRPCClient) UpdateCertificateAuthorityOperation(name string) *UpdateCertificateAuthorityOperation { return &UpdateCertificateAuthorityOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1469,9 +1676,9 @@ type UpdateCertificateRevocationListOperation struct { // UpdateCertificateRevocationListOperation returns a new UpdateCertificateRevocationListOperation from a given name. // The name must be that of a previously created UpdateCertificateRevocationListOperation, possibly from a different process. -func (c *CertificateAuthorityClient) UpdateCertificateRevocationListOperation(name string) *UpdateCertificateRevocationListOperation { +func (c *certificateAuthorityGRPCClient) UpdateCertificateRevocationListOperation(name string) *UpdateCertificateRevocationListOperation { return &UpdateCertificateRevocationListOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/security/privateca/apiv1beta1/certificate_authority_client_example_test.go b/security/privateca/apiv1beta1/certificate_authority_client_example_test.go index 3888e6f408d1..af0e19426f69 100644 --- a/security/privateca/apiv1beta1/certificate_authority_client_example_test.go +++ b/security/privateca/apiv1beta1/certificate_authority_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewCertificateAuthorityClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCertificateAuthorityClient_CreateCertificate() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.CreateCertificateRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleCertificateAuthorityClient_CreateCertificate() { } func ExampleCertificateAuthorityClient_GetCertificate() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetCertificateRequest{ // TODO: Fill request struct fields. @@ -75,14 +75,12 @@ func ExampleCertificateAuthorityClient_GetCertificate() { } func ExampleCertificateAuthorityClient_ListCertificates() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListCertificatesRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleCertificateAuthorityClient_ListCertificates() { } func ExampleCertificateAuthorityClient_RevokeCertificate() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.RevokeCertificateRequest{ // TODO: Fill request struct fields. @@ -122,13 +119,12 @@ func ExampleCertificateAuthorityClient_RevokeCertificate() { } func ExampleCertificateAuthorityClient_UpdateCertificate() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UpdateCertificateRequest{ // TODO: Fill request struct fields. @@ -142,13 +138,12 @@ func ExampleCertificateAuthorityClient_UpdateCertificate() { } func ExampleCertificateAuthorityClient_ActivateCertificateAuthority() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ActivateCertificateAuthorityRequest{ // TODO: Fill request struct fields. @@ -167,13 +162,12 @@ func ExampleCertificateAuthorityClient_ActivateCertificateAuthority() { } func ExampleCertificateAuthorityClient_CreateCertificateAuthority() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.CreateCertificateAuthorityRequest{ // TODO: Fill request struct fields. @@ -192,13 +186,12 @@ func ExampleCertificateAuthorityClient_CreateCertificateAuthority() { } func ExampleCertificateAuthorityClient_DisableCertificateAuthority() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.DisableCertificateAuthorityRequest{ // TODO: Fill request struct fields. @@ -217,13 +210,12 @@ func ExampleCertificateAuthorityClient_DisableCertificateAuthority() { } func ExampleCertificateAuthorityClient_EnableCertificateAuthority() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.EnableCertificateAuthorityRequest{ // TODO: Fill request struct fields. @@ -242,13 +234,12 @@ func ExampleCertificateAuthorityClient_EnableCertificateAuthority() { } func ExampleCertificateAuthorityClient_FetchCertificateAuthorityCsr() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.FetchCertificateAuthorityCsrRequest{ // TODO: Fill request struct fields. @@ -262,13 +253,12 @@ func ExampleCertificateAuthorityClient_FetchCertificateAuthorityCsr() { } func ExampleCertificateAuthorityClient_GetCertificateAuthority() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetCertificateAuthorityRequest{ // TODO: Fill request struct fields. @@ -282,14 +272,12 @@ func ExampleCertificateAuthorityClient_GetCertificateAuthority() { } func ExampleCertificateAuthorityClient_ListCertificateAuthorities() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListCertificateAuthoritiesRequest{ // TODO: Fill request struct fields. @@ -309,13 +297,12 @@ func ExampleCertificateAuthorityClient_ListCertificateAuthorities() { } func ExampleCertificateAuthorityClient_RestoreCertificateAuthority() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.RestoreCertificateAuthorityRequest{ // TODO: Fill request struct fields. @@ -334,13 +321,12 @@ func ExampleCertificateAuthorityClient_RestoreCertificateAuthority() { } func ExampleCertificateAuthorityClient_ScheduleDeleteCertificateAuthority() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ScheduleDeleteCertificateAuthorityRequest{ // TODO: Fill request struct fields. @@ -359,13 +345,12 @@ func ExampleCertificateAuthorityClient_ScheduleDeleteCertificateAuthority() { } func ExampleCertificateAuthorityClient_UpdateCertificateAuthority() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UpdateCertificateAuthorityRequest{ // TODO: Fill request struct fields. @@ -384,13 +369,12 @@ func ExampleCertificateAuthorityClient_UpdateCertificateAuthority() { } func ExampleCertificateAuthorityClient_GetCertificateRevocationList() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetCertificateRevocationListRequest{ // TODO: Fill request struct fields. @@ -404,14 +388,12 @@ func ExampleCertificateAuthorityClient_GetCertificateRevocationList() { } func ExampleCertificateAuthorityClient_ListCertificateRevocationLists() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListCertificateRevocationListsRequest{ // TODO: Fill request struct fields. @@ -431,13 +413,12 @@ func ExampleCertificateAuthorityClient_ListCertificateRevocationLists() { } func ExampleCertificateAuthorityClient_UpdateCertificateRevocationList() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.UpdateCertificateRevocationListRequest{ // TODO: Fill request struct fields. @@ -456,13 +437,12 @@ func ExampleCertificateAuthorityClient_UpdateCertificateRevocationList() { } func ExampleCertificateAuthorityClient_GetReusableConfig() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.GetReusableConfigRequest{ // TODO: Fill request struct fields. @@ -476,14 +456,12 @@ func ExampleCertificateAuthorityClient_GetReusableConfig() { } func ExampleCertificateAuthorityClient_ListReusableConfigs() { - // import privatecapb "google.golang.org/genproto/googleapis/cloud/security/privateca/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := privateca.NewCertificateAuthorityClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &privatecapb.ListReusableConfigsRequest{ // TODO: Fill request struct fields. diff --git a/security/privateca/apiv1beta1/doc.go b/security/privateca/apiv1beta1/doc.go index 5bf24ff96a27..518665ca6025 100644 --- a/security/privateca/apiv1beta1/doc.go +++ b/security/privateca/apiv1beta1/doc.go @@ -17,6 +17,8 @@ // Package privateca is an auto-generated package for the // Certificate Authority API. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -26,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package privateca // import "cloud.google.com/go/security/privateca/apiv1beta1" import ( @@ -46,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/securitycenter/apiv1/doc.go b/securitycenter/apiv1/doc.go index 778d9d8265e5..c00d54e2ad72 100644 --- a/securitycenter/apiv1/doc.go +++ b/securitycenter/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package securitycenter // import "cloud.google.com/go/securitycenter/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/securitycenter/apiv1/security_center_client.go b/securitycenter/apiv1/security_center_client.go index d48f73e0e4ef..2ae7da959146 100644 --- a/securitycenter/apiv1/security_center_client.go +++ b/securitycenter/apiv1/security_center_client.go @@ -69,7 +69,7 @@ type CallOptions struct { UpdateSecurityMarks []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("securitycenter.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("securitycenter.mtls.googleapis.com:443"), @@ -230,37 +230,246 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Security Command Center API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateSource(context.Context, *securitycenterpb.CreateSourceRequest, ...gax.CallOption) (*securitycenterpb.Source, error) + CreateFinding(context.Context, *securitycenterpb.CreateFindingRequest, ...gax.CallOption) (*securitycenterpb.Finding, error) + CreateNotificationConfig(context.Context, *securitycenterpb.CreateNotificationConfigRequest, ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) + DeleteNotificationConfig(context.Context, *securitycenterpb.DeleteNotificationConfigRequest, ...gax.CallOption) error + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + GetNotificationConfig(context.Context, *securitycenterpb.GetNotificationConfigRequest, ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) + GetOrganizationSettings(context.Context, *securitycenterpb.GetOrganizationSettingsRequest, ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) + GetSource(context.Context, *securitycenterpb.GetSourceRequest, ...gax.CallOption) (*securitycenterpb.Source, error) + GroupAssets(context.Context, *securitycenterpb.GroupAssetsRequest, ...gax.CallOption) *GroupResultIterator + GroupFindings(context.Context, *securitycenterpb.GroupFindingsRequest, ...gax.CallOption) *GroupResultIterator + ListAssets(context.Context, *securitycenterpb.ListAssetsRequest, ...gax.CallOption) *ListAssetsResponse_ListAssetsResultIterator + ListFindings(context.Context, *securitycenterpb.ListFindingsRequest, ...gax.CallOption) *ListFindingsResponse_ListFindingsResultIterator + ListNotificationConfigs(context.Context, *securitycenterpb.ListNotificationConfigsRequest, ...gax.CallOption) *NotificationConfigIterator + ListSources(context.Context, *securitycenterpb.ListSourcesRequest, ...gax.CallOption) *SourceIterator + RunAssetDiscovery(context.Context, *securitycenterpb.RunAssetDiscoveryRequest, ...gax.CallOption) (*RunAssetDiscoveryOperation, error) + RunAssetDiscoveryOperation(name string) *RunAssetDiscoveryOperation + SetFindingState(context.Context, *securitycenterpb.SetFindingStateRequest, ...gax.CallOption) (*securitycenterpb.Finding, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) + UpdateFinding(context.Context, *securitycenterpb.UpdateFindingRequest, ...gax.CallOption) (*securitycenterpb.Finding, error) + UpdateNotificationConfig(context.Context, *securitycenterpb.UpdateNotificationConfigRequest, ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) + UpdateOrganizationSettings(context.Context, *securitycenterpb.UpdateOrganizationSettingsRequest, ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) + UpdateSource(context.Context, *securitycenterpb.UpdateSourceRequest, ...gax.CallOption) (*securitycenterpb.Source, error) + UpdateSecurityMarks(context.Context, *securitycenterpb.UpdateSecurityMarksRequest, ...gax.CallOption) (*securitycenterpb.SecurityMarks, error) +} + // Client is a client for interacting with Security Command Center API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// V1 APIs for Security Center service. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateSource creates a source. +func (c *Client) CreateSource(ctx context.Context, req *securitycenterpb.CreateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { + return c.internalClient.CreateSource(ctx, req, opts...) +} + +// CreateFinding creates a finding. The corresponding source must exist for finding creation +// to succeed. +func (c *Client) CreateFinding(ctx context.Context, req *securitycenterpb.CreateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { + return c.internalClient.CreateFinding(ctx, req, opts...) +} + +// CreateNotificationConfig creates a notification config. +func (c *Client) CreateNotificationConfig(ctx context.Context, req *securitycenterpb.CreateNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { + return c.internalClient.CreateNotificationConfig(ctx, req, opts...) +} + +// DeleteNotificationConfig deletes a notification config. +func (c *Client) DeleteNotificationConfig(ctx context.Context, req *securitycenterpb.DeleteNotificationConfigRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteNotificationConfig(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy on the specified Source. +func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// GetNotificationConfig gets a notification config. +func (c *Client) GetNotificationConfig(ctx context.Context, req *securitycenterpb.GetNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { + return c.internalClient.GetNotificationConfig(ctx, req, opts...) +} + +// GetOrganizationSettings gets the settings for an organization. +func (c *Client) GetOrganizationSettings(ctx context.Context, req *securitycenterpb.GetOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { + return c.internalClient.GetOrganizationSettings(ctx, req, opts...) +} + +// GetSource gets a source. +func (c *Client) GetSource(ctx context.Context, req *securitycenterpb.GetSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { + return c.internalClient.GetSource(ctx, req, opts...) +} + +// GroupAssets filters an organization’s assets and groups them by their specified +// properties. +func (c *Client) GroupAssets(ctx context.Context, req *securitycenterpb.GroupAssetsRequest, opts ...gax.CallOption) *GroupResultIterator { + return c.internalClient.GroupAssets(ctx, req, opts...) +} + +// GroupFindings filters an organization or source’s findings and groups them by their +// specified properties. +// +// To group across all sources provide a - as the source id. +// Example: /v1/organizations/{organization_id}/sources/-/findings, +// /v1/folders/{folder_id}/sources/-/findings, +// /v1/projects/{project_id}/sources/-/findings +func (c *Client) GroupFindings(ctx context.Context, req *securitycenterpb.GroupFindingsRequest, opts ...gax.CallOption) *GroupResultIterator { + return c.internalClient.GroupFindings(ctx, req, opts...) +} + +// ListAssets lists an organization’s assets. +func (c *Client) ListAssets(ctx context.Context, req *securitycenterpb.ListAssetsRequest, opts ...gax.CallOption) *ListAssetsResponse_ListAssetsResultIterator { + return c.internalClient.ListAssets(ctx, req, opts...) +} + +// ListFindings lists an organization or source’s findings. +// +// To list across all sources provide a - as the source id. +// Example: /v1/organizations/{organization_id}/sources/-/findings +func (c *Client) ListFindings(ctx context.Context, req *securitycenterpb.ListFindingsRequest, opts ...gax.CallOption) *ListFindingsResponse_ListFindingsResultIterator { + return c.internalClient.ListFindings(ctx, req, opts...) +} + +// ListNotificationConfigs lists notification configs. +func (c *Client) ListNotificationConfigs(ctx context.Context, req *securitycenterpb.ListNotificationConfigsRequest, opts ...gax.CallOption) *NotificationConfigIterator { + return c.internalClient.ListNotificationConfigs(ctx, req, opts...) +} + +// ListSources lists all sources belonging to an organization. +func (c *Client) ListSources(ctx context.Context, req *securitycenterpb.ListSourcesRequest, opts ...gax.CallOption) *SourceIterator { + return c.internalClient.ListSources(ctx, req, opts...) +} + +// RunAssetDiscovery runs asset discovery. The discovery is tracked with a long-running +// operation. +// +// This API can only be called with limited frequency for an organization. If +// it is called too frequently the caller will receive a TOO_MANY_REQUESTS +// error. +func (c *Client) RunAssetDiscovery(ctx context.Context, req *securitycenterpb.RunAssetDiscoveryRequest, opts ...gax.CallOption) (*RunAssetDiscoveryOperation, error) { + return c.internalClient.RunAssetDiscovery(ctx, req, opts...) +} + +// RunAssetDiscoveryOperation returns a new RunAssetDiscoveryOperation from a given name. +// The name must be that of a previously created RunAssetDiscoveryOperation, possibly from a different process. +func (c *Client) RunAssetDiscoveryOperation(name string) *RunAssetDiscoveryOperation { + return c.internalClient.RunAssetDiscoveryOperation(name) +} + +// SetFindingState updates the state of a finding. +func (c *Client) SetFindingState(ctx context.Context, req *securitycenterpb.SetFindingStateRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { + return c.internalClient.SetFindingState(ctx, req, opts...) +} + +// SetIamPolicy sets the access control policy on the specified Source. +func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns the permissions that a caller has on the specified source. +func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// UpdateFinding creates or updates a finding. The corresponding source must exist for a +// finding creation to succeed. +func (c *Client) UpdateFinding(ctx context.Context, req *securitycenterpb.UpdateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { + return c.internalClient.UpdateFinding(ctx, req, opts...) +} + +// UpdateNotificationConfig updates a notification config. The following update +// fields are allowed: description, pubsub_topic, streaming_config.filter +func (c *Client) UpdateNotificationConfig(ctx context.Context, req *securitycenterpb.UpdateNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { + return c.internalClient.UpdateNotificationConfig(ctx, req, opts...) +} + +// UpdateOrganizationSettings updates an organization’s settings. +func (c *Client) UpdateOrganizationSettings(ctx context.Context, req *securitycenterpb.UpdateOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { + return c.internalClient.UpdateOrganizationSettings(ctx, req, opts...) +} + +// UpdateSource updates a source. +func (c *Client) UpdateSource(ctx context.Context, req *securitycenterpb.UpdateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { + return c.internalClient.UpdateSource(ctx, req, opts...) +} + +// UpdateSecurityMarks updates security marks. +func (c *Client) UpdateSecurityMarks(ctx context.Context, req *securitycenterpb.UpdateSecurityMarksRequest, opts ...gax.CallOption) (*securitycenterpb.SecurityMarks, error) { + return c.internalClient.UpdateSecurityMarks(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Security Command Center API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client securitycenterpb.SecurityCenterClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new security center client. +// NewClient creates a new security center client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // V1 APIs for Security Center service. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -278,16 +487,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: securitycenterpb.NewSecurityCenterClient(connPool), + client: securitycenterpb.NewSecurityCenterClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -297,33 +509,33 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateSource creates a source. -func (c *Client) CreateSource(ctx context.Context, req *securitycenterpb.CreateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateSource(ctx context.Context, req *securitycenterpb.CreateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -331,7 +543,7 @@ func (c *Client) CreateSource(ctx context.Context, req *securitycenterpb.CreateS } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSource[0:len(c.CallOptions.CreateSource):len(c.CallOptions.CreateSource)], opts...) + opts = append((*c.CallOptions).CreateSource[0:len((*c.CallOptions).CreateSource):len((*c.CallOptions).CreateSource)], opts...) var resp *securitycenterpb.Source err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -344,9 +556,7 @@ func (c *Client) CreateSource(ctx context.Context, req *securitycenterpb.CreateS return resp, nil } -// CreateFinding creates a finding. The corresponding source must exist for finding creation -// to succeed. -func (c *Client) CreateFinding(ctx context.Context, req *securitycenterpb.CreateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { +func (c *gRPCClient) CreateFinding(ctx context.Context, req *securitycenterpb.CreateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -354,7 +564,7 @@ func (c *Client) CreateFinding(ctx context.Context, req *securitycenterpb.Create } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateFinding[0:len(c.CallOptions.CreateFinding):len(c.CallOptions.CreateFinding)], opts...) + opts = append((*c.CallOptions).CreateFinding[0:len((*c.CallOptions).CreateFinding):len((*c.CallOptions).CreateFinding)], opts...) var resp *securitycenterpb.Finding err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -367,8 +577,7 @@ func (c *Client) CreateFinding(ctx context.Context, req *securitycenterpb.Create return resp, nil } -// CreateNotificationConfig creates a notification config. -func (c *Client) CreateNotificationConfig(ctx context.Context, req *securitycenterpb.CreateNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { +func (c *gRPCClient) CreateNotificationConfig(ctx context.Context, req *securitycenterpb.CreateNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -376,7 +585,7 @@ func (c *Client) CreateNotificationConfig(ctx context.Context, req *securitycent } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateNotificationConfig[0:len(c.CallOptions.CreateNotificationConfig):len(c.CallOptions.CreateNotificationConfig)], opts...) + opts = append((*c.CallOptions).CreateNotificationConfig[0:len((*c.CallOptions).CreateNotificationConfig):len((*c.CallOptions).CreateNotificationConfig)], opts...) var resp *securitycenterpb.NotificationConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -389,8 +598,7 @@ func (c *Client) CreateNotificationConfig(ctx context.Context, req *securitycent return resp, nil } -// DeleteNotificationConfig deletes a notification config. -func (c *Client) DeleteNotificationConfig(ctx context.Context, req *securitycenterpb.DeleteNotificationConfigRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteNotificationConfig(ctx context.Context, req *securitycenterpb.DeleteNotificationConfigRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -398,7 +606,7 @@ func (c *Client) DeleteNotificationConfig(ctx context.Context, req *securitycent } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteNotificationConfig[0:len(c.CallOptions.DeleteNotificationConfig):len(c.CallOptions.DeleteNotificationConfig)], opts...) + opts = append((*c.CallOptions).DeleteNotificationConfig[0:len((*c.CallOptions).DeleteNotificationConfig):len((*c.CallOptions).DeleteNotificationConfig)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteNotificationConfig(ctx, req, settings.GRPC...) @@ -407,8 +615,7 @@ func (c *Client) DeleteNotificationConfig(ctx context.Context, req *securitycent return err } -// GetIamPolicy gets the access control policy on the specified Source. -func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -416,7 +623,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -429,8 +636,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques return resp, nil } -// GetNotificationConfig gets a notification config. -func (c *Client) GetNotificationConfig(ctx context.Context, req *securitycenterpb.GetNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { +func (c *gRPCClient) GetNotificationConfig(ctx context.Context, req *securitycenterpb.GetNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -438,7 +644,7 @@ func (c *Client) GetNotificationConfig(ctx context.Context, req *securitycenterp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetNotificationConfig[0:len(c.CallOptions.GetNotificationConfig):len(c.CallOptions.GetNotificationConfig)], opts...) + opts = append((*c.CallOptions).GetNotificationConfig[0:len((*c.CallOptions).GetNotificationConfig):len((*c.CallOptions).GetNotificationConfig)], opts...) var resp *securitycenterpb.NotificationConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -451,8 +657,7 @@ func (c *Client) GetNotificationConfig(ctx context.Context, req *securitycenterp return resp, nil } -// GetOrganizationSettings gets the settings for an organization. -func (c *Client) GetOrganizationSettings(ctx context.Context, req *securitycenterpb.GetOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { +func (c *gRPCClient) GetOrganizationSettings(ctx context.Context, req *securitycenterpb.GetOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -460,7 +665,7 @@ func (c *Client) GetOrganizationSettings(ctx context.Context, req *securitycente } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetOrganizationSettings[0:len(c.CallOptions.GetOrganizationSettings):len(c.CallOptions.GetOrganizationSettings)], opts...) + opts = append((*c.CallOptions).GetOrganizationSettings[0:len((*c.CallOptions).GetOrganizationSettings):len((*c.CallOptions).GetOrganizationSettings)], opts...) var resp *securitycenterpb.OrganizationSettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -473,8 +678,7 @@ func (c *Client) GetOrganizationSettings(ctx context.Context, req *securitycente return resp, nil } -// GetSource gets a source. -func (c *Client) GetSource(ctx context.Context, req *securitycenterpb.GetSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { +func (c *gRPCClient) GetSource(ctx context.Context, req *securitycenterpb.GetSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -482,7 +686,7 @@ func (c *Client) GetSource(ctx context.Context, req *securitycenterpb.GetSourceR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSource[0:len(c.CallOptions.GetSource):len(c.CallOptions.GetSource)], opts...) + opts = append((*c.CallOptions).GetSource[0:len((*c.CallOptions).GetSource):len((*c.CallOptions).GetSource)], opts...) var resp *securitycenterpb.Source err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -495,12 +699,10 @@ func (c *Client) GetSource(ctx context.Context, req *securitycenterpb.GetSourceR return resp, nil } -// GroupAssets filters an organization’s assets and groups them by their specified -// properties. -func (c *Client) GroupAssets(ctx context.Context, req *securitycenterpb.GroupAssetsRequest, opts ...gax.CallOption) *GroupResultIterator { +func (c *gRPCClient) GroupAssets(ctx context.Context, req *securitycenterpb.GroupAssetsRequest, opts ...gax.CallOption) *GroupResultIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GroupAssets[0:len(c.CallOptions.GroupAssets):len(c.CallOptions.GroupAssets)], opts...) + opts = append((*c.CallOptions).GroupAssets[0:len((*c.CallOptions).GroupAssets):len((*c.CallOptions).GroupAssets)], opts...) it := &GroupResultIterator{} req = proto.Clone(req).(*securitycenterpb.GroupAssetsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.GroupResult, string, error) { @@ -537,17 +739,10 @@ func (c *Client) GroupAssets(ctx context.Context, req *securitycenterpb.GroupAss return it } -// GroupFindings filters an organization or source’s findings and groups them by their -// specified properties. -// -// To group across all sources provide a - as the source id. -// Example: /v1/organizations/{organization_id}/sources/-/findings, -// /v1/folders/{folder_id}/sources/-/findings, -// /v1/projects/{project_id}/sources/-/findings -func (c *Client) GroupFindings(ctx context.Context, req *securitycenterpb.GroupFindingsRequest, opts ...gax.CallOption) *GroupResultIterator { +func (c *gRPCClient) GroupFindings(ctx context.Context, req *securitycenterpb.GroupFindingsRequest, opts ...gax.CallOption) *GroupResultIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GroupFindings[0:len(c.CallOptions.GroupFindings):len(c.CallOptions.GroupFindings)], opts...) + opts = append((*c.CallOptions).GroupFindings[0:len((*c.CallOptions).GroupFindings):len((*c.CallOptions).GroupFindings)], opts...) it := &GroupResultIterator{} req = proto.Clone(req).(*securitycenterpb.GroupFindingsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.GroupResult, string, error) { @@ -584,11 +779,10 @@ func (c *Client) GroupFindings(ctx context.Context, req *securitycenterpb.GroupF return it } -// ListAssets lists an organization’s assets. -func (c *Client) ListAssets(ctx context.Context, req *securitycenterpb.ListAssetsRequest, opts ...gax.CallOption) *ListAssetsResponse_ListAssetsResultIterator { +func (c *gRPCClient) ListAssets(ctx context.Context, req *securitycenterpb.ListAssetsRequest, opts ...gax.CallOption) *ListAssetsResponse_ListAssetsResultIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAssets[0:len(c.CallOptions.ListAssets):len(c.CallOptions.ListAssets)], opts...) + opts = append((*c.CallOptions).ListAssets[0:len((*c.CallOptions).ListAssets):len((*c.CallOptions).ListAssets)], opts...) it := &ListAssetsResponse_ListAssetsResultIterator{} req = proto.Clone(req).(*securitycenterpb.ListAssetsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.ListAssetsResponse_ListAssetsResult, string, error) { @@ -625,14 +819,10 @@ func (c *Client) ListAssets(ctx context.Context, req *securitycenterpb.ListAsset return it } -// ListFindings lists an organization or source’s findings. -// -// To list across all sources provide a - as the source id. -// Example: /v1/organizations/{organization_id}/sources/-/findings -func (c *Client) ListFindings(ctx context.Context, req *securitycenterpb.ListFindingsRequest, opts ...gax.CallOption) *ListFindingsResponse_ListFindingsResultIterator { +func (c *gRPCClient) ListFindings(ctx context.Context, req *securitycenterpb.ListFindingsRequest, opts ...gax.CallOption) *ListFindingsResponse_ListFindingsResultIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListFindings[0:len(c.CallOptions.ListFindings):len(c.CallOptions.ListFindings)], opts...) + opts = append((*c.CallOptions).ListFindings[0:len((*c.CallOptions).ListFindings):len((*c.CallOptions).ListFindings)], opts...) it := &ListFindingsResponse_ListFindingsResultIterator{} req = proto.Clone(req).(*securitycenterpb.ListFindingsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.ListFindingsResponse_ListFindingsResult, string, error) { @@ -669,11 +859,10 @@ func (c *Client) ListFindings(ctx context.Context, req *securitycenterpb.ListFin return it } -// ListNotificationConfigs lists notification configs. -func (c *Client) ListNotificationConfigs(ctx context.Context, req *securitycenterpb.ListNotificationConfigsRequest, opts ...gax.CallOption) *NotificationConfigIterator { +func (c *gRPCClient) ListNotificationConfigs(ctx context.Context, req *securitycenterpb.ListNotificationConfigsRequest, opts ...gax.CallOption) *NotificationConfigIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListNotificationConfigs[0:len(c.CallOptions.ListNotificationConfigs):len(c.CallOptions.ListNotificationConfigs)], opts...) + opts = append((*c.CallOptions).ListNotificationConfigs[0:len((*c.CallOptions).ListNotificationConfigs):len((*c.CallOptions).ListNotificationConfigs)], opts...) it := &NotificationConfigIterator{} req = proto.Clone(req).(*securitycenterpb.ListNotificationConfigsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.NotificationConfig, string, error) { @@ -710,11 +899,10 @@ func (c *Client) ListNotificationConfigs(ctx context.Context, req *securitycente return it } -// ListSources lists all sources belonging to an organization. -func (c *Client) ListSources(ctx context.Context, req *securitycenterpb.ListSourcesRequest, opts ...gax.CallOption) *SourceIterator { +func (c *gRPCClient) ListSources(ctx context.Context, req *securitycenterpb.ListSourcesRequest, opts ...gax.CallOption) *SourceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSources[0:len(c.CallOptions.ListSources):len(c.CallOptions.ListSources)], opts...) + opts = append((*c.CallOptions).ListSources[0:len((*c.CallOptions).ListSources):len((*c.CallOptions).ListSources)], opts...) it := &SourceIterator{} req = proto.Clone(req).(*securitycenterpb.ListSourcesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.Source, string, error) { @@ -751,13 +939,7 @@ func (c *Client) ListSources(ctx context.Context, req *securitycenterpb.ListSour return it } -// RunAssetDiscovery runs asset discovery. The discovery is tracked with a long-running -// operation. -// -// This API can only be called with limited frequency for an organization. If -// it is called too frequently the caller will receive a TOO_MANY_REQUESTS -// error. -func (c *Client) RunAssetDiscovery(ctx context.Context, req *securitycenterpb.RunAssetDiscoveryRequest, opts ...gax.CallOption) (*RunAssetDiscoveryOperation, error) { +func (c *gRPCClient) RunAssetDiscovery(ctx context.Context, req *securitycenterpb.RunAssetDiscoveryRequest, opts ...gax.CallOption) (*RunAssetDiscoveryOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -765,7 +947,7 @@ func (c *Client) RunAssetDiscovery(ctx context.Context, req *securitycenterpb.Ru } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RunAssetDiscovery[0:len(c.CallOptions.RunAssetDiscovery):len(c.CallOptions.RunAssetDiscovery)], opts...) + opts = append((*c.CallOptions).RunAssetDiscovery[0:len((*c.CallOptions).RunAssetDiscovery):len((*c.CallOptions).RunAssetDiscovery)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -776,12 +958,11 @@ func (c *Client) RunAssetDiscovery(ctx context.Context, req *securitycenterpb.Ru return nil, err } return &RunAssetDiscoveryOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// SetFindingState updates the state of a finding. -func (c *Client) SetFindingState(ctx context.Context, req *securitycenterpb.SetFindingStateRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { +func (c *gRPCClient) SetFindingState(ctx context.Context, req *securitycenterpb.SetFindingStateRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -789,7 +970,7 @@ func (c *Client) SetFindingState(ctx context.Context, req *securitycenterpb.SetF } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetFindingState[0:len(c.CallOptions.SetFindingState):len(c.CallOptions.SetFindingState)], opts...) + opts = append((*c.CallOptions).SetFindingState[0:len((*c.CallOptions).SetFindingState):len((*c.CallOptions).SetFindingState)], opts...) var resp *securitycenterpb.Finding err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -802,8 +983,7 @@ func (c *Client) SetFindingState(ctx context.Context, req *securitycenterpb.SetF return resp, nil } -// SetIamPolicy sets the access control policy on the specified Source. -func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -811,7 +991,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -824,8 +1004,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques return resp, nil } -// TestIamPermissions returns the permissions that a caller has on the specified source. -func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *gRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -833,7 +1012,7 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -846,9 +1025,7 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi return resp, nil } -// UpdateFinding creates or updates a finding. The corresponding source must exist for a -// finding creation to succeed. -func (c *Client) UpdateFinding(ctx context.Context, req *securitycenterpb.UpdateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { +func (c *gRPCClient) UpdateFinding(ctx context.Context, req *securitycenterpb.UpdateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -856,7 +1033,7 @@ func (c *Client) UpdateFinding(ctx context.Context, req *securitycenterpb.Update } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "finding.name", url.QueryEscape(req.GetFinding().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateFinding[0:len(c.CallOptions.UpdateFinding):len(c.CallOptions.UpdateFinding)], opts...) + opts = append((*c.CallOptions).UpdateFinding[0:len((*c.CallOptions).UpdateFinding):len((*c.CallOptions).UpdateFinding)], opts...) var resp *securitycenterpb.Finding err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -869,9 +1046,7 @@ func (c *Client) UpdateFinding(ctx context.Context, req *securitycenterpb.Update return resp, nil } -// UpdateNotificationConfig updates a notification config. The following update -// fields are allowed: description, pubsub_topic, streaming_config.filter -func (c *Client) UpdateNotificationConfig(ctx context.Context, req *securitycenterpb.UpdateNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { +func (c *gRPCClient) UpdateNotificationConfig(ctx context.Context, req *securitycenterpb.UpdateNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -879,7 +1054,7 @@ func (c *Client) UpdateNotificationConfig(ctx context.Context, req *securitycent } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "notification_config.name", url.QueryEscape(req.GetNotificationConfig().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateNotificationConfig[0:len(c.CallOptions.UpdateNotificationConfig):len(c.CallOptions.UpdateNotificationConfig)], opts...) + opts = append((*c.CallOptions).UpdateNotificationConfig[0:len((*c.CallOptions).UpdateNotificationConfig):len((*c.CallOptions).UpdateNotificationConfig)], opts...) var resp *securitycenterpb.NotificationConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -892,8 +1067,7 @@ func (c *Client) UpdateNotificationConfig(ctx context.Context, req *securitycent return resp, nil } -// UpdateOrganizationSettings updates an organization’s settings. -func (c *Client) UpdateOrganizationSettings(ctx context.Context, req *securitycenterpb.UpdateOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { +func (c *gRPCClient) UpdateOrganizationSettings(ctx context.Context, req *securitycenterpb.UpdateOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -901,7 +1075,7 @@ func (c *Client) UpdateOrganizationSettings(ctx context.Context, req *securityce } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "organization_settings.name", url.QueryEscape(req.GetOrganizationSettings().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateOrganizationSettings[0:len(c.CallOptions.UpdateOrganizationSettings):len(c.CallOptions.UpdateOrganizationSettings)], opts...) + opts = append((*c.CallOptions).UpdateOrganizationSettings[0:len((*c.CallOptions).UpdateOrganizationSettings):len((*c.CallOptions).UpdateOrganizationSettings)], opts...) var resp *securitycenterpb.OrganizationSettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -914,8 +1088,7 @@ func (c *Client) UpdateOrganizationSettings(ctx context.Context, req *securityce return resp, nil } -// UpdateSource updates a source. -func (c *Client) UpdateSource(ctx context.Context, req *securitycenterpb.UpdateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { +func (c *gRPCClient) UpdateSource(ctx context.Context, req *securitycenterpb.UpdateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -923,7 +1096,7 @@ func (c *Client) UpdateSource(ctx context.Context, req *securitycenterpb.UpdateS } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "source.name", url.QueryEscape(req.GetSource().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSource[0:len(c.CallOptions.UpdateSource):len(c.CallOptions.UpdateSource)], opts...) + opts = append((*c.CallOptions).UpdateSource[0:len((*c.CallOptions).UpdateSource):len((*c.CallOptions).UpdateSource)], opts...) var resp *securitycenterpb.Source err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -936,8 +1109,7 @@ func (c *Client) UpdateSource(ctx context.Context, req *securitycenterpb.UpdateS return resp, nil } -// UpdateSecurityMarks updates security marks. -func (c *Client) UpdateSecurityMarks(ctx context.Context, req *securitycenterpb.UpdateSecurityMarksRequest, opts ...gax.CallOption) (*securitycenterpb.SecurityMarks, error) { +func (c *gRPCClient) UpdateSecurityMarks(ctx context.Context, req *securitycenterpb.UpdateSecurityMarksRequest, opts ...gax.CallOption) (*securitycenterpb.SecurityMarks, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 480000*time.Millisecond) defer cancel() @@ -945,7 +1117,7 @@ func (c *Client) UpdateSecurityMarks(ctx context.Context, req *securitycenterpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "security_marks.name", url.QueryEscape(req.GetSecurityMarks().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSecurityMarks[0:len(c.CallOptions.UpdateSecurityMarks):len(c.CallOptions.UpdateSecurityMarks)], opts...) + opts = append((*c.CallOptions).UpdateSecurityMarks[0:len((*c.CallOptions).UpdateSecurityMarks):len((*c.CallOptions).UpdateSecurityMarks)], opts...) var resp *securitycenterpb.SecurityMarks err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -965,9 +1137,9 @@ type RunAssetDiscoveryOperation struct { // RunAssetDiscoveryOperation returns a new RunAssetDiscoveryOperation from a given name. // The name must be that of a previously created RunAssetDiscoveryOperation, possibly from a different process. -func (c *Client) RunAssetDiscoveryOperation(name string) *RunAssetDiscoveryOperation { +func (c *gRPCClient) RunAssetDiscoveryOperation(name string) *RunAssetDiscoveryOperation { return &RunAssetDiscoveryOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/securitycenter/apiv1/security_center_client_example_test.go b/securitycenter/apiv1/security_center_client_example_test.go index de6eefe50bb2..ce1d06de7a92 100644 --- a/securitycenter/apiv1/security_center_client_example_test.go +++ b/securitycenter/apiv1/security_center_client_example_test.go @@ -31,18 +31,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateSource() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.CreateSourceRequest{ // TODO: Fill request struct fields. @@ -56,13 +57,12 @@ func ExampleClient_CreateSource() { } func ExampleClient_CreateFinding() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.CreateFindingRequest{ // TODO: Fill request struct fields. @@ -76,13 +76,12 @@ func ExampleClient_CreateFinding() { } func ExampleClient_CreateNotificationConfig() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.CreateNotificationConfigRequest{ // TODO: Fill request struct fields. @@ -101,6 +100,7 @@ func ExampleClient_DeleteNotificationConfig() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.DeleteNotificationConfigRequest{ // TODO: Fill request struct fields. @@ -112,13 +112,12 @@ func ExampleClient_DeleteNotificationConfig() { } func ExampleClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -132,13 +131,12 @@ func ExampleClient_GetIamPolicy() { } func ExampleClient_GetNotificationConfig() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GetNotificationConfigRequest{ // TODO: Fill request struct fields. @@ -152,13 +150,12 @@ func ExampleClient_GetNotificationConfig() { } func ExampleClient_GetOrganizationSettings() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GetOrganizationSettingsRequest{ // TODO: Fill request struct fields. @@ -172,13 +169,12 @@ func ExampleClient_GetOrganizationSettings() { } func ExampleClient_GetSource() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GetSourceRequest{ // TODO: Fill request struct fields. @@ -192,14 +188,12 @@ func ExampleClient_GetSource() { } func ExampleClient_GroupAssets() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GroupAssetsRequest{ // TODO: Fill request struct fields. @@ -219,14 +213,12 @@ func ExampleClient_GroupAssets() { } func ExampleClient_GroupFindings() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GroupFindingsRequest{ // TODO: Fill request struct fields. @@ -246,14 +238,12 @@ func ExampleClient_GroupFindings() { } func ExampleClient_ListAssets() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListAssetsRequest{ // TODO: Fill request struct fields. @@ -273,14 +263,12 @@ func ExampleClient_ListAssets() { } func ExampleClient_ListFindings() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListFindingsRequest{ // TODO: Fill request struct fields. @@ -300,14 +288,12 @@ func ExampleClient_ListFindings() { } func ExampleClient_ListNotificationConfigs() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListNotificationConfigsRequest{ // TODO: Fill request struct fields. @@ -327,14 +313,12 @@ func ExampleClient_ListNotificationConfigs() { } func ExampleClient_ListSources() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListSourcesRequest{ // TODO: Fill request struct fields. @@ -354,13 +338,12 @@ func ExampleClient_ListSources() { } func ExampleClient_RunAssetDiscovery() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.RunAssetDiscoveryRequest{ // TODO: Fill request struct fields. @@ -379,13 +362,12 @@ func ExampleClient_RunAssetDiscovery() { } func ExampleClient_SetFindingState() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.SetFindingStateRequest{ // TODO: Fill request struct fields. @@ -399,13 +381,12 @@ func ExampleClient_SetFindingState() { } func ExampleClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -419,13 +400,12 @@ func ExampleClient_SetIamPolicy() { } func ExampleClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. @@ -439,13 +419,12 @@ func ExampleClient_TestIamPermissions() { } func ExampleClient_UpdateFinding() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateFindingRequest{ // TODO: Fill request struct fields. @@ -459,13 +438,12 @@ func ExampleClient_UpdateFinding() { } func ExampleClient_UpdateNotificationConfig() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateNotificationConfigRequest{ // TODO: Fill request struct fields. @@ -479,13 +457,12 @@ func ExampleClient_UpdateNotificationConfig() { } func ExampleClient_UpdateOrganizationSettings() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateOrganizationSettingsRequest{ // TODO: Fill request struct fields. @@ -499,13 +476,12 @@ func ExampleClient_UpdateOrganizationSettings() { } func ExampleClient_UpdateSource() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateSourceRequest{ // TODO: Fill request struct fields. @@ -519,13 +495,12 @@ func ExampleClient_UpdateSource() { } func ExampleClient_UpdateSecurityMarks() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateSecurityMarksRequest{ // TODO: Fill request struct fields. diff --git a/securitycenter/apiv1beta1/doc.go b/securitycenter/apiv1beta1/doc.go index da9ef57c9fcb..2df70f7cc776 100644 --- a/securitycenter/apiv1beta1/doc.go +++ b/securitycenter/apiv1beta1/doc.go @@ -20,6 +20,8 @@ // Security Command Center API provides access to temporal views of assets // and findings within an organization. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package securitycenter // import "cloud.google.com/go/securitycenter/apiv1beta1" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/securitycenter/apiv1beta1/security_center_client.go b/securitycenter/apiv1beta1/security_center_client.go index 7aeee6b435a7..b58cf97fb133 100644 --- a/securitycenter/apiv1beta1/security_center_client.go +++ b/securitycenter/apiv1beta1/security_center_client.go @@ -64,7 +64,7 @@ type CallOptions struct { UpdateSecurityMarks []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("securitycenter.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("securitycenter.mtls.googleapis.com:443"), @@ -198,37 +198,213 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Security Command Center API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateSource(context.Context, *securitycenterpb.CreateSourceRequest, ...gax.CallOption) (*securitycenterpb.Source, error) + CreateFinding(context.Context, *securitycenterpb.CreateFindingRequest, ...gax.CallOption) (*securitycenterpb.Finding, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + GetOrganizationSettings(context.Context, *securitycenterpb.GetOrganizationSettingsRequest, ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) + GetSource(context.Context, *securitycenterpb.GetSourceRequest, ...gax.CallOption) (*securitycenterpb.Source, error) + GroupAssets(context.Context, *securitycenterpb.GroupAssetsRequest, ...gax.CallOption) *GroupResultIterator + GroupFindings(context.Context, *securitycenterpb.GroupFindingsRequest, ...gax.CallOption) *GroupResultIterator + ListAssets(context.Context, *securitycenterpb.ListAssetsRequest, ...gax.CallOption) *ListAssetsResponse_ListAssetsResultIterator + ListFindings(context.Context, *securitycenterpb.ListFindingsRequest, ...gax.CallOption) *FindingIterator + ListSources(context.Context, *securitycenterpb.ListSourcesRequest, ...gax.CallOption) *SourceIterator + RunAssetDiscovery(context.Context, *securitycenterpb.RunAssetDiscoveryRequest, ...gax.CallOption) (*RunAssetDiscoveryOperation, error) + RunAssetDiscoveryOperation(name string) *RunAssetDiscoveryOperation + SetFindingState(context.Context, *securitycenterpb.SetFindingStateRequest, ...gax.CallOption) (*securitycenterpb.Finding, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) + UpdateFinding(context.Context, *securitycenterpb.UpdateFindingRequest, ...gax.CallOption) (*securitycenterpb.Finding, error) + UpdateOrganizationSettings(context.Context, *securitycenterpb.UpdateOrganizationSettingsRequest, ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) + UpdateSource(context.Context, *securitycenterpb.UpdateSourceRequest, ...gax.CallOption) (*securitycenterpb.Source, error) + UpdateSecurityMarks(context.Context, *securitycenterpb.UpdateSecurityMarksRequest, ...gax.CallOption) (*securitycenterpb.SecurityMarks, error) +} + // Client is a client for interacting with Security Command Center API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// V1 Beta APIs for Security Center service. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateSource creates a source. +func (c *Client) CreateSource(ctx context.Context, req *securitycenterpb.CreateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { + return c.internalClient.CreateSource(ctx, req, opts...) +} + +// CreateFinding creates a finding. The corresponding source must exist for finding creation +// to succeed. +func (c *Client) CreateFinding(ctx context.Context, req *securitycenterpb.CreateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { + return c.internalClient.CreateFinding(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy on the specified Source. +func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// GetOrganizationSettings gets the settings for an organization. +func (c *Client) GetOrganizationSettings(ctx context.Context, req *securitycenterpb.GetOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { + return c.internalClient.GetOrganizationSettings(ctx, req, opts...) +} + +// GetSource gets a source. +func (c *Client) GetSource(ctx context.Context, req *securitycenterpb.GetSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { + return c.internalClient.GetSource(ctx, req, opts...) +} + +// GroupAssets filters an organization’s assets and groups them by their specified +// properties. +func (c *Client) GroupAssets(ctx context.Context, req *securitycenterpb.GroupAssetsRequest, opts ...gax.CallOption) *GroupResultIterator { + return c.internalClient.GroupAssets(ctx, req, opts...) +} + +// GroupFindings filters an organization or source’s findings and groups them by their +// specified properties. +// +// To group across all sources provide a - as the source id. +// Example: /v1beta1/organizations/{organization_id}/sources/-/findings +func (c *Client) GroupFindings(ctx context.Context, req *securitycenterpb.GroupFindingsRequest, opts ...gax.CallOption) *GroupResultIterator { + return c.internalClient.GroupFindings(ctx, req, opts...) +} + +// ListAssets lists an organization’s assets. +func (c *Client) ListAssets(ctx context.Context, req *securitycenterpb.ListAssetsRequest, opts ...gax.CallOption) *ListAssetsResponse_ListAssetsResultIterator { + return c.internalClient.ListAssets(ctx, req, opts...) +} + +// ListFindings lists an organization or source’s findings. +// +// To list across all sources provide a - as the source id. +// Example: /v1beta1/organizations/{organization_id}/sources/-/findings +func (c *Client) ListFindings(ctx context.Context, req *securitycenterpb.ListFindingsRequest, opts ...gax.CallOption) *FindingIterator { + return c.internalClient.ListFindings(ctx, req, opts...) +} + +// ListSources lists all sources belonging to an organization. +func (c *Client) ListSources(ctx context.Context, req *securitycenterpb.ListSourcesRequest, opts ...gax.CallOption) *SourceIterator { + return c.internalClient.ListSources(ctx, req, opts...) +} + +// RunAssetDiscovery runs asset discovery. The discovery is tracked with a long-running +// operation. +// +// This API can only be called with limited frequency for an organization. If +// it is called too frequently the caller will receive a TOO_MANY_REQUESTS +// error. +func (c *Client) RunAssetDiscovery(ctx context.Context, req *securitycenterpb.RunAssetDiscoveryRequest, opts ...gax.CallOption) (*RunAssetDiscoveryOperation, error) { + return c.internalClient.RunAssetDiscovery(ctx, req, opts...) +} + +// RunAssetDiscoveryOperation returns a new RunAssetDiscoveryOperation from a given name. +// The name must be that of a previously created RunAssetDiscoveryOperation, possibly from a different process. +func (c *Client) RunAssetDiscoveryOperation(name string) *RunAssetDiscoveryOperation { + return c.internalClient.RunAssetDiscoveryOperation(name) +} + +// SetFindingState updates the state of a finding. +func (c *Client) SetFindingState(ctx context.Context, req *securitycenterpb.SetFindingStateRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { + return c.internalClient.SetFindingState(ctx, req, opts...) +} + +// SetIamPolicy sets the access control policy on the specified Source. +func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns the permissions that a caller has on the specified source. +func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// UpdateFinding creates or updates a finding. The corresponding source must exist for a +// finding creation to succeed. +func (c *Client) UpdateFinding(ctx context.Context, req *securitycenterpb.UpdateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { + return c.internalClient.UpdateFinding(ctx, req, opts...) +} + +// UpdateOrganizationSettings updates an organization’s settings. +func (c *Client) UpdateOrganizationSettings(ctx context.Context, req *securitycenterpb.UpdateOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { + return c.internalClient.UpdateOrganizationSettings(ctx, req, opts...) +} + +// UpdateSource updates a source. +func (c *Client) UpdateSource(ctx context.Context, req *securitycenterpb.UpdateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { + return c.internalClient.UpdateSource(ctx, req, opts...) +} + +// UpdateSecurityMarks updates security marks. +func (c *Client) UpdateSecurityMarks(ctx context.Context, req *securitycenterpb.UpdateSecurityMarksRequest, opts ...gax.CallOption) (*securitycenterpb.SecurityMarks, error) { + return c.internalClient.UpdateSecurityMarks(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Security Command Center API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client securitycenterpb.SecurityCenterClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new security center client. +// NewClient creates a new security center client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // V1 Beta APIs for Security Center service. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -246,16 +422,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: securitycenterpb.NewSecurityCenterClient(connPool), + client: securitycenterpb.NewSecurityCenterClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -265,33 +444,33 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateSource creates a source. -func (c *Client) CreateSource(ctx context.Context, req *securitycenterpb.CreateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateSource(ctx context.Context, req *securitycenterpb.CreateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -299,7 +478,7 @@ func (c *Client) CreateSource(ctx context.Context, req *securitycenterpb.CreateS } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSource[0:len(c.CallOptions.CreateSource):len(c.CallOptions.CreateSource)], opts...) + opts = append((*c.CallOptions).CreateSource[0:len((*c.CallOptions).CreateSource):len((*c.CallOptions).CreateSource)], opts...) var resp *securitycenterpb.Source err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -312,9 +491,7 @@ func (c *Client) CreateSource(ctx context.Context, req *securitycenterpb.CreateS return resp, nil } -// CreateFinding creates a finding. The corresponding source must exist for finding creation -// to succeed. -func (c *Client) CreateFinding(ctx context.Context, req *securitycenterpb.CreateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { +func (c *gRPCClient) CreateFinding(ctx context.Context, req *securitycenterpb.CreateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -322,7 +499,7 @@ func (c *Client) CreateFinding(ctx context.Context, req *securitycenterpb.Create } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateFinding[0:len(c.CallOptions.CreateFinding):len(c.CallOptions.CreateFinding)], opts...) + opts = append((*c.CallOptions).CreateFinding[0:len((*c.CallOptions).CreateFinding):len((*c.CallOptions).CreateFinding)], opts...) var resp *securitycenterpb.Finding err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -335,8 +512,7 @@ func (c *Client) CreateFinding(ctx context.Context, req *securitycenterpb.Create return resp, nil } -// GetIamPolicy gets the access control policy on the specified Source. -func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -344,7 +520,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -357,8 +533,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques return resp, nil } -// GetOrganizationSettings gets the settings for an organization. -func (c *Client) GetOrganizationSettings(ctx context.Context, req *securitycenterpb.GetOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { +func (c *gRPCClient) GetOrganizationSettings(ctx context.Context, req *securitycenterpb.GetOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -366,7 +541,7 @@ func (c *Client) GetOrganizationSettings(ctx context.Context, req *securitycente } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetOrganizationSettings[0:len(c.CallOptions.GetOrganizationSettings):len(c.CallOptions.GetOrganizationSettings)], opts...) + opts = append((*c.CallOptions).GetOrganizationSettings[0:len((*c.CallOptions).GetOrganizationSettings):len((*c.CallOptions).GetOrganizationSettings)], opts...) var resp *securitycenterpb.OrganizationSettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -379,8 +554,7 @@ func (c *Client) GetOrganizationSettings(ctx context.Context, req *securitycente return resp, nil } -// GetSource gets a source. -func (c *Client) GetSource(ctx context.Context, req *securitycenterpb.GetSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { +func (c *gRPCClient) GetSource(ctx context.Context, req *securitycenterpb.GetSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -388,7 +562,7 @@ func (c *Client) GetSource(ctx context.Context, req *securitycenterpb.GetSourceR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSource[0:len(c.CallOptions.GetSource):len(c.CallOptions.GetSource)], opts...) + opts = append((*c.CallOptions).GetSource[0:len((*c.CallOptions).GetSource):len((*c.CallOptions).GetSource)], opts...) var resp *securitycenterpb.Source err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -401,12 +575,10 @@ func (c *Client) GetSource(ctx context.Context, req *securitycenterpb.GetSourceR return resp, nil } -// GroupAssets filters an organization’s assets and groups them by their specified -// properties. -func (c *Client) GroupAssets(ctx context.Context, req *securitycenterpb.GroupAssetsRequest, opts ...gax.CallOption) *GroupResultIterator { +func (c *gRPCClient) GroupAssets(ctx context.Context, req *securitycenterpb.GroupAssetsRequest, opts ...gax.CallOption) *GroupResultIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GroupAssets[0:len(c.CallOptions.GroupAssets):len(c.CallOptions.GroupAssets)], opts...) + opts = append((*c.CallOptions).GroupAssets[0:len((*c.CallOptions).GroupAssets):len((*c.CallOptions).GroupAssets)], opts...) it := &GroupResultIterator{} req = proto.Clone(req).(*securitycenterpb.GroupAssetsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.GroupResult, string, error) { @@ -443,15 +615,10 @@ func (c *Client) GroupAssets(ctx context.Context, req *securitycenterpb.GroupAss return it } -// GroupFindings filters an organization or source’s findings and groups them by their -// specified properties. -// -// To group across all sources provide a - as the source id. -// Example: /v1beta1/organizations/{organization_id}/sources/-/findings -func (c *Client) GroupFindings(ctx context.Context, req *securitycenterpb.GroupFindingsRequest, opts ...gax.CallOption) *GroupResultIterator { +func (c *gRPCClient) GroupFindings(ctx context.Context, req *securitycenterpb.GroupFindingsRequest, opts ...gax.CallOption) *GroupResultIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GroupFindings[0:len(c.CallOptions.GroupFindings):len(c.CallOptions.GroupFindings)], opts...) + opts = append((*c.CallOptions).GroupFindings[0:len((*c.CallOptions).GroupFindings):len((*c.CallOptions).GroupFindings)], opts...) it := &GroupResultIterator{} req = proto.Clone(req).(*securitycenterpb.GroupFindingsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.GroupResult, string, error) { @@ -488,11 +655,10 @@ func (c *Client) GroupFindings(ctx context.Context, req *securitycenterpb.GroupF return it } -// ListAssets lists an organization’s assets. -func (c *Client) ListAssets(ctx context.Context, req *securitycenterpb.ListAssetsRequest, opts ...gax.CallOption) *ListAssetsResponse_ListAssetsResultIterator { +func (c *gRPCClient) ListAssets(ctx context.Context, req *securitycenterpb.ListAssetsRequest, opts ...gax.CallOption) *ListAssetsResponse_ListAssetsResultIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAssets[0:len(c.CallOptions.ListAssets):len(c.CallOptions.ListAssets)], opts...) + opts = append((*c.CallOptions).ListAssets[0:len((*c.CallOptions).ListAssets):len((*c.CallOptions).ListAssets)], opts...) it := &ListAssetsResponse_ListAssetsResultIterator{} req = proto.Clone(req).(*securitycenterpb.ListAssetsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.ListAssetsResponse_ListAssetsResult, string, error) { @@ -529,14 +695,10 @@ func (c *Client) ListAssets(ctx context.Context, req *securitycenterpb.ListAsset return it } -// ListFindings lists an organization or source’s findings. -// -// To list across all sources provide a - as the source id. -// Example: /v1beta1/organizations/{organization_id}/sources/-/findings -func (c *Client) ListFindings(ctx context.Context, req *securitycenterpb.ListFindingsRequest, opts ...gax.CallOption) *FindingIterator { +func (c *gRPCClient) ListFindings(ctx context.Context, req *securitycenterpb.ListFindingsRequest, opts ...gax.CallOption) *FindingIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListFindings[0:len(c.CallOptions.ListFindings):len(c.CallOptions.ListFindings)], opts...) + opts = append((*c.CallOptions).ListFindings[0:len((*c.CallOptions).ListFindings):len((*c.CallOptions).ListFindings)], opts...) it := &FindingIterator{} req = proto.Clone(req).(*securitycenterpb.ListFindingsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.Finding, string, error) { @@ -573,11 +735,10 @@ func (c *Client) ListFindings(ctx context.Context, req *securitycenterpb.ListFin return it } -// ListSources lists all sources belonging to an organization. -func (c *Client) ListSources(ctx context.Context, req *securitycenterpb.ListSourcesRequest, opts ...gax.CallOption) *SourceIterator { +func (c *gRPCClient) ListSources(ctx context.Context, req *securitycenterpb.ListSourcesRequest, opts ...gax.CallOption) *SourceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSources[0:len(c.CallOptions.ListSources):len(c.CallOptions.ListSources)], opts...) + opts = append((*c.CallOptions).ListSources[0:len((*c.CallOptions).ListSources):len((*c.CallOptions).ListSources)], opts...) it := &SourceIterator{} req = proto.Clone(req).(*securitycenterpb.ListSourcesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.Source, string, error) { @@ -614,13 +775,7 @@ func (c *Client) ListSources(ctx context.Context, req *securitycenterpb.ListSour return it } -// RunAssetDiscovery runs asset discovery. The discovery is tracked with a long-running -// operation. -// -// This API can only be called with limited frequency for an organization. If -// it is called too frequently the caller will receive a TOO_MANY_REQUESTS -// error. -func (c *Client) RunAssetDiscovery(ctx context.Context, req *securitycenterpb.RunAssetDiscoveryRequest, opts ...gax.CallOption) (*RunAssetDiscoveryOperation, error) { +func (c *gRPCClient) RunAssetDiscovery(ctx context.Context, req *securitycenterpb.RunAssetDiscoveryRequest, opts ...gax.CallOption) (*RunAssetDiscoveryOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -628,7 +783,7 @@ func (c *Client) RunAssetDiscovery(ctx context.Context, req *securitycenterpb.Ru } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RunAssetDiscovery[0:len(c.CallOptions.RunAssetDiscovery):len(c.CallOptions.RunAssetDiscovery)], opts...) + opts = append((*c.CallOptions).RunAssetDiscovery[0:len((*c.CallOptions).RunAssetDiscovery):len((*c.CallOptions).RunAssetDiscovery)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -639,12 +794,11 @@ func (c *Client) RunAssetDiscovery(ctx context.Context, req *securitycenterpb.Ru return nil, err } return &RunAssetDiscoveryOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// SetFindingState updates the state of a finding. -func (c *Client) SetFindingState(ctx context.Context, req *securitycenterpb.SetFindingStateRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { +func (c *gRPCClient) SetFindingState(ctx context.Context, req *securitycenterpb.SetFindingStateRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -652,7 +806,7 @@ func (c *Client) SetFindingState(ctx context.Context, req *securitycenterpb.SetF } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetFindingState[0:len(c.CallOptions.SetFindingState):len(c.CallOptions.SetFindingState)], opts...) + opts = append((*c.CallOptions).SetFindingState[0:len((*c.CallOptions).SetFindingState):len((*c.CallOptions).SetFindingState)], opts...) var resp *securitycenterpb.Finding err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -665,8 +819,7 @@ func (c *Client) SetFindingState(ctx context.Context, req *securitycenterpb.SetF return resp, nil } -// SetIamPolicy sets the access control policy on the specified Source. -func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -674,7 +827,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -687,8 +840,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques return resp, nil } -// TestIamPermissions returns the permissions that a caller has on the specified source. -func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *gRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -696,7 +848,7 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -709,9 +861,7 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi return resp, nil } -// UpdateFinding creates or updates a finding. The corresponding source must exist for a -// finding creation to succeed. -func (c *Client) UpdateFinding(ctx context.Context, req *securitycenterpb.UpdateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { +func (c *gRPCClient) UpdateFinding(ctx context.Context, req *securitycenterpb.UpdateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -719,7 +869,7 @@ func (c *Client) UpdateFinding(ctx context.Context, req *securitycenterpb.Update } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "finding.name", url.QueryEscape(req.GetFinding().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateFinding[0:len(c.CallOptions.UpdateFinding):len(c.CallOptions.UpdateFinding)], opts...) + opts = append((*c.CallOptions).UpdateFinding[0:len((*c.CallOptions).UpdateFinding):len((*c.CallOptions).UpdateFinding)], opts...) var resp *securitycenterpb.Finding err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -732,8 +882,7 @@ func (c *Client) UpdateFinding(ctx context.Context, req *securitycenterpb.Update return resp, nil } -// UpdateOrganizationSettings updates an organization’s settings. -func (c *Client) UpdateOrganizationSettings(ctx context.Context, req *securitycenterpb.UpdateOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { +func (c *gRPCClient) UpdateOrganizationSettings(ctx context.Context, req *securitycenterpb.UpdateOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -741,7 +890,7 @@ func (c *Client) UpdateOrganizationSettings(ctx context.Context, req *securityce } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "organization_settings.name", url.QueryEscape(req.GetOrganizationSettings().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateOrganizationSettings[0:len(c.CallOptions.UpdateOrganizationSettings):len(c.CallOptions.UpdateOrganizationSettings)], opts...) + opts = append((*c.CallOptions).UpdateOrganizationSettings[0:len((*c.CallOptions).UpdateOrganizationSettings):len((*c.CallOptions).UpdateOrganizationSettings)], opts...) var resp *securitycenterpb.OrganizationSettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -754,8 +903,7 @@ func (c *Client) UpdateOrganizationSettings(ctx context.Context, req *securityce return resp, nil } -// UpdateSource updates a source. -func (c *Client) UpdateSource(ctx context.Context, req *securitycenterpb.UpdateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { +func (c *gRPCClient) UpdateSource(ctx context.Context, req *securitycenterpb.UpdateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -763,7 +911,7 @@ func (c *Client) UpdateSource(ctx context.Context, req *securitycenterpb.UpdateS } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "source.name", url.QueryEscape(req.GetSource().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSource[0:len(c.CallOptions.UpdateSource):len(c.CallOptions.UpdateSource)], opts...) + opts = append((*c.CallOptions).UpdateSource[0:len((*c.CallOptions).UpdateSource):len((*c.CallOptions).UpdateSource)], opts...) var resp *securitycenterpb.Source err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -776,8 +924,7 @@ func (c *Client) UpdateSource(ctx context.Context, req *securitycenterpb.UpdateS return resp, nil } -// UpdateSecurityMarks updates security marks. -func (c *Client) UpdateSecurityMarks(ctx context.Context, req *securitycenterpb.UpdateSecurityMarksRequest, opts ...gax.CallOption) (*securitycenterpb.SecurityMarks, error) { +func (c *gRPCClient) UpdateSecurityMarks(ctx context.Context, req *securitycenterpb.UpdateSecurityMarksRequest, opts ...gax.CallOption) (*securitycenterpb.SecurityMarks, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 480000*time.Millisecond) defer cancel() @@ -785,7 +932,7 @@ func (c *Client) UpdateSecurityMarks(ctx context.Context, req *securitycenterpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "security_marks.name", url.QueryEscape(req.GetSecurityMarks().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSecurityMarks[0:len(c.CallOptions.UpdateSecurityMarks):len(c.CallOptions.UpdateSecurityMarks)], opts...) + opts = append((*c.CallOptions).UpdateSecurityMarks[0:len((*c.CallOptions).UpdateSecurityMarks):len((*c.CallOptions).UpdateSecurityMarks)], opts...) var resp *securitycenterpb.SecurityMarks err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -805,9 +952,9 @@ type RunAssetDiscoveryOperation struct { // RunAssetDiscoveryOperation returns a new RunAssetDiscoveryOperation from a given name. // The name must be that of a previously created RunAssetDiscoveryOperation, possibly from a different process. -func (c *Client) RunAssetDiscoveryOperation(name string) *RunAssetDiscoveryOperation { +func (c *gRPCClient) RunAssetDiscoveryOperation(name string) *RunAssetDiscoveryOperation { return &RunAssetDiscoveryOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/securitycenter/apiv1beta1/security_center_client_example_test.go b/securitycenter/apiv1beta1/security_center_client_example_test.go index 1148708c9d41..a462b9e81931 100644 --- a/securitycenter/apiv1beta1/security_center_client_example_test.go +++ b/securitycenter/apiv1beta1/security_center_client_example_test.go @@ -31,18 +31,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateSource() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.CreateSourceRequest{ // TODO: Fill request struct fields. @@ -56,13 +57,12 @@ func ExampleClient_CreateSource() { } func ExampleClient_CreateFinding() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.CreateFindingRequest{ // TODO: Fill request struct fields. @@ -76,13 +76,12 @@ func ExampleClient_CreateFinding() { } func ExampleClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -96,13 +95,12 @@ func ExampleClient_GetIamPolicy() { } func ExampleClient_GetOrganizationSettings() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GetOrganizationSettingsRequest{ // TODO: Fill request struct fields. @@ -116,13 +114,12 @@ func ExampleClient_GetOrganizationSettings() { } func ExampleClient_GetSource() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GetSourceRequest{ // TODO: Fill request struct fields. @@ -136,14 +133,12 @@ func ExampleClient_GetSource() { } func ExampleClient_GroupAssets() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GroupAssetsRequest{ // TODO: Fill request struct fields. @@ -163,14 +158,12 @@ func ExampleClient_GroupAssets() { } func ExampleClient_GroupFindings() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GroupFindingsRequest{ // TODO: Fill request struct fields. @@ -190,14 +183,12 @@ func ExampleClient_GroupFindings() { } func ExampleClient_ListAssets() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListAssetsRequest{ // TODO: Fill request struct fields. @@ -217,14 +208,12 @@ func ExampleClient_ListAssets() { } func ExampleClient_ListFindings() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListFindingsRequest{ // TODO: Fill request struct fields. @@ -244,14 +233,12 @@ func ExampleClient_ListFindings() { } func ExampleClient_ListSources() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListSourcesRequest{ // TODO: Fill request struct fields. @@ -271,13 +258,12 @@ func ExampleClient_ListSources() { } func ExampleClient_RunAssetDiscovery() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.RunAssetDiscoveryRequest{ // TODO: Fill request struct fields. @@ -294,13 +280,12 @@ func ExampleClient_RunAssetDiscovery() { } func ExampleClient_SetFindingState() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.SetFindingStateRequest{ // TODO: Fill request struct fields. @@ -314,13 +299,12 @@ func ExampleClient_SetFindingState() { } func ExampleClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -334,13 +318,12 @@ func ExampleClient_SetIamPolicy() { } func ExampleClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. @@ -354,13 +337,12 @@ func ExampleClient_TestIamPermissions() { } func ExampleClient_UpdateFinding() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateFindingRequest{ // TODO: Fill request struct fields. @@ -374,13 +356,12 @@ func ExampleClient_UpdateFinding() { } func ExampleClient_UpdateOrganizationSettings() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateOrganizationSettingsRequest{ // TODO: Fill request struct fields. @@ -394,13 +375,12 @@ func ExampleClient_UpdateOrganizationSettings() { } func ExampleClient_UpdateSource() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateSourceRequest{ // TODO: Fill request struct fields. @@ -414,13 +394,12 @@ func ExampleClient_UpdateSource() { } func ExampleClient_UpdateSecurityMarks() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateSecurityMarksRequest{ // TODO: Fill request struct fields. diff --git a/securitycenter/apiv1p1beta1/doc.go b/securitycenter/apiv1p1beta1/doc.go index 4a00183891cc..0eb0c160ffd9 100644 --- a/securitycenter/apiv1p1beta1/doc.go +++ b/securitycenter/apiv1p1beta1/doc.go @@ -20,6 +20,8 @@ // Security Command Center API provides access to temporal views of assets // and findings within an organization. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package securitycenter // import "cloud.google.com/go/securitycenter/apiv1p1beta1" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/securitycenter/apiv1p1beta1/security_center_client.go b/securitycenter/apiv1p1beta1/security_center_client.go index 565b11534d2f..7a321d3c2f83 100644 --- a/securitycenter/apiv1p1beta1/security_center_client.go +++ b/securitycenter/apiv1p1beta1/security_center_client.go @@ -69,7 +69,7 @@ type CallOptions struct { UpdateSecurityMarks []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("securitycenter.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("securitycenter.mtls.googleapis.com:443"), @@ -230,37 +230,246 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Security Command Center API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateSource(context.Context, *securitycenterpb.CreateSourceRequest, ...gax.CallOption) (*securitycenterpb.Source, error) + CreateFinding(context.Context, *securitycenterpb.CreateFindingRequest, ...gax.CallOption) (*securitycenterpb.Finding, error) + CreateNotificationConfig(context.Context, *securitycenterpb.CreateNotificationConfigRequest, ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) + DeleteNotificationConfig(context.Context, *securitycenterpb.DeleteNotificationConfigRequest, ...gax.CallOption) error + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + GetNotificationConfig(context.Context, *securitycenterpb.GetNotificationConfigRequest, ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) + GetOrganizationSettings(context.Context, *securitycenterpb.GetOrganizationSettingsRequest, ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) + GetSource(context.Context, *securitycenterpb.GetSourceRequest, ...gax.CallOption) (*securitycenterpb.Source, error) + GroupAssets(context.Context, *securitycenterpb.GroupAssetsRequest, ...gax.CallOption) *GroupResultIterator + GroupFindings(context.Context, *securitycenterpb.GroupFindingsRequest, ...gax.CallOption) *GroupResultIterator + ListAssets(context.Context, *securitycenterpb.ListAssetsRequest, ...gax.CallOption) *ListAssetsResponse_ListAssetsResultIterator + ListFindings(context.Context, *securitycenterpb.ListFindingsRequest, ...gax.CallOption) *ListFindingsResponse_ListFindingsResultIterator + ListNotificationConfigs(context.Context, *securitycenterpb.ListNotificationConfigsRequest, ...gax.CallOption) *NotificationConfigIterator + ListSources(context.Context, *securitycenterpb.ListSourcesRequest, ...gax.CallOption) *SourceIterator + RunAssetDiscovery(context.Context, *securitycenterpb.RunAssetDiscoveryRequest, ...gax.CallOption) (*RunAssetDiscoveryOperation, error) + RunAssetDiscoveryOperation(name string) *RunAssetDiscoveryOperation + SetFindingState(context.Context, *securitycenterpb.SetFindingStateRequest, ...gax.CallOption) (*securitycenterpb.Finding, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) + UpdateFinding(context.Context, *securitycenterpb.UpdateFindingRequest, ...gax.CallOption) (*securitycenterpb.Finding, error) + UpdateNotificationConfig(context.Context, *securitycenterpb.UpdateNotificationConfigRequest, ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) + UpdateOrganizationSettings(context.Context, *securitycenterpb.UpdateOrganizationSettingsRequest, ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) + UpdateSource(context.Context, *securitycenterpb.UpdateSourceRequest, ...gax.CallOption) (*securitycenterpb.Source, error) + UpdateSecurityMarks(context.Context, *securitycenterpb.UpdateSecurityMarksRequest, ...gax.CallOption) (*securitycenterpb.SecurityMarks, error) +} + // Client is a client for interacting with Security Command Center API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// V1p1Beta1 APIs for Security Center service. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateSource creates a source. +func (c *Client) CreateSource(ctx context.Context, req *securitycenterpb.CreateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { + return c.internalClient.CreateSource(ctx, req, opts...) +} + +// CreateFinding creates a finding. The corresponding source must exist for finding +// creation to succeed. +func (c *Client) CreateFinding(ctx context.Context, req *securitycenterpb.CreateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { + return c.internalClient.CreateFinding(ctx, req, opts...) +} + +// CreateNotificationConfig creates a notification config. +func (c *Client) CreateNotificationConfig(ctx context.Context, req *securitycenterpb.CreateNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { + return c.internalClient.CreateNotificationConfig(ctx, req, opts...) +} + +// DeleteNotificationConfig deletes a notification config. +func (c *Client) DeleteNotificationConfig(ctx context.Context, req *securitycenterpb.DeleteNotificationConfigRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteNotificationConfig(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy on the specified Source. +func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// GetNotificationConfig gets a notification config. +func (c *Client) GetNotificationConfig(ctx context.Context, req *securitycenterpb.GetNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { + return c.internalClient.GetNotificationConfig(ctx, req, opts...) +} + +// GetOrganizationSettings gets the settings for an organization. +func (c *Client) GetOrganizationSettings(ctx context.Context, req *securitycenterpb.GetOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { + return c.internalClient.GetOrganizationSettings(ctx, req, opts...) +} + +// GetSource gets a source. +func (c *Client) GetSource(ctx context.Context, req *securitycenterpb.GetSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { + return c.internalClient.GetSource(ctx, req, opts...) +} + +// GroupAssets filters an organization’s assets and groups them by their specified +// properties. +func (c *Client) GroupAssets(ctx context.Context, req *securitycenterpb.GroupAssetsRequest, opts ...gax.CallOption) *GroupResultIterator { + return c.internalClient.GroupAssets(ctx, req, opts...) +} + +// GroupFindings filters an organization or source’s findings and groups them by their +// specified properties. +// +// To group across all sources provide a - as the source id. +// Example: /v1/organizations/{organization_id}/sources/-/findings, +// /v1/folders/{folder_id}/sources/-/findings, +// /v1/projects/{project_id}/sources/-/findings +func (c *Client) GroupFindings(ctx context.Context, req *securitycenterpb.GroupFindingsRequest, opts ...gax.CallOption) *GroupResultIterator { + return c.internalClient.GroupFindings(ctx, req, opts...) +} + +// ListAssets lists an organization’s assets. +func (c *Client) ListAssets(ctx context.Context, req *securitycenterpb.ListAssetsRequest, opts ...gax.CallOption) *ListAssetsResponse_ListAssetsResultIterator { + return c.internalClient.ListAssets(ctx, req, opts...) +} + +// ListFindings lists an organization or source’s findings. +// +// To list across all sources provide a - as the source id. +// Example: /v1p1beta1/organizations/{organization_id}/sources/-/findings +func (c *Client) ListFindings(ctx context.Context, req *securitycenterpb.ListFindingsRequest, opts ...gax.CallOption) *ListFindingsResponse_ListFindingsResultIterator { + return c.internalClient.ListFindings(ctx, req, opts...) +} + +// ListNotificationConfigs lists notification configs. +func (c *Client) ListNotificationConfigs(ctx context.Context, req *securitycenterpb.ListNotificationConfigsRequest, opts ...gax.CallOption) *NotificationConfigIterator { + return c.internalClient.ListNotificationConfigs(ctx, req, opts...) +} + +// ListSources lists all sources belonging to an organization. +func (c *Client) ListSources(ctx context.Context, req *securitycenterpb.ListSourcesRequest, opts ...gax.CallOption) *SourceIterator { + return c.internalClient.ListSources(ctx, req, opts...) +} + +// RunAssetDiscovery runs asset discovery. The discovery is tracked with a long-running +// operation. +// +// This API can only be called with limited frequency for an organization. If +// it is called too frequently the caller will receive a TOO_MANY_REQUESTS +// error. +func (c *Client) RunAssetDiscovery(ctx context.Context, req *securitycenterpb.RunAssetDiscoveryRequest, opts ...gax.CallOption) (*RunAssetDiscoveryOperation, error) { + return c.internalClient.RunAssetDiscovery(ctx, req, opts...) +} + +// RunAssetDiscoveryOperation returns a new RunAssetDiscoveryOperation from a given name. +// The name must be that of a previously created RunAssetDiscoveryOperation, possibly from a different process. +func (c *Client) RunAssetDiscoveryOperation(name string) *RunAssetDiscoveryOperation { + return c.internalClient.RunAssetDiscoveryOperation(name) +} + +// SetFindingState updates the state of a finding. +func (c *Client) SetFindingState(ctx context.Context, req *securitycenterpb.SetFindingStateRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { + return c.internalClient.SetFindingState(ctx, req, opts...) +} + +// SetIamPolicy sets the access control policy on the specified Source. +func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns the permissions that a caller has on the specified source. +func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// UpdateFinding creates or updates a finding. The corresponding source must exist for a +// finding creation to succeed. +func (c *Client) UpdateFinding(ctx context.Context, req *securitycenterpb.UpdateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { + return c.internalClient.UpdateFinding(ctx, req, opts...) +} + +// UpdateNotificationConfig updates a notification config. The following update +// fields are allowed: description, pubsub_topic, streaming_config.filter +func (c *Client) UpdateNotificationConfig(ctx context.Context, req *securitycenterpb.UpdateNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { + return c.internalClient.UpdateNotificationConfig(ctx, req, opts...) +} + +// UpdateOrganizationSettings updates an organization’s settings. +func (c *Client) UpdateOrganizationSettings(ctx context.Context, req *securitycenterpb.UpdateOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { + return c.internalClient.UpdateOrganizationSettings(ctx, req, opts...) +} + +// UpdateSource updates a source. +func (c *Client) UpdateSource(ctx context.Context, req *securitycenterpb.UpdateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { + return c.internalClient.UpdateSource(ctx, req, opts...) +} + +// UpdateSecurityMarks updates security marks. +func (c *Client) UpdateSecurityMarks(ctx context.Context, req *securitycenterpb.UpdateSecurityMarksRequest, opts ...gax.CallOption) (*securitycenterpb.SecurityMarks, error) { + return c.internalClient.UpdateSecurityMarks(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Security Command Center API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client securitycenterpb.SecurityCenterClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new security center client. +// NewClient creates a new security center client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // V1p1Beta1 APIs for Security Center service. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -278,16 +487,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: securitycenterpb.NewSecurityCenterClient(connPool), + client: securitycenterpb.NewSecurityCenterClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -297,33 +509,33 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateSource creates a source. -func (c *Client) CreateSource(ctx context.Context, req *securitycenterpb.CreateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateSource(ctx context.Context, req *securitycenterpb.CreateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -331,7 +543,7 @@ func (c *Client) CreateSource(ctx context.Context, req *securitycenterpb.CreateS } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSource[0:len(c.CallOptions.CreateSource):len(c.CallOptions.CreateSource)], opts...) + opts = append((*c.CallOptions).CreateSource[0:len((*c.CallOptions).CreateSource):len((*c.CallOptions).CreateSource)], opts...) var resp *securitycenterpb.Source err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -344,9 +556,7 @@ func (c *Client) CreateSource(ctx context.Context, req *securitycenterpb.CreateS return resp, nil } -// CreateFinding creates a finding. The corresponding source must exist for finding -// creation to succeed. -func (c *Client) CreateFinding(ctx context.Context, req *securitycenterpb.CreateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { +func (c *gRPCClient) CreateFinding(ctx context.Context, req *securitycenterpb.CreateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -354,7 +564,7 @@ func (c *Client) CreateFinding(ctx context.Context, req *securitycenterpb.Create } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateFinding[0:len(c.CallOptions.CreateFinding):len(c.CallOptions.CreateFinding)], opts...) + opts = append((*c.CallOptions).CreateFinding[0:len((*c.CallOptions).CreateFinding):len((*c.CallOptions).CreateFinding)], opts...) var resp *securitycenterpb.Finding err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -367,8 +577,7 @@ func (c *Client) CreateFinding(ctx context.Context, req *securitycenterpb.Create return resp, nil } -// CreateNotificationConfig creates a notification config. -func (c *Client) CreateNotificationConfig(ctx context.Context, req *securitycenterpb.CreateNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { +func (c *gRPCClient) CreateNotificationConfig(ctx context.Context, req *securitycenterpb.CreateNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -376,7 +585,7 @@ func (c *Client) CreateNotificationConfig(ctx context.Context, req *securitycent } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateNotificationConfig[0:len(c.CallOptions.CreateNotificationConfig):len(c.CallOptions.CreateNotificationConfig)], opts...) + opts = append((*c.CallOptions).CreateNotificationConfig[0:len((*c.CallOptions).CreateNotificationConfig):len((*c.CallOptions).CreateNotificationConfig)], opts...) var resp *securitycenterpb.NotificationConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -389,8 +598,7 @@ func (c *Client) CreateNotificationConfig(ctx context.Context, req *securitycent return resp, nil } -// DeleteNotificationConfig deletes a notification config. -func (c *Client) DeleteNotificationConfig(ctx context.Context, req *securitycenterpb.DeleteNotificationConfigRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteNotificationConfig(ctx context.Context, req *securitycenterpb.DeleteNotificationConfigRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -398,7 +606,7 @@ func (c *Client) DeleteNotificationConfig(ctx context.Context, req *securitycent } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteNotificationConfig[0:len(c.CallOptions.DeleteNotificationConfig):len(c.CallOptions.DeleteNotificationConfig)], opts...) + opts = append((*c.CallOptions).DeleteNotificationConfig[0:len((*c.CallOptions).DeleteNotificationConfig):len((*c.CallOptions).DeleteNotificationConfig)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteNotificationConfig(ctx, req, settings.GRPC...) @@ -407,8 +615,7 @@ func (c *Client) DeleteNotificationConfig(ctx context.Context, req *securitycent return err } -// GetIamPolicy gets the access control policy on the specified Source. -func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -416,7 +623,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -429,8 +636,7 @@ func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyReques return resp, nil } -// GetNotificationConfig gets a notification config. -func (c *Client) GetNotificationConfig(ctx context.Context, req *securitycenterpb.GetNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { +func (c *gRPCClient) GetNotificationConfig(ctx context.Context, req *securitycenterpb.GetNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -438,7 +644,7 @@ func (c *Client) GetNotificationConfig(ctx context.Context, req *securitycenterp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetNotificationConfig[0:len(c.CallOptions.GetNotificationConfig):len(c.CallOptions.GetNotificationConfig)], opts...) + opts = append((*c.CallOptions).GetNotificationConfig[0:len((*c.CallOptions).GetNotificationConfig):len((*c.CallOptions).GetNotificationConfig)], opts...) var resp *securitycenterpb.NotificationConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -451,8 +657,7 @@ func (c *Client) GetNotificationConfig(ctx context.Context, req *securitycenterp return resp, nil } -// GetOrganizationSettings gets the settings for an organization. -func (c *Client) GetOrganizationSettings(ctx context.Context, req *securitycenterpb.GetOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { +func (c *gRPCClient) GetOrganizationSettings(ctx context.Context, req *securitycenterpb.GetOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -460,7 +665,7 @@ func (c *Client) GetOrganizationSettings(ctx context.Context, req *securitycente } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetOrganizationSettings[0:len(c.CallOptions.GetOrganizationSettings):len(c.CallOptions.GetOrganizationSettings)], opts...) + opts = append((*c.CallOptions).GetOrganizationSettings[0:len((*c.CallOptions).GetOrganizationSettings):len((*c.CallOptions).GetOrganizationSettings)], opts...) var resp *securitycenterpb.OrganizationSettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -473,8 +678,7 @@ func (c *Client) GetOrganizationSettings(ctx context.Context, req *securitycente return resp, nil } -// GetSource gets a source. -func (c *Client) GetSource(ctx context.Context, req *securitycenterpb.GetSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { +func (c *gRPCClient) GetSource(ctx context.Context, req *securitycenterpb.GetSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -482,7 +686,7 @@ func (c *Client) GetSource(ctx context.Context, req *securitycenterpb.GetSourceR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSource[0:len(c.CallOptions.GetSource):len(c.CallOptions.GetSource)], opts...) + opts = append((*c.CallOptions).GetSource[0:len((*c.CallOptions).GetSource):len((*c.CallOptions).GetSource)], opts...) var resp *securitycenterpb.Source err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -495,12 +699,10 @@ func (c *Client) GetSource(ctx context.Context, req *securitycenterpb.GetSourceR return resp, nil } -// GroupAssets filters an organization’s assets and groups them by their specified -// properties. -func (c *Client) GroupAssets(ctx context.Context, req *securitycenterpb.GroupAssetsRequest, opts ...gax.CallOption) *GroupResultIterator { +func (c *gRPCClient) GroupAssets(ctx context.Context, req *securitycenterpb.GroupAssetsRequest, opts ...gax.CallOption) *GroupResultIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GroupAssets[0:len(c.CallOptions.GroupAssets):len(c.CallOptions.GroupAssets)], opts...) + opts = append((*c.CallOptions).GroupAssets[0:len((*c.CallOptions).GroupAssets):len((*c.CallOptions).GroupAssets)], opts...) it := &GroupResultIterator{} req = proto.Clone(req).(*securitycenterpb.GroupAssetsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.GroupResult, string, error) { @@ -537,17 +739,10 @@ func (c *Client) GroupAssets(ctx context.Context, req *securitycenterpb.GroupAss return it } -// GroupFindings filters an organization or source’s findings and groups them by their -// specified properties. -// -// To group across all sources provide a - as the source id. -// Example: /v1/organizations/{organization_id}/sources/-/findings, -// /v1/folders/{folder_id}/sources/-/findings, -// /v1/projects/{project_id}/sources/-/findings -func (c *Client) GroupFindings(ctx context.Context, req *securitycenterpb.GroupFindingsRequest, opts ...gax.CallOption) *GroupResultIterator { +func (c *gRPCClient) GroupFindings(ctx context.Context, req *securitycenterpb.GroupFindingsRequest, opts ...gax.CallOption) *GroupResultIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GroupFindings[0:len(c.CallOptions.GroupFindings):len(c.CallOptions.GroupFindings)], opts...) + opts = append((*c.CallOptions).GroupFindings[0:len((*c.CallOptions).GroupFindings):len((*c.CallOptions).GroupFindings)], opts...) it := &GroupResultIterator{} req = proto.Clone(req).(*securitycenterpb.GroupFindingsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.GroupResult, string, error) { @@ -584,11 +779,10 @@ func (c *Client) GroupFindings(ctx context.Context, req *securitycenterpb.GroupF return it } -// ListAssets lists an organization’s assets. -func (c *Client) ListAssets(ctx context.Context, req *securitycenterpb.ListAssetsRequest, opts ...gax.CallOption) *ListAssetsResponse_ListAssetsResultIterator { +func (c *gRPCClient) ListAssets(ctx context.Context, req *securitycenterpb.ListAssetsRequest, opts ...gax.CallOption) *ListAssetsResponse_ListAssetsResultIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListAssets[0:len(c.CallOptions.ListAssets):len(c.CallOptions.ListAssets)], opts...) + opts = append((*c.CallOptions).ListAssets[0:len((*c.CallOptions).ListAssets):len((*c.CallOptions).ListAssets)], opts...) it := &ListAssetsResponse_ListAssetsResultIterator{} req = proto.Clone(req).(*securitycenterpb.ListAssetsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.ListAssetsResponse_ListAssetsResult, string, error) { @@ -625,14 +819,10 @@ func (c *Client) ListAssets(ctx context.Context, req *securitycenterpb.ListAsset return it } -// ListFindings lists an organization or source’s findings. -// -// To list across all sources provide a - as the source id. -// Example: /v1p1beta1/organizations/{organization_id}/sources/-/findings -func (c *Client) ListFindings(ctx context.Context, req *securitycenterpb.ListFindingsRequest, opts ...gax.CallOption) *ListFindingsResponse_ListFindingsResultIterator { +func (c *gRPCClient) ListFindings(ctx context.Context, req *securitycenterpb.ListFindingsRequest, opts ...gax.CallOption) *ListFindingsResponse_ListFindingsResultIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListFindings[0:len(c.CallOptions.ListFindings):len(c.CallOptions.ListFindings)], opts...) + opts = append((*c.CallOptions).ListFindings[0:len((*c.CallOptions).ListFindings):len((*c.CallOptions).ListFindings)], opts...) it := &ListFindingsResponse_ListFindingsResultIterator{} req = proto.Clone(req).(*securitycenterpb.ListFindingsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.ListFindingsResponse_ListFindingsResult, string, error) { @@ -669,11 +859,10 @@ func (c *Client) ListFindings(ctx context.Context, req *securitycenterpb.ListFin return it } -// ListNotificationConfigs lists notification configs. -func (c *Client) ListNotificationConfigs(ctx context.Context, req *securitycenterpb.ListNotificationConfigsRequest, opts ...gax.CallOption) *NotificationConfigIterator { +func (c *gRPCClient) ListNotificationConfigs(ctx context.Context, req *securitycenterpb.ListNotificationConfigsRequest, opts ...gax.CallOption) *NotificationConfigIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListNotificationConfigs[0:len(c.CallOptions.ListNotificationConfigs):len(c.CallOptions.ListNotificationConfigs)], opts...) + opts = append((*c.CallOptions).ListNotificationConfigs[0:len((*c.CallOptions).ListNotificationConfigs):len((*c.CallOptions).ListNotificationConfigs)], opts...) it := &NotificationConfigIterator{} req = proto.Clone(req).(*securitycenterpb.ListNotificationConfigsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.NotificationConfig, string, error) { @@ -710,11 +899,10 @@ func (c *Client) ListNotificationConfigs(ctx context.Context, req *securitycente return it } -// ListSources lists all sources belonging to an organization. -func (c *Client) ListSources(ctx context.Context, req *securitycenterpb.ListSourcesRequest, opts ...gax.CallOption) *SourceIterator { +func (c *gRPCClient) ListSources(ctx context.Context, req *securitycenterpb.ListSourcesRequest, opts ...gax.CallOption) *SourceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSources[0:len(c.CallOptions.ListSources):len(c.CallOptions.ListSources)], opts...) + opts = append((*c.CallOptions).ListSources[0:len((*c.CallOptions).ListSources):len((*c.CallOptions).ListSources)], opts...) it := &SourceIterator{} req = proto.Clone(req).(*securitycenterpb.ListSourcesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.Source, string, error) { @@ -751,13 +939,7 @@ func (c *Client) ListSources(ctx context.Context, req *securitycenterpb.ListSour return it } -// RunAssetDiscovery runs asset discovery. The discovery is tracked with a long-running -// operation. -// -// This API can only be called with limited frequency for an organization. If -// it is called too frequently the caller will receive a TOO_MANY_REQUESTS -// error. -func (c *Client) RunAssetDiscovery(ctx context.Context, req *securitycenterpb.RunAssetDiscoveryRequest, opts ...gax.CallOption) (*RunAssetDiscoveryOperation, error) { +func (c *gRPCClient) RunAssetDiscovery(ctx context.Context, req *securitycenterpb.RunAssetDiscoveryRequest, opts ...gax.CallOption) (*RunAssetDiscoveryOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -765,7 +947,7 @@ func (c *Client) RunAssetDiscovery(ctx context.Context, req *securitycenterpb.Ru } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RunAssetDiscovery[0:len(c.CallOptions.RunAssetDiscovery):len(c.CallOptions.RunAssetDiscovery)], opts...) + opts = append((*c.CallOptions).RunAssetDiscovery[0:len((*c.CallOptions).RunAssetDiscovery):len((*c.CallOptions).RunAssetDiscovery)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -776,12 +958,11 @@ func (c *Client) RunAssetDiscovery(ctx context.Context, req *securitycenterpb.Ru return nil, err } return &RunAssetDiscoveryOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// SetFindingState updates the state of a finding. -func (c *Client) SetFindingState(ctx context.Context, req *securitycenterpb.SetFindingStateRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { +func (c *gRPCClient) SetFindingState(ctx context.Context, req *securitycenterpb.SetFindingStateRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -789,7 +970,7 @@ func (c *Client) SetFindingState(ctx context.Context, req *securitycenterpb.SetF } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetFindingState[0:len(c.CallOptions.SetFindingState):len(c.CallOptions.SetFindingState)], opts...) + opts = append((*c.CallOptions).SetFindingState[0:len((*c.CallOptions).SetFindingState):len((*c.CallOptions).SetFindingState)], opts...) var resp *securitycenterpb.Finding err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -802,8 +983,7 @@ func (c *Client) SetFindingState(ctx context.Context, req *securitycenterpb.SetF return resp, nil } -// SetIamPolicy sets the access control policy on the specified Source. -func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *gRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -811,7 +991,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -824,8 +1004,7 @@ func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyReques return resp, nil } -// TestIamPermissions returns the permissions that a caller has on the specified source. -func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *gRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -833,7 +1012,7 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -846,9 +1025,7 @@ func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermi return resp, nil } -// UpdateFinding creates or updates a finding. The corresponding source must exist for a -// finding creation to succeed. -func (c *Client) UpdateFinding(ctx context.Context, req *securitycenterpb.UpdateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { +func (c *gRPCClient) UpdateFinding(ctx context.Context, req *securitycenterpb.UpdateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -856,7 +1033,7 @@ func (c *Client) UpdateFinding(ctx context.Context, req *securitycenterpb.Update } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "finding.name", url.QueryEscape(req.GetFinding().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateFinding[0:len(c.CallOptions.UpdateFinding):len(c.CallOptions.UpdateFinding)], opts...) + opts = append((*c.CallOptions).UpdateFinding[0:len((*c.CallOptions).UpdateFinding):len((*c.CallOptions).UpdateFinding)], opts...) var resp *securitycenterpb.Finding err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -869,9 +1046,7 @@ func (c *Client) UpdateFinding(ctx context.Context, req *securitycenterpb.Update return resp, nil } -// UpdateNotificationConfig updates a notification config. The following update -// fields are allowed: description, pubsub_topic, streaming_config.filter -func (c *Client) UpdateNotificationConfig(ctx context.Context, req *securitycenterpb.UpdateNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { +func (c *gRPCClient) UpdateNotificationConfig(ctx context.Context, req *securitycenterpb.UpdateNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -879,7 +1054,7 @@ func (c *Client) UpdateNotificationConfig(ctx context.Context, req *securitycent } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "notification_config.name", url.QueryEscape(req.GetNotificationConfig().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateNotificationConfig[0:len(c.CallOptions.UpdateNotificationConfig):len(c.CallOptions.UpdateNotificationConfig)], opts...) + opts = append((*c.CallOptions).UpdateNotificationConfig[0:len((*c.CallOptions).UpdateNotificationConfig):len((*c.CallOptions).UpdateNotificationConfig)], opts...) var resp *securitycenterpb.NotificationConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -892,8 +1067,7 @@ func (c *Client) UpdateNotificationConfig(ctx context.Context, req *securitycent return resp, nil } -// UpdateOrganizationSettings updates an organization’s settings. -func (c *Client) UpdateOrganizationSettings(ctx context.Context, req *securitycenterpb.UpdateOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { +func (c *gRPCClient) UpdateOrganizationSettings(ctx context.Context, req *securitycenterpb.UpdateOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -901,7 +1075,7 @@ func (c *Client) UpdateOrganizationSettings(ctx context.Context, req *securityce } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "organization_settings.name", url.QueryEscape(req.GetOrganizationSettings().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateOrganizationSettings[0:len(c.CallOptions.UpdateOrganizationSettings):len(c.CallOptions.UpdateOrganizationSettings)], opts...) + opts = append((*c.CallOptions).UpdateOrganizationSettings[0:len((*c.CallOptions).UpdateOrganizationSettings):len((*c.CallOptions).UpdateOrganizationSettings)], opts...) var resp *securitycenterpb.OrganizationSettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -914,8 +1088,7 @@ func (c *Client) UpdateOrganizationSettings(ctx context.Context, req *securityce return resp, nil } -// UpdateSource updates a source. -func (c *Client) UpdateSource(ctx context.Context, req *securitycenterpb.UpdateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { +func (c *gRPCClient) UpdateSource(ctx context.Context, req *securitycenterpb.UpdateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -923,7 +1096,7 @@ func (c *Client) UpdateSource(ctx context.Context, req *securitycenterpb.UpdateS } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "source.name", url.QueryEscape(req.GetSource().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSource[0:len(c.CallOptions.UpdateSource):len(c.CallOptions.UpdateSource)], opts...) + opts = append((*c.CallOptions).UpdateSource[0:len((*c.CallOptions).UpdateSource):len((*c.CallOptions).UpdateSource)], opts...) var resp *securitycenterpb.Source err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -936,8 +1109,7 @@ func (c *Client) UpdateSource(ctx context.Context, req *securitycenterpb.UpdateS return resp, nil } -// UpdateSecurityMarks updates security marks. -func (c *Client) UpdateSecurityMarks(ctx context.Context, req *securitycenterpb.UpdateSecurityMarksRequest, opts ...gax.CallOption) (*securitycenterpb.SecurityMarks, error) { +func (c *gRPCClient) UpdateSecurityMarks(ctx context.Context, req *securitycenterpb.UpdateSecurityMarksRequest, opts ...gax.CallOption) (*securitycenterpb.SecurityMarks, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 480000*time.Millisecond) defer cancel() @@ -945,7 +1117,7 @@ func (c *Client) UpdateSecurityMarks(ctx context.Context, req *securitycenterpb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "security_marks.name", url.QueryEscape(req.GetSecurityMarks().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSecurityMarks[0:len(c.CallOptions.UpdateSecurityMarks):len(c.CallOptions.UpdateSecurityMarks)], opts...) + opts = append((*c.CallOptions).UpdateSecurityMarks[0:len((*c.CallOptions).UpdateSecurityMarks):len((*c.CallOptions).UpdateSecurityMarks)], opts...) var resp *securitycenterpb.SecurityMarks err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -965,9 +1137,9 @@ type RunAssetDiscoveryOperation struct { // RunAssetDiscoveryOperation returns a new RunAssetDiscoveryOperation from a given name. // The name must be that of a previously created RunAssetDiscoveryOperation, possibly from a different process. -func (c *Client) RunAssetDiscoveryOperation(name string) *RunAssetDiscoveryOperation { +func (c *gRPCClient) RunAssetDiscoveryOperation(name string) *RunAssetDiscoveryOperation { return &RunAssetDiscoveryOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/securitycenter/apiv1p1beta1/security_center_client_example_test.go b/securitycenter/apiv1p1beta1/security_center_client_example_test.go index 836c0c1705cb..0e3d7038a270 100644 --- a/securitycenter/apiv1p1beta1/security_center_client_example_test.go +++ b/securitycenter/apiv1p1beta1/security_center_client_example_test.go @@ -31,18 +31,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateSource() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.CreateSourceRequest{ // TODO: Fill request struct fields. @@ -56,13 +57,12 @@ func ExampleClient_CreateSource() { } func ExampleClient_CreateFinding() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.CreateFindingRequest{ // TODO: Fill request struct fields. @@ -76,13 +76,12 @@ func ExampleClient_CreateFinding() { } func ExampleClient_CreateNotificationConfig() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.CreateNotificationConfigRequest{ // TODO: Fill request struct fields. @@ -101,6 +100,7 @@ func ExampleClient_DeleteNotificationConfig() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.DeleteNotificationConfigRequest{ // TODO: Fill request struct fields. @@ -112,13 +112,12 @@ func ExampleClient_DeleteNotificationConfig() { } func ExampleClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -132,13 +131,12 @@ func ExampleClient_GetIamPolicy() { } func ExampleClient_GetNotificationConfig() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GetNotificationConfigRequest{ // TODO: Fill request struct fields. @@ -152,13 +150,12 @@ func ExampleClient_GetNotificationConfig() { } func ExampleClient_GetOrganizationSettings() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GetOrganizationSettingsRequest{ // TODO: Fill request struct fields. @@ -172,13 +169,12 @@ func ExampleClient_GetOrganizationSettings() { } func ExampleClient_GetSource() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GetSourceRequest{ // TODO: Fill request struct fields. @@ -192,14 +188,12 @@ func ExampleClient_GetSource() { } func ExampleClient_GroupAssets() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GroupAssetsRequest{ // TODO: Fill request struct fields. @@ -219,14 +213,12 @@ func ExampleClient_GroupAssets() { } func ExampleClient_GroupFindings() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.GroupFindingsRequest{ // TODO: Fill request struct fields. @@ -246,14 +238,12 @@ func ExampleClient_GroupFindings() { } func ExampleClient_ListAssets() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListAssetsRequest{ // TODO: Fill request struct fields. @@ -273,14 +263,12 @@ func ExampleClient_ListAssets() { } func ExampleClient_ListFindings() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListFindingsRequest{ // TODO: Fill request struct fields. @@ -300,14 +288,12 @@ func ExampleClient_ListFindings() { } func ExampleClient_ListNotificationConfigs() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListNotificationConfigsRequest{ // TODO: Fill request struct fields. @@ -327,14 +313,12 @@ func ExampleClient_ListNotificationConfigs() { } func ExampleClient_ListSources() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.ListSourcesRequest{ // TODO: Fill request struct fields. @@ -354,13 +338,12 @@ func ExampleClient_ListSources() { } func ExampleClient_RunAssetDiscovery() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.RunAssetDiscoveryRequest{ // TODO: Fill request struct fields. @@ -379,13 +362,12 @@ func ExampleClient_RunAssetDiscovery() { } func ExampleClient_SetFindingState() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.SetFindingStateRequest{ // TODO: Fill request struct fields. @@ -399,13 +381,12 @@ func ExampleClient_SetFindingState() { } func ExampleClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -419,13 +400,12 @@ func ExampleClient_SetIamPolicy() { } func ExampleClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. @@ -439,13 +419,12 @@ func ExampleClient_TestIamPermissions() { } func ExampleClient_UpdateFinding() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateFindingRequest{ // TODO: Fill request struct fields. @@ -459,13 +438,12 @@ func ExampleClient_UpdateFinding() { } func ExampleClient_UpdateNotificationConfig() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateNotificationConfigRequest{ // TODO: Fill request struct fields. @@ -479,13 +457,12 @@ func ExampleClient_UpdateNotificationConfig() { } func ExampleClient_UpdateOrganizationSettings() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateOrganizationSettingsRequest{ // TODO: Fill request struct fields. @@ -499,13 +476,12 @@ func ExampleClient_UpdateOrganizationSettings() { } func ExampleClient_UpdateSource() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateSourceRequest{ // TODO: Fill request struct fields. @@ -519,13 +495,12 @@ func ExampleClient_UpdateSource() { } func ExampleClient_UpdateSecurityMarks() { - // import securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1" - ctx := context.Background() c, err := securitycenter.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &securitycenterpb.UpdateSecurityMarksRequest{ // TODO: Fill request struct fields. diff --git a/securitycenter/settings/apiv1beta1/doc.go b/securitycenter/settings/apiv1beta1/doc.go index 7992d743d0bf..bd194be87fd5 100644 --- a/securitycenter/settings/apiv1beta1/doc.go +++ b/securitycenter/settings/apiv1beta1/doc.go @@ -20,6 +20,8 @@ // Cloud Security Command Center Settings API provides functionality to // retrieve and update configurations. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package settings // import "cloud.google.com/go/securitycenter/settings/apiv1beta1" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/securitycenter/settings/apiv1beta1/security_center_settings_client.go b/securitycenter/settings/apiv1beta1/security_center_settings_client.go index 98a34ef18f31..effaad104c5b 100644 --- a/securitycenter/settings/apiv1beta1/security_center_settings_client.go +++ b/securitycenter/settings/apiv1beta1/security_center_settings_client.go @@ -54,7 +54,7 @@ type SecurityCenterSettingsCallOptions struct { ListComponents []gax.CallOption } -func defaultSecurityCenterSettingsClientOptions() []option.ClientOption { +func defaultSecurityCenterSettingsGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("securitycenter.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("securitycenter.mtls.googleapis.com:443"), @@ -227,35 +227,192 @@ func defaultSecurityCenterSettingsCallOptions() *SecurityCenterSettingsCallOptio } } +// internalSecurityCenterSettingsClient is an interface that defines the methods availaible from Cloud Security Command Center API. +type internalSecurityCenterSettingsClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + GetServiceAccount(context.Context, *settingspb.GetServiceAccountRequest, ...gax.CallOption) (*settingspb.ServiceAccount, error) + GetSettings(context.Context, *settingspb.GetSettingsRequest, ...gax.CallOption) (*settingspb.Settings, error) + UpdateSettings(context.Context, *settingspb.UpdateSettingsRequest, ...gax.CallOption) (*settingspb.Settings, error) + ResetSettings(context.Context, *settingspb.ResetSettingsRequest, ...gax.CallOption) error + BatchGetSettings(context.Context, *settingspb.BatchGetSettingsRequest, ...gax.CallOption) (*settingspb.BatchGetSettingsResponse, error) + CalculateEffectiveSettings(context.Context, *settingspb.CalculateEffectiveSettingsRequest, ...gax.CallOption) (*settingspb.Settings, error) + BatchCalculateEffectiveSettings(context.Context, *settingspb.BatchCalculateEffectiveSettingsRequest, ...gax.CallOption) (*settingspb.BatchCalculateEffectiveSettingsResponse, error) + GetComponentSettings(context.Context, *settingspb.GetComponentSettingsRequest, ...gax.CallOption) (*settingspb.ComponentSettings, error) + UpdateComponentSettings(context.Context, *settingspb.UpdateComponentSettingsRequest, ...gax.CallOption) (*settingspb.ComponentSettings, error) + ResetComponentSettings(context.Context, *settingspb.ResetComponentSettingsRequest, ...gax.CallOption) error + CalculateEffectiveComponentSettings(context.Context, *settingspb.CalculateEffectiveComponentSettingsRequest, ...gax.CallOption) (*settingspb.ComponentSettings, error) + ListDetectors(context.Context, *settingspb.ListDetectorsRequest, ...gax.CallOption) *DetectorIterator + ListComponents(context.Context, *settingspb.ListComponentsRequest, ...gax.CallOption) *StringIterator +} + // SecurityCenterSettingsClient is a client for interacting with Cloud Security Command Center API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// API OverviewThe SecurityCenterSettingsService is a sub-api of +// securitycenter.googleapis.com. The service provides methods to manage +// Security Center Settings, and Component Settings for GCP organizations, +// folders, projects, and clusters. type SecurityCenterSettingsClient struct { + // The internal transport-dependent client. + internalClient internalSecurityCenterSettingsClient + + // The call options for this service. + CallOptions *SecurityCenterSettingsCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *SecurityCenterSettingsClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *SecurityCenterSettingsClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *SecurityCenterSettingsClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// GetServiceAccount retrieves the organizations service account, if it exists, otherwise it +// creates the organization service account. This API is idempotent and +// will only create a service account once. On subsequent calls it will +// return the previously created service account. SHA, SCC and CTD Infra +// Automation will use this SA. This SA will not have any permissions when +// created. The UI will provision this via IAM or the user will using +// their own internal process. This API only creates SAs on the organization. +// Folders are not supported and projects will use per-project SAs associated +// with APIs enabled on a project. This API will be called by the UX +// onboarding workflow. +func (c *SecurityCenterSettingsClient) GetServiceAccount(ctx context.Context, req *settingspb.GetServiceAccountRequest, opts ...gax.CallOption) (*settingspb.ServiceAccount, error) { + return c.internalClient.GetServiceAccount(ctx, req, opts...) +} + +// GetSettings gets the Settings. +func (c *SecurityCenterSettingsClient) GetSettings(ctx context.Context, req *settingspb.GetSettingsRequest, opts ...gax.CallOption) (*settingspb.Settings, error) { + return c.internalClient.GetSettings(ctx, req, opts...) +} + +// UpdateSettings updates the Settings. +func (c *SecurityCenterSettingsClient) UpdateSettings(ctx context.Context, req *settingspb.UpdateSettingsRequest, opts ...gax.CallOption) (*settingspb.Settings, error) { + return c.internalClient.UpdateSettings(ctx, req, opts...) +} + +// ResetSettings reset the organization, folder or project’s settings and return +// the settings of just that resource to the default. +// +// Settings are present at the organization, folder, project, and cluster +// levels. Using Reset on a sub-organization level will remove that resource’s +// override and result in the parent’s settings being used (eg: if Reset on a +// cluster, project settings will be used). +// +// Using Reset on organization will remove the override that was set and +// result in default settings being used. +func (c *SecurityCenterSettingsClient) ResetSettings(ctx context.Context, req *settingspb.ResetSettingsRequest, opts ...gax.CallOption) error { + return c.internalClient.ResetSettings(ctx, req, opts...) +} + +// BatchGetSettings gets a list of settings. +func (c *SecurityCenterSettingsClient) BatchGetSettings(ctx context.Context, req *settingspb.BatchGetSettingsRequest, opts ...gax.CallOption) (*settingspb.BatchGetSettingsResponse, error) { + return c.internalClient.BatchGetSettings(ctx, req, opts...) +} + +// CalculateEffectiveSettings calculateEffectiveSettings looks up all of the Security Center +// Settings resources in the GCP resource hierarchy, and calculates the +// effective settings on that resource by applying the following rules: +// +// Settings provided closer to the target resource take precedence over +// those further away (e.g. folder will override organization level +// settings). +// +// Product defaults can be overridden at org, folder, project, and cluster +// levels. +// +// Detectors will be filtered out if they belong to a billing tier the +// customer +// has not configured. +func (c *SecurityCenterSettingsClient) CalculateEffectiveSettings(ctx context.Context, req *settingspb.CalculateEffectiveSettingsRequest, opts ...gax.CallOption) (*settingspb.Settings, error) { + return c.internalClient.CalculateEffectiveSettings(ctx, req, opts...) +} + +// BatchCalculateEffectiveSettings gets a list of effective settings. +func (c *SecurityCenterSettingsClient) BatchCalculateEffectiveSettings(ctx context.Context, req *settingspb.BatchCalculateEffectiveSettingsRequest, opts ...gax.CallOption) (*settingspb.BatchCalculateEffectiveSettingsResponse, error) { + return c.internalClient.BatchCalculateEffectiveSettings(ctx, req, opts...) +} + +// GetComponentSettings gets the Component Settings. +func (c *SecurityCenterSettingsClient) GetComponentSettings(ctx context.Context, req *settingspb.GetComponentSettingsRequest, opts ...gax.CallOption) (*settingspb.ComponentSettings, error) { + return c.internalClient.GetComponentSettings(ctx, req, opts...) +} + +// UpdateComponentSettings updates the Component Settings. +func (c *SecurityCenterSettingsClient) UpdateComponentSettings(ctx context.Context, req *settingspb.UpdateComponentSettingsRequest, opts ...gax.CallOption) (*settingspb.ComponentSettings, error) { + return c.internalClient.UpdateComponentSettings(ctx, req, opts...) +} + +// ResetComponentSettings reset the organization, folder or project’s component settings and return +// the settings to the default. Settings are present at the +// organization, folder and project levels. Using Reset for a folder or +// project will remove the override that was set and result in the +// organization-level settings being used. +func (c *SecurityCenterSettingsClient) ResetComponentSettings(ctx context.Context, req *settingspb.ResetComponentSettingsRequest, opts ...gax.CallOption) error { + return c.internalClient.ResetComponentSettings(ctx, req, opts...) +} + +// CalculateEffectiveComponentSettings gets the Effective Component Settings. +func (c *SecurityCenterSettingsClient) CalculateEffectiveComponentSettings(ctx context.Context, req *settingspb.CalculateEffectiveComponentSettingsRequest, opts ...gax.CallOption) (*settingspb.ComponentSettings, error) { + return c.internalClient.CalculateEffectiveComponentSettings(ctx, req, opts...) +} + +// ListDetectors retrieves an unordered list of available detectors. +func (c *SecurityCenterSettingsClient) ListDetectors(ctx context.Context, req *settingspb.ListDetectorsRequest, opts ...gax.CallOption) *DetectorIterator { + return c.internalClient.ListDetectors(ctx, req, opts...) +} + +// ListComponents retrieves an unordered list of available SCC components. +func (c *SecurityCenterSettingsClient) ListComponents(ctx context.Context, req *settingspb.ListComponentsRequest, opts ...gax.CallOption) *StringIterator { + return c.internalClient.ListComponents(ctx, req, opts...) +} + +// securityCenterSettingsGRPCClient is a client for interacting with Cloud Security Command Center API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type securityCenterSettingsGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing SecurityCenterSettingsClient + CallOptions **SecurityCenterSettingsCallOptions + // The gRPC API client. securityCenterSettingsClient settingspb.SecurityCenterSettingsServiceClient - // The call options for this service. - CallOptions *SecurityCenterSettingsCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewSecurityCenterSettingsClient creates a new security center settings service client. +// NewSecurityCenterSettingsClient creates a new security center settings service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // API OverviewThe SecurityCenterSettingsService is a sub-api of // securitycenter.googleapis.com. The service provides methods to manage // Security Center Settings, and Component Settings for GCP organizations, // folders, projects, and clusters. func NewSecurityCenterSettingsClient(ctx context.Context, opts ...option.ClientOption) (*SecurityCenterSettingsClient, error) { - clientOpts := defaultSecurityCenterSettingsClientOptions() - + clientOpts := defaultSecurityCenterSettingsGRPCClientOptions() if newSecurityCenterSettingsClientHook != nil { hookOpts, err := newSecurityCenterSettingsClientHook(ctx, clientHookParams{}) if err != nil { @@ -273,51 +430,44 @@ func NewSecurityCenterSettingsClient(ctx context.Context, opts ...option.ClientO if err != nil { return nil, err } - c := &SecurityCenterSettingsClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultSecurityCenterSettingsCallOptions(), + client := SecurityCenterSettingsClient{CallOptions: defaultSecurityCenterSettingsCallOptions()} + c := &securityCenterSettingsGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, securityCenterSettingsClient: settingspb.NewSecurityCenterSettingsServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *SecurityCenterSettingsClient) Connection() *grpc.ClientConn { +func (c *securityCenterSettingsGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *SecurityCenterSettingsClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *SecurityCenterSettingsClient) setGoogleClientInfo(keyval ...string) { +func (c *securityCenterSettingsGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// GetServiceAccount retrieves the organizations service account, if it exists, otherwise it -// creates the organization service account. This API is idempotent and -// will only create a service account once. On subsequent calls it will -// return the previously created service account. SHA, SCC and CTD Infra -// Automation will use this SA. This SA will not have any permissions when -// created. The UI will provision this via IAM or the user will using -// their own internal process. This API only creates SAs on the organization. -// Folders are not supported and projects will use per-project SAs associated -// with APIs enabled on a project. This API will be called by the UX -// onboarding workflow. -func (c *SecurityCenterSettingsClient) GetServiceAccount(ctx context.Context, req *settingspb.GetServiceAccountRequest, opts ...gax.CallOption) (*settingspb.ServiceAccount, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *securityCenterSettingsGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *securityCenterSettingsGRPCClient) GetServiceAccount(ctx context.Context, req *settingspb.GetServiceAccountRequest, opts ...gax.CallOption) (*settingspb.ServiceAccount, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -325,7 +475,7 @@ func (c *SecurityCenterSettingsClient) GetServiceAccount(ctx context.Context, re } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetServiceAccount[0:len(c.CallOptions.GetServiceAccount):len(c.CallOptions.GetServiceAccount)], opts...) + opts = append((*c.CallOptions).GetServiceAccount[0:len((*c.CallOptions).GetServiceAccount):len((*c.CallOptions).GetServiceAccount)], opts...) var resp *settingspb.ServiceAccount err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -338,8 +488,7 @@ func (c *SecurityCenterSettingsClient) GetServiceAccount(ctx context.Context, re return resp, nil } -// GetSettings gets the Settings. -func (c *SecurityCenterSettingsClient) GetSettings(ctx context.Context, req *settingspb.GetSettingsRequest, opts ...gax.CallOption) (*settingspb.Settings, error) { +func (c *securityCenterSettingsGRPCClient) GetSettings(ctx context.Context, req *settingspb.GetSettingsRequest, opts ...gax.CallOption) (*settingspb.Settings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -347,7 +496,7 @@ func (c *SecurityCenterSettingsClient) GetSettings(ctx context.Context, req *set } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSettings[0:len(c.CallOptions.GetSettings):len(c.CallOptions.GetSettings)], opts...) + opts = append((*c.CallOptions).GetSettings[0:len((*c.CallOptions).GetSettings):len((*c.CallOptions).GetSettings)], opts...) var resp *settingspb.Settings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -360,8 +509,7 @@ func (c *SecurityCenterSettingsClient) GetSettings(ctx context.Context, req *set return resp, nil } -// UpdateSettings updates the Settings. -func (c *SecurityCenterSettingsClient) UpdateSettings(ctx context.Context, req *settingspb.UpdateSettingsRequest, opts ...gax.CallOption) (*settingspb.Settings, error) { +func (c *securityCenterSettingsGRPCClient) UpdateSettings(ctx context.Context, req *settingspb.UpdateSettingsRequest, opts ...gax.CallOption) (*settingspb.Settings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -369,7 +517,7 @@ func (c *SecurityCenterSettingsClient) UpdateSettings(ctx context.Context, req * } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "settings.name", url.QueryEscape(req.GetSettings().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSettings[0:len(c.CallOptions.UpdateSettings):len(c.CallOptions.UpdateSettings)], opts...) + opts = append((*c.CallOptions).UpdateSettings[0:len((*c.CallOptions).UpdateSettings):len((*c.CallOptions).UpdateSettings)], opts...) var resp *settingspb.Settings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -382,17 +530,7 @@ func (c *SecurityCenterSettingsClient) UpdateSettings(ctx context.Context, req * return resp, nil } -// ResetSettings reset the organization, folder or project’s settings and return -// the settings of just that resource to the default. -// -// Settings are present at the organization, folder, project, and cluster -// levels. Using Reset on a sub-organization level will remove that resource’s -// override and result in the parent’s settings being used (eg: if Reset on a -// cluster, project settings will be used). -// -// Using Reset on organization will remove the override that was set and -// result in default settings being used. -func (c *SecurityCenterSettingsClient) ResetSettings(ctx context.Context, req *settingspb.ResetSettingsRequest, opts ...gax.CallOption) error { +func (c *securityCenterSettingsGRPCClient) ResetSettings(ctx context.Context, req *settingspb.ResetSettingsRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -400,7 +538,7 @@ func (c *SecurityCenterSettingsClient) ResetSettings(ctx context.Context, req *s } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ResetSettings[0:len(c.CallOptions.ResetSettings):len(c.CallOptions.ResetSettings)], opts...) + opts = append((*c.CallOptions).ResetSettings[0:len((*c.CallOptions).ResetSettings):len((*c.CallOptions).ResetSettings)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.securityCenterSettingsClient.ResetSettings(ctx, req, settings.GRPC...) @@ -409,8 +547,7 @@ func (c *SecurityCenterSettingsClient) ResetSettings(ctx context.Context, req *s return err } -// BatchGetSettings gets a list of settings. -func (c *SecurityCenterSettingsClient) BatchGetSettings(ctx context.Context, req *settingspb.BatchGetSettingsRequest, opts ...gax.CallOption) (*settingspb.BatchGetSettingsResponse, error) { +func (c *securityCenterSettingsGRPCClient) BatchGetSettings(ctx context.Context, req *settingspb.BatchGetSettingsRequest, opts ...gax.CallOption) (*settingspb.BatchGetSettingsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -418,7 +555,7 @@ func (c *SecurityCenterSettingsClient) BatchGetSettings(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchGetSettings[0:len(c.CallOptions.BatchGetSettings):len(c.CallOptions.BatchGetSettings)], opts...) + opts = append((*c.CallOptions).BatchGetSettings[0:len((*c.CallOptions).BatchGetSettings):len((*c.CallOptions).BatchGetSettings)], opts...) var resp *settingspb.BatchGetSettingsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -431,21 +568,7 @@ func (c *SecurityCenterSettingsClient) BatchGetSettings(ctx context.Context, req return resp, nil } -// CalculateEffectiveSettings calculateEffectiveSettings looks up all of the Security Center -// Settings resources in the GCP resource hierarchy, and calculates the -// effective settings on that resource by applying the following rules: -// -// Settings provided closer to the target resource take precedence over -// those further away (e.g. folder will override organization level -// settings). -// -// Product defaults can be overridden at org, folder, project, and cluster -// levels. -// -// Detectors will be filtered out if they belong to a billing tier the -// customer -// has not configured. -func (c *SecurityCenterSettingsClient) CalculateEffectiveSettings(ctx context.Context, req *settingspb.CalculateEffectiveSettingsRequest, opts ...gax.CallOption) (*settingspb.Settings, error) { +func (c *securityCenterSettingsGRPCClient) CalculateEffectiveSettings(ctx context.Context, req *settingspb.CalculateEffectiveSettingsRequest, opts ...gax.CallOption) (*settingspb.Settings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -453,7 +576,7 @@ func (c *SecurityCenterSettingsClient) CalculateEffectiveSettings(ctx context.Co } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CalculateEffectiveSettings[0:len(c.CallOptions.CalculateEffectiveSettings):len(c.CallOptions.CalculateEffectiveSettings)], opts...) + opts = append((*c.CallOptions).CalculateEffectiveSettings[0:len((*c.CallOptions).CalculateEffectiveSettings):len((*c.CallOptions).CalculateEffectiveSettings)], opts...) var resp *settingspb.Settings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -466,8 +589,7 @@ func (c *SecurityCenterSettingsClient) CalculateEffectiveSettings(ctx context.Co return resp, nil } -// BatchCalculateEffectiveSettings gets a list of effective settings. -func (c *SecurityCenterSettingsClient) BatchCalculateEffectiveSettings(ctx context.Context, req *settingspb.BatchCalculateEffectiveSettingsRequest, opts ...gax.CallOption) (*settingspb.BatchCalculateEffectiveSettingsResponse, error) { +func (c *securityCenterSettingsGRPCClient) BatchCalculateEffectiveSettings(ctx context.Context, req *settingspb.BatchCalculateEffectiveSettingsRequest, opts ...gax.CallOption) (*settingspb.BatchCalculateEffectiveSettingsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -475,7 +597,7 @@ func (c *SecurityCenterSettingsClient) BatchCalculateEffectiveSettings(ctx conte } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchCalculateEffectiveSettings[0:len(c.CallOptions.BatchCalculateEffectiveSettings):len(c.CallOptions.BatchCalculateEffectiveSettings)], opts...) + opts = append((*c.CallOptions).BatchCalculateEffectiveSettings[0:len((*c.CallOptions).BatchCalculateEffectiveSettings):len((*c.CallOptions).BatchCalculateEffectiveSettings)], opts...) var resp *settingspb.BatchCalculateEffectiveSettingsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -488,8 +610,7 @@ func (c *SecurityCenterSettingsClient) BatchCalculateEffectiveSettings(ctx conte return resp, nil } -// GetComponentSettings gets the Component Settings. -func (c *SecurityCenterSettingsClient) GetComponentSettings(ctx context.Context, req *settingspb.GetComponentSettingsRequest, opts ...gax.CallOption) (*settingspb.ComponentSettings, error) { +func (c *securityCenterSettingsGRPCClient) GetComponentSettings(ctx context.Context, req *settingspb.GetComponentSettingsRequest, opts ...gax.CallOption) (*settingspb.ComponentSettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -497,7 +618,7 @@ func (c *SecurityCenterSettingsClient) GetComponentSettings(ctx context.Context, } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetComponentSettings[0:len(c.CallOptions.GetComponentSettings):len(c.CallOptions.GetComponentSettings)], opts...) + opts = append((*c.CallOptions).GetComponentSettings[0:len((*c.CallOptions).GetComponentSettings):len((*c.CallOptions).GetComponentSettings)], opts...) var resp *settingspb.ComponentSettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -510,8 +631,7 @@ func (c *SecurityCenterSettingsClient) GetComponentSettings(ctx context.Context, return resp, nil } -// UpdateComponentSettings updates the Component Settings. -func (c *SecurityCenterSettingsClient) UpdateComponentSettings(ctx context.Context, req *settingspb.UpdateComponentSettingsRequest, opts ...gax.CallOption) (*settingspb.ComponentSettings, error) { +func (c *securityCenterSettingsGRPCClient) UpdateComponentSettings(ctx context.Context, req *settingspb.UpdateComponentSettingsRequest, opts ...gax.CallOption) (*settingspb.ComponentSettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -519,7 +639,7 @@ func (c *SecurityCenterSettingsClient) UpdateComponentSettings(ctx context.Conte } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "component_settings.name", url.QueryEscape(req.GetComponentSettings().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateComponentSettings[0:len(c.CallOptions.UpdateComponentSettings):len(c.CallOptions.UpdateComponentSettings)], opts...) + opts = append((*c.CallOptions).UpdateComponentSettings[0:len((*c.CallOptions).UpdateComponentSettings):len((*c.CallOptions).UpdateComponentSettings)], opts...) var resp *settingspb.ComponentSettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -532,12 +652,7 @@ func (c *SecurityCenterSettingsClient) UpdateComponentSettings(ctx context.Conte return resp, nil } -// ResetComponentSettings reset the organization, folder or project’s component settings and return -// the settings to the default. Settings are present at the -// organization, folder and project levels. Using Reset for a folder or -// project will remove the override that was set and result in the -// organization-level settings being used. -func (c *SecurityCenterSettingsClient) ResetComponentSettings(ctx context.Context, req *settingspb.ResetComponentSettingsRequest, opts ...gax.CallOption) error { +func (c *securityCenterSettingsGRPCClient) ResetComponentSettings(ctx context.Context, req *settingspb.ResetComponentSettingsRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -545,7 +660,7 @@ func (c *SecurityCenterSettingsClient) ResetComponentSettings(ctx context.Contex } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ResetComponentSettings[0:len(c.CallOptions.ResetComponentSettings):len(c.CallOptions.ResetComponentSettings)], opts...) + opts = append((*c.CallOptions).ResetComponentSettings[0:len((*c.CallOptions).ResetComponentSettings):len((*c.CallOptions).ResetComponentSettings)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.securityCenterSettingsClient.ResetComponentSettings(ctx, req, settings.GRPC...) @@ -554,8 +669,7 @@ func (c *SecurityCenterSettingsClient) ResetComponentSettings(ctx context.Contex return err } -// CalculateEffectiveComponentSettings gets the Effective Component Settings. -func (c *SecurityCenterSettingsClient) CalculateEffectiveComponentSettings(ctx context.Context, req *settingspb.CalculateEffectiveComponentSettingsRequest, opts ...gax.CallOption) (*settingspb.ComponentSettings, error) { +func (c *securityCenterSettingsGRPCClient) CalculateEffectiveComponentSettings(ctx context.Context, req *settingspb.CalculateEffectiveComponentSettingsRequest, opts ...gax.CallOption) (*settingspb.ComponentSettings, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -563,7 +677,7 @@ func (c *SecurityCenterSettingsClient) CalculateEffectiveComponentSettings(ctx c } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CalculateEffectiveComponentSettings[0:len(c.CallOptions.CalculateEffectiveComponentSettings):len(c.CallOptions.CalculateEffectiveComponentSettings)], opts...) + opts = append((*c.CallOptions).CalculateEffectiveComponentSettings[0:len((*c.CallOptions).CalculateEffectiveComponentSettings):len((*c.CallOptions).CalculateEffectiveComponentSettings)], opts...) var resp *settingspb.ComponentSettings err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -576,11 +690,10 @@ func (c *SecurityCenterSettingsClient) CalculateEffectiveComponentSettings(ctx c return resp, nil } -// ListDetectors retrieves an unordered list of available detectors. -func (c *SecurityCenterSettingsClient) ListDetectors(ctx context.Context, req *settingspb.ListDetectorsRequest, opts ...gax.CallOption) *DetectorIterator { +func (c *securityCenterSettingsGRPCClient) ListDetectors(ctx context.Context, req *settingspb.ListDetectorsRequest, opts ...gax.CallOption) *DetectorIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDetectors[0:len(c.CallOptions.ListDetectors):len(c.CallOptions.ListDetectors)], opts...) + opts = append((*c.CallOptions).ListDetectors[0:len((*c.CallOptions).ListDetectors):len((*c.CallOptions).ListDetectors)], opts...) it := &DetectorIterator{} req = proto.Clone(req).(*settingspb.ListDetectorsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*settingspb.Detector, string, error) { @@ -617,11 +730,10 @@ func (c *SecurityCenterSettingsClient) ListDetectors(ctx context.Context, req *s return it } -// ListComponents retrieves an unordered list of available SCC components. -func (c *SecurityCenterSettingsClient) ListComponents(ctx context.Context, req *settingspb.ListComponentsRequest, opts ...gax.CallOption) *StringIterator { +func (c *securityCenterSettingsGRPCClient) ListComponents(ctx context.Context, req *settingspb.ListComponentsRequest, opts ...gax.CallOption) *StringIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListComponents[0:len(c.CallOptions.ListComponents):len(c.CallOptions.ListComponents)], opts...) + opts = append((*c.CallOptions).ListComponents[0:len((*c.CallOptions).ListComponents):len((*c.CallOptions).ListComponents)], opts...) it := &StringIterator{} req = proto.Clone(req).(*settingspb.ListComponentsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]string, string, error) { diff --git a/securitycenter/settings/apiv1beta1/security_center_settings_client_example_test.go b/securitycenter/settings/apiv1beta1/security_center_settings_client_example_test.go index 66de834dde01..e30ba3b6f538 100644 --- a/securitycenter/settings/apiv1beta1/security_center_settings_client_example_test.go +++ b/securitycenter/settings/apiv1beta1/security_center_settings_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewSecurityCenterSettingsClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleSecurityCenterSettingsClient_GetServiceAccount() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.GetServiceAccountRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleSecurityCenterSettingsClient_GetServiceAccount() { } func ExampleSecurityCenterSettingsClient_GetSettings() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.GetSettingsRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleSecurityCenterSettingsClient_GetSettings() { } func ExampleSecurityCenterSettingsClient_UpdateSettings() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.UpdateSettingsRequest{ // TODO: Fill request struct fields. @@ -100,6 +99,7 @@ func ExampleSecurityCenterSettingsClient_ResetSettings() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.ResetSettingsRequest{ // TODO: Fill request struct fields. @@ -111,13 +111,12 @@ func ExampleSecurityCenterSettingsClient_ResetSettings() { } func ExampleSecurityCenterSettingsClient_BatchGetSettings() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.BatchGetSettingsRequest{ // TODO: Fill request struct fields. @@ -131,13 +130,12 @@ func ExampleSecurityCenterSettingsClient_BatchGetSettings() { } func ExampleSecurityCenterSettingsClient_CalculateEffectiveSettings() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.CalculateEffectiveSettingsRequest{ // TODO: Fill request struct fields. @@ -151,13 +149,12 @@ func ExampleSecurityCenterSettingsClient_CalculateEffectiveSettings() { } func ExampleSecurityCenterSettingsClient_BatchCalculateEffectiveSettings() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.BatchCalculateEffectiveSettingsRequest{ // TODO: Fill request struct fields. @@ -171,13 +168,12 @@ func ExampleSecurityCenterSettingsClient_BatchCalculateEffectiveSettings() { } func ExampleSecurityCenterSettingsClient_GetComponentSettings() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.GetComponentSettingsRequest{ // TODO: Fill request struct fields. @@ -191,13 +187,12 @@ func ExampleSecurityCenterSettingsClient_GetComponentSettings() { } func ExampleSecurityCenterSettingsClient_UpdateComponentSettings() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.UpdateComponentSettingsRequest{ // TODO: Fill request struct fields. @@ -216,6 +211,7 @@ func ExampleSecurityCenterSettingsClient_ResetComponentSettings() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.ResetComponentSettingsRequest{ // TODO: Fill request struct fields. @@ -227,13 +223,12 @@ func ExampleSecurityCenterSettingsClient_ResetComponentSettings() { } func ExampleSecurityCenterSettingsClient_CalculateEffectiveComponentSettings() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.CalculateEffectiveComponentSettingsRequest{ // TODO: Fill request struct fields. @@ -247,14 +242,12 @@ func ExampleSecurityCenterSettingsClient_CalculateEffectiveComponentSettings() { } func ExampleSecurityCenterSettingsClient_ListDetectors() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.ListDetectorsRequest{ // TODO: Fill request struct fields. @@ -274,14 +267,12 @@ func ExampleSecurityCenterSettingsClient_ListDetectors() { } func ExampleSecurityCenterSettingsClient_ListComponents() { - // import settingspb "google.golang.org/genproto/googleapis/cloud/securitycenter/settings/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := settings.NewSecurityCenterSettingsClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &settingspb.ListComponentsRequest{ // TODO: Fill request struct fields. diff --git a/servicecontrol/apiv1/doc.go b/servicecontrol/apiv1/doc.go index 886572ae342a..a06ce69b608f 100644 --- a/servicecontrol/apiv1/doc.go +++ b/servicecontrol/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package servicecontrol // import "cloud.google.com/go/servicecontrol/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/servicecontrol/apiv1/quota_controller_client.go b/servicecontrol/apiv1/quota_controller_client.go index 1acd2b60e857..d1ca9b522105 100644 --- a/servicecontrol/apiv1/quota_controller_client.go +++ b/servicecontrol/apiv1/quota_controller_client.go @@ -38,7 +38,7 @@ type QuotaControllerCallOptions struct { AllocateQuota []gax.CallOption } -func defaultQuotaControllerClientOptions() []option.ClientOption { +func defaultQuotaControllerGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("servicecontrol.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("servicecontrol.mtls.googleapis.com:443"), @@ -56,35 +56,95 @@ func defaultQuotaControllerCallOptions() *QuotaControllerCallOptions { } } +// internalQuotaControllerClient is an interface that defines the methods availaible from Service Control API. +type internalQuotaControllerClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + AllocateQuota(context.Context, *servicecontrolpb.AllocateQuotaRequest, ...gax.CallOption) (*servicecontrolpb.AllocateQuotaResponse, error) +} + // QuotaControllerClient is a client for interacting with Service Control API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Google Quota Control API (at https://cloud.google.com/service-control/overview) +// +// Allows clients to allocate and release quota against a managed +// service (at https://cloud.google.com/service-management/reference/rpc/google.api/servicemanagement.v1#google.api.servicemanagement.v1.ManagedService). type QuotaControllerClient struct { + // The internal transport-dependent client. + internalClient internalQuotaControllerClient + + // The call options for this service. + CallOptions *QuotaControllerCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *QuotaControllerClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *QuotaControllerClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *QuotaControllerClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// AllocateQuota attempts to allocate quota for the specified consumer. It should be called +// before the operation is executed. +// +// This method requires the servicemanagement.services.quota +// permission on the specified service. For more information, see +// Cloud IAM (at https://cloud.google.com/iam). +// +// NOTE: The client must fail-open on server errors INTERNAL, +// UNKNOWN, DEADLINE_EXCEEDED, and UNAVAILABLE. To ensure system +// reliability, the server may inject these errors to prohibit any hard +// dependency on the quota functionality. +func (c *QuotaControllerClient) AllocateQuota(ctx context.Context, req *servicecontrolpb.AllocateQuotaRequest, opts ...gax.CallOption) (*servicecontrolpb.AllocateQuotaResponse, error) { + return c.internalClient.AllocateQuota(ctx, req, opts...) +} + +// quotaControllerGRPCClient is a client for interacting with Service Control API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type quotaControllerGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing QuotaControllerClient + CallOptions **QuotaControllerCallOptions + // The gRPC API client. quotaControllerClient servicecontrolpb.QuotaControllerClient - // The call options for this service. - CallOptions *QuotaControllerCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewQuotaControllerClient creates a new quota controller client. +// NewQuotaControllerClient creates a new quota controller client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Google Quota Control API (at https://cloud.google.com/service-control/overview) // // Allows clients to allocate and release quota against a managed // service (at https://cloud.google.com/service-management/reference/rpc/google.api/servicemanagement.v1#google.api.servicemanagement.v1.ManagedService). func NewQuotaControllerClient(ctx context.Context, opts ...option.ClientOption) (*QuotaControllerClient, error) { - clientOpts := defaultQuotaControllerClientOptions() - + clientOpts := defaultQuotaControllerGRPCClientOptions() if newQuotaControllerClientHook != nil { hookOpts, err := newQuotaControllerClientHook(ctx, clientHookParams{}) if err != nil { @@ -102,55 +162,47 @@ func NewQuotaControllerClient(ctx context.Context, opts ...option.ClientOption) if err != nil { return nil, err } - c := &QuotaControllerClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultQuotaControllerCallOptions(), + client := QuotaControllerClient{CallOptions: defaultQuotaControllerCallOptions()} + c := "aControllerGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, quotaControllerClient: servicecontrolpb.NewQuotaControllerClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *QuotaControllerClient) Connection() *grpc.ClientConn { +func (c *quotaControllerGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *QuotaControllerClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *QuotaControllerClient) setGoogleClientInfo(keyval ...string) { +func (c *quotaControllerGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// AllocateQuota attempts to allocate quota for the specified consumer. It should be called -// before the operation is executed. -// -// This method requires the servicemanagement.services.quota -// permission on the specified service. For more information, see -// Cloud IAM (at https://cloud.google.com/iam). -// -// NOTE: The client must fail-open on server errors INTERNAL, -// UNKNOWN, DEADLINE_EXCEEDED, and UNAVAILABLE. To ensure system -// reliability, the server may inject these errors to prohibit any hard -// dependency on the quota functionality. -func (c *QuotaControllerClient) AllocateQuota(ctx context.Context, req *servicecontrolpb.AllocateQuotaRequest, opts ...gax.CallOption) (*servicecontrolpb.AllocateQuotaResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *quotaControllerGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *quotaControllerGRPCClient) AllocateQuota(ctx context.Context, req *servicecontrolpb.AllocateQuotaRequest, opts ...gax.CallOption) (*servicecontrolpb.AllocateQuotaResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AllocateQuota[0:len(c.CallOptions.AllocateQuota):len(c.CallOptions.AllocateQuota)], opts...) + opts = append((*c.CallOptions).AllocateQuota[0:len((*c.CallOptions).AllocateQuota):len((*c.CallOptions).AllocateQuota)], opts...) var resp *servicecontrolpb.AllocateQuotaResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/servicecontrol/apiv1/quota_controller_client_example_test.go b/servicecontrol/apiv1/quota_controller_client_example_test.go index bb015981be7f..1b4d0beb960f 100644 --- a/servicecontrol/apiv1/quota_controller_client_example_test.go +++ b/servicecontrol/apiv1/quota_controller_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewQuotaControllerClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleQuotaControllerClient_AllocateQuota() { - // import servicecontrolpb "google.golang.org/genproto/googleapis/api/servicecontrol/v1" - ctx := context.Background() c, err := servicecontrol.NewQuotaControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicecontrolpb.AllocateQuotaRequest{ // TODO: Fill request struct fields. diff --git a/servicecontrol/apiv1/service_controller_client.go b/servicecontrol/apiv1/service_controller_client.go index 77391413e313..e75c10bba6bd 100644 --- a/servicecontrol/apiv1/service_controller_client.go +++ b/servicecontrol/apiv1/service_controller_client.go @@ -39,7 +39,7 @@ type ServiceControllerCallOptions struct { Report []gax.CallOption } -func defaultServiceControllerClientOptions() []option.ClientOption { +func defaultServiceControllerGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("servicecontrol.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("servicecontrol.mtls.googleapis.com:443"), @@ -58,35 +58,120 @@ func defaultServiceControllerCallOptions() *ServiceControllerCallOptions { } } +// internalServiceControllerClient is an interface that defines the methods availaible from Service Control API. +type internalServiceControllerClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + Check(context.Context, *servicecontrolpb.CheckRequest, ...gax.CallOption) (*servicecontrolpb.CheckResponse, error) + Report(context.Context, *servicecontrolpb.ReportRequest, ...gax.CallOption) (*servicecontrolpb.ReportResponse, error) +} + // ServiceControllerClient is a client for interacting with Service Control API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Google Service Control API (at https://cloud.google.com/service-control/overview) +// +// Lets clients check and report operations against a managed +// service (at https://cloud.google.com/service-management/reference/rpc/google.api/servicemanagement.v1#google.api.servicemanagement.v1.ManagedService). type ServiceControllerClient struct { + // The internal transport-dependent client. + internalClient internalServiceControllerClient + + // The call options for this service. + CallOptions *ServiceControllerCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ServiceControllerClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ServiceControllerClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ServiceControllerClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// Check checks whether an operation on a service should be allowed to proceed +// based on the configuration of the service and related policies. It must be +// called before the operation is executed. +// +// If feasible, the client should cache the check results and reuse them for +// 60 seconds. In case of any server errors, the client should rely on the +// cached results for much longer time to avoid outage. +// WARNING: There is general 60s delay for the configuration and policy +// propagation, therefore callers MUST NOT depend on the Check method having +// the latest policy information. +// +// NOTE: the CheckRequest has the size limit of 64KB. +// +// This method requires the servicemanagement.services.check permission +// on the specified service. For more information, see +// Cloud IAM (at https://cloud.google.com/iam). +func (c *ServiceControllerClient) Check(ctx context.Context, req *servicecontrolpb.CheckRequest, opts ...gax.CallOption) (*servicecontrolpb.CheckResponse, error) { + return c.internalClient.Check(ctx, req, opts...) +} + +// Report reports operation results to Google Service Control, such as logs and +// metrics. It should be called after an operation is completed. +// +// If feasible, the client should aggregate reporting data for up to 5 +// seconds to reduce API traffic. Limiting aggregation to 5 seconds is to +// reduce data loss during client crashes. Clients should carefully choose +// the aggregation time window to avoid data loss risk more than 0.01% +// for business and compliance reasons. +// +// NOTE: the ReportRequest has the size limit (wire-format byte size) of +// 1MB. +// +// This method requires the servicemanagement.services.report permission +// on the specified service. For more information, see +// Google Cloud IAM (at https://cloud.google.com/iam). +func (c *ServiceControllerClient) Report(ctx context.Context, req *servicecontrolpb.ReportRequest, opts ...gax.CallOption) (*servicecontrolpb.ReportResponse, error) { + return c.internalClient.Report(ctx, req, opts...) +} + +// serviceControllerGRPCClient is a client for interacting with Service Control API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type serviceControllerGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ServiceControllerClient + CallOptions **ServiceControllerCallOptions + // The gRPC API client. serviceControllerClient servicecontrolpb.ServiceControllerClient - // The call options for this service. - CallOptions *ServiceControllerCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewServiceControllerClient creates a new service controller client. +// NewServiceControllerClient creates a new service controller client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Google Service Control API (at https://cloud.google.com/service-control/overview) // // Lets clients check and report operations against a managed // service (at https://cloud.google.com/service-management/reference/rpc/google.api/servicemanagement.v1#google.api.servicemanagement.v1.ManagedService). func NewServiceControllerClient(ctx context.Context, opts ...option.ClientOption) (*ServiceControllerClient, error) { - clientOpts := defaultServiceControllerClientOptions() - + clientOpts := defaultServiceControllerGRPCClientOptions() if newServiceControllerClientHook != nil { hookOpts, err := newServiceControllerClientHook(ctx, clientHookParams{}) if err != nil { @@ -104,60 +189,47 @@ func NewServiceControllerClient(ctx context.Context, opts ...option.ClientOption if err != nil { return nil, err } - c := &ServiceControllerClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultServiceControllerCallOptions(), + client := ServiceControllerClient{CallOptions: defaultServiceControllerCallOptions()} + c := &serviceControllerGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, serviceControllerClient: servicecontrolpb.NewServiceControllerClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ServiceControllerClient) Connection() *grpc.ClientConn { +func (c *serviceControllerGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ServiceControllerClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ServiceControllerClient) setGoogleClientInfo(keyval ...string) { +func (c *serviceControllerGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// Check checks whether an operation on a service should be allowed to proceed -// based on the configuration of the service and related policies. It must be -// called before the operation is executed. -// -// If feasible, the client should cache the check results and reuse them for -// 60 seconds. In case of any server errors, the client should rely on the -// cached results for much longer time to avoid outage. -// WARNING: There is general 60s delay for the configuration and policy -// propagation, therefore callers MUST NOT depend on the Check method having -// the latest policy information. -// -// NOTE: the CheckRequest has the size limit of 64KB. -// -// This method requires the servicemanagement.services.check permission -// on the specified service. For more information, see -// Cloud IAM (at https://cloud.google.com/iam). -func (c *ServiceControllerClient) Check(ctx context.Context, req *servicecontrolpb.CheckRequest, opts ...gax.CallOption) (*servicecontrolpb.CheckResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *serviceControllerGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *serviceControllerGRPCClient) Check(ctx context.Context, req *servicecontrolpb.CheckRequest, opts ...gax.CallOption) (*servicecontrolpb.CheckResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.Check[0:len(c.CallOptions.Check):len(c.CallOptions.Check)], opts...) + opts = append((*c.CallOptions).Check[0:len((*c.CallOptions).Check):len((*c.CallOptions).Check)], opts...) var resp *servicecontrolpb.CheckResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -170,25 +242,10 @@ func (c *ServiceControllerClient) Check(ctx context.Context, req *servicecontrol return resp, nil } -// Report reports operation results to Google Service Control, such as logs and -// metrics. It should be called after an operation is completed. -// -// If feasible, the client should aggregate reporting data for up to 5 -// seconds to reduce API traffic. Limiting aggregation to 5 seconds is to -// reduce data loss during client crashes. Clients should carefully choose -// the aggregation time window to avoid data loss risk more than 0.01% -// for business and compliance reasons. -// -// NOTE: the ReportRequest has the size limit (wire-format byte size) of -// 1MB. -// -// This method requires the servicemanagement.services.report permission -// on the specified service. For more information, see -// Google Cloud IAM (at https://cloud.google.com/iam). -func (c *ServiceControllerClient) Report(ctx context.Context, req *servicecontrolpb.ReportRequest, opts ...gax.CallOption) (*servicecontrolpb.ReportResponse, error) { +func (c *serviceControllerGRPCClient) Report(ctx context.Context, req *servicecontrolpb.ReportRequest, opts ...gax.CallOption) (*servicecontrolpb.ReportResponse, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.Report[0:len(c.CallOptions.Report):len(c.CallOptions.Report)], opts...) + opts = append((*c.CallOptions).Report[0:len((*c.CallOptions).Report):len((*c.CallOptions).Report)], opts...) var resp *servicecontrolpb.ReportResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/servicecontrol/apiv1/service_controller_client_example_test.go b/servicecontrol/apiv1/service_controller_client_example_test.go index 8894f62d58a7..adbbcc352a19 100644 --- a/servicecontrol/apiv1/service_controller_client_example_test.go +++ b/servicecontrol/apiv1/service_controller_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewServiceControllerClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleServiceControllerClient_Check() { - // import servicecontrolpb "google.golang.org/genproto/googleapis/api/servicecontrol/v1" - ctx := context.Background() c, err := servicecontrol.NewServiceControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicecontrolpb.CheckRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleServiceControllerClient_Check() { } func ExampleServiceControllerClient_Report() { - // import servicecontrolpb "google.golang.org/genproto/googleapis/api/servicecontrol/v1" - ctx := context.Background() c, err := servicecontrol.NewServiceControllerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicecontrolpb.ReportRequest{ // TODO: Fill request struct fields. diff --git a/servicedirectory/apiv1/doc.go b/servicedirectory/apiv1/doc.go index f9c3720cee3b..2c30c09aafd2 100644 --- a/servicedirectory/apiv1/doc.go +++ b/servicedirectory/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package servicedirectory // import "cloud.google.com/go/servicedirectory/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/servicedirectory/apiv1/lookup_client.go b/servicedirectory/apiv1/lookup_client.go index 32c688483c9b..c9962a6a71e7 100644 --- a/servicedirectory/apiv1/lookup_client.go +++ b/servicedirectory/apiv1/lookup_client.go @@ -40,7 +40,7 @@ type LookupCallOptions struct { ResolveService []gax.CallOption } -func defaultLookupClientOptions() []option.ClientOption { +func defaultLookupGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("servicedirectory.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("servicedirectory.mtls.googleapis.com:443"), @@ -69,32 +69,81 @@ func defaultLookupCallOptions() *LookupCallOptions { } } +// internalLookupClient is an interface that defines the methods availaible from Service Directory API. +type internalLookupClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ResolveService(context.Context, *servicedirectorypb.ResolveServiceRequest, ...gax.CallOption) (*servicedirectorypb.ResolveServiceResponse, error) +} + // LookupClient is a client for interacting with Service Directory API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service Directory API for looking up service data at runtime. type LookupClient struct { + // The internal transport-dependent client. + internalClient internalLookupClient + + // The call options for this service. + CallOptions *LookupCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *LookupClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *LookupClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *LookupClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ResolveService returns a service and its +// associated endpoints. +// Resolving a service is not considered an active developer method. +func (c *LookupClient) ResolveService(ctx context.Context, req *servicedirectorypb.ResolveServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.ResolveServiceResponse, error) { + return c.internalClient.ResolveService(ctx, req, opts...) +} + +// lookupGRPCClient is a client for interacting with Service Directory API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type lookupGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing LookupClient + CallOptions **LookupCallOptions + // The gRPC API client. lookupClient servicedirectorypb.LookupServiceClient - // The call options for this service. - CallOptions *LookupCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewLookupClient creates a new lookup service client. +// NewLookupClient creates a new lookup service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service Directory API for looking up service data at runtime. func NewLookupClient(ctx context.Context, opts ...option.ClientOption) (*LookupClient, error) { - clientOpts := defaultLookupClientOptions() - + clientOpts := defaultLookupGRPCClientOptions() if newLookupClientHook != nil { hookOpts, err := newLookupClientHook(ctx, clientHookParams{}) if err != nil { @@ -112,44 +161,44 @@ func NewLookupClient(ctx context.Context, opts ...option.ClientOption) (*LookupC if err != nil { return nil, err } - c := &LookupClient{ + client := LookupClient{CallOptions: defaultLookupCallOptions()} + + c := &lookupGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultLookupCallOptions(), - - lookupClient: servicedirectorypb.NewLookupServiceClient(connPool), + lookupClient: servicedirectorypb.NewLookupServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *LookupClient) Connection() *grpc.ClientConn { +func (c *lookupGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *LookupClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *LookupClient) setGoogleClientInfo(keyval ...string) { +func (c *lookupGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ResolveService returns a service and its -// associated endpoints. -// Resolving a service is not considered an active developer method. -func (c *LookupClient) ResolveService(ctx context.Context, req *servicedirectorypb.ResolveServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.ResolveServiceResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *lookupGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *lookupGRPCClient) ResolveService(ctx context.Context, req *servicedirectorypb.ResolveServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.ResolveServiceResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -157,7 +206,7 @@ func (c *LookupClient) ResolveService(ctx context.Context, req *servicedirectory } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ResolveService[0:len(c.CallOptions.ResolveService):len(c.CallOptions.ResolveService)], opts...) + opts = append((*c.CallOptions).ResolveService[0:len((*c.CallOptions).ResolveService):len((*c.CallOptions).ResolveService)], opts...) var resp *servicedirectorypb.ResolveServiceResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/servicedirectory/apiv1/lookup_client_example_test.go b/servicedirectory/apiv1/lookup_client_example_test.go index 5d73be9afcf6..558a1465131c 100644 --- a/servicedirectory/apiv1/lookup_client_example_test.go +++ b/servicedirectory/apiv1/lookup_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewLookupClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleLookupClient_ResolveService() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewLookupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.ResolveServiceRequest{ // TODO: Fill request struct fields. diff --git a/servicedirectory/apiv1/registration_client.go b/servicedirectory/apiv1/registration_client.go index 925f9e42475a..10de1dba5647 100644 --- a/servicedirectory/apiv1/registration_client.go +++ b/servicedirectory/apiv1/registration_client.go @@ -60,7 +60,7 @@ type RegistrationCallOptions struct { TestIamPermissions []gax.CallOption } -func defaultRegistrationClientOptions() []option.ClientOption { +func defaultRegistrationGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("servicedirectory.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("servicedirectory.mtls.googleapis.com:443"), @@ -293,27 +293,193 @@ func defaultRegistrationCallOptions() *RegistrationCallOptions { } } +// internalRegistrationClient is an interface that defines the methods availaible from Service Directory API. +type internalRegistrationClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateNamespace(context.Context, *servicedirectorypb.CreateNamespaceRequest, ...gax.CallOption) (*servicedirectorypb.Namespace, error) + ListNamespaces(context.Context, *servicedirectorypb.ListNamespacesRequest, ...gax.CallOption) *NamespaceIterator + GetNamespace(context.Context, *servicedirectorypb.GetNamespaceRequest, ...gax.CallOption) (*servicedirectorypb.Namespace, error) + UpdateNamespace(context.Context, *servicedirectorypb.UpdateNamespaceRequest, ...gax.CallOption) (*servicedirectorypb.Namespace, error) + DeleteNamespace(context.Context, *servicedirectorypb.DeleteNamespaceRequest, ...gax.CallOption) error + CreateService(context.Context, *servicedirectorypb.CreateServiceRequest, ...gax.CallOption) (*servicedirectorypb.Service, error) + ListServices(context.Context, *servicedirectorypb.ListServicesRequest, ...gax.CallOption) *ServiceIterator + GetService(context.Context, *servicedirectorypb.GetServiceRequest, ...gax.CallOption) (*servicedirectorypb.Service, error) + UpdateService(context.Context, *servicedirectorypb.UpdateServiceRequest, ...gax.CallOption) (*servicedirectorypb.Service, error) + DeleteService(context.Context, *servicedirectorypb.DeleteServiceRequest, ...gax.CallOption) error + CreateEndpoint(context.Context, *servicedirectorypb.CreateEndpointRequest, ...gax.CallOption) (*servicedirectorypb.Endpoint, error) + ListEndpoints(context.Context, *servicedirectorypb.ListEndpointsRequest, ...gax.CallOption) *EndpointIterator + GetEndpoint(context.Context, *servicedirectorypb.GetEndpointRequest, ...gax.CallOption) (*servicedirectorypb.Endpoint, error) + UpdateEndpoint(context.Context, *servicedirectorypb.UpdateEndpointRequest, ...gax.CallOption) (*servicedirectorypb.Endpoint, error) + DeleteEndpoint(context.Context, *servicedirectorypb.DeleteEndpointRequest, ...gax.CallOption) error + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) +} + // RegistrationClient is a client for interacting with Service Directory API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service Directory API for registering services. It defines the following +// resource model: +// +// The API has a collection of +// Namespace +// resources, named projects/*/locations/*/namespaces/*. +// +// Each Namespace has a collection of +// Service resources, named +// projects/*/locations/*/namespaces/*/services/*. +// +// Each Service has a collection of +// Endpoint +// resources, named +// projects/*/locations/*/namespaces/*/services/*/endpoints/*. type RegistrationClient struct { + // The internal transport-dependent client. + internalClient internalRegistrationClient + + // The call options for this service. + CallOptions *RegistrationCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *RegistrationClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *RegistrationClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *RegistrationClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateNamespace creates a namespace, and returns the new Namespace. +func (c *RegistrationClient) CreateNamespace(ctx context.Context, req *servicedirectorypb.CreateNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { + return c.internalClient.CreateNamespace(ctx, req, opts...) +} + +// ListNamespaces lists all namespaces. +func (c *RegistrationClient) ListNamespaces(ctx context.Context, req *servicedirectorypb.ListNamespacesRequest, opts ...gax.CallOption) *NamespaceIterator { + return c.internalClient.ListNamespaces(ctx, req, opts...) +} + +// GetNamespace gets a namespace. +func (c *RegistrationClient) GetNamespace(ctx context.Context, req *servicedirectorypb.GetNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { + return c.internalClient.GetNamespace(ctx, req, opts...) +} + +// UpdateNamespace updates a namespace. +func (c *RegistrationClient) UpdateNamespace(ctx context.Context, req *servicedirectorypb.UpdateNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { + return c.internalClient.UpdateNamespace(ctx, req, opts...) +} + +// DeleteNamespace deletes a namespace. This also deletes all services and endpoints in +// the namespace. +func (c *RegistrationClient) DeleteNamespace(ctx context.Context, req *servicedirectorypb.DeleteNamespaceRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteNamespace(ctx, req, opts...) +} + +// CreateService creates a service, and returns the new Service. +func (c *RegistrationClient) CreateService(ctx context.Context, req *servicedirectorypb.CreateServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { + return c.internalClient.CreateService(ctx, req, opts...) +} + +// ListServices lists all services belonging to a namespace. +func (c *RegistrationClient) ListServices(ctx context.Context, req *servicedirectorypb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { + return c.internalClient.ListServices(ctx, req, opts...) +} + +// GetService gets a service. +func (c *RegistrationClient) GetService(ctx context.Context, req *servicedirectorypb.GetServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { + return c.internalClient.GetService(ctx, req, opts...) +} + +// UpdateService updates a service. +func (c *RegistrationClient) UpdateService(ctx context.Context, req *servicedirectorypb.UpdateServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { + return c.internalClient.UpdateService(ctx, req, opts...) +} + +// DeleteService deletes a service. This also deletes all endpoints associated with +// the service. +func (c *RegistrationClient) DeleteService(ctx context.Context, req *servicedirectorypb.DeleteServiceRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteService(ctx, req, opts...) +} + +// CreateEndpoint creates a endpoint, and returns the new Endpoint. +func (c *RegistrationClient) CreateEndpoint(ctx context.Context, req *servicedirectorypb.CreateEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { + return c.internalClient.CreateEndpoint(ctx, req, opts...) +} + +// ListEndpoints lists all endpoints. +func (c *RegistrationClient) ListEndpoints(ctx context.Context, req *servicedirectorypb.ListEndpointsRequest, opts ...gax.CallOption) *EndpointIterator { + return c.internalClient.ListEndpoints(ctx, req, opts...) +} + +// GetEndpoint gets a endpoint. +func (c *RegistrationClient) GetEndpoint(ctx context.Context, req *servicedirectorypb.GetEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { + return c.internalClient.GetEndpoint(ctx, req, opts...) +} + +// UpdateEndpoint updates a endpoint. +func (c *RegistrationClient) UpdateEndpoint(ctx context.Context, req *servicedirectorypb.UpdateEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { + return c.internalClient.UpdateEndpoint(ctx, req, opts...) +} + +// DeleteEndpoint deletes a endpoint. +func (c *RegistrationClient) DeleteEndpoint(ctx context.Context, req *servicedirectorypb.DeleteEndpointRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteEndpoint(ctx, req, opts...) +} + +// GetIamPolicy gets the IAM Policy for a resource (namespace or service only). +func (c *RegistrationClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// SetIamPolicy sets the IAM Policy for a resource (namespace or service only). +func (c *RegistrationClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions tests IAM permissions for a resource (namespace or service only). +func (c *RegistrationClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// registrationGRPCClient is a client for interacting with Service Directory API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type registrationGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing RegistrationClient + CallOptions **RegistrationCallOptions + // The gRPC API client. registrationClient servicedirectorypb.RegistrationServiceClient - // The call options for this service. - CallOptions *RegistrationCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewRegistrationClient creates a new registration service client. +// NewRegistrationClient creates a new registration service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service Directory API for registering services. It defines the following // resource model: @@ -331,8 +497,7 @@ type RegistrationClient struct { // resources, named // projects/*/locations/*/namespaces/*/services/*/endpoints/*. func NewRegistrationClient(ctx context.Context, opts ...option.ClientOption) (*RegistrationClient, error) { - clientOpts := defaultRegistrationClientOptions() - + clientOpts := defaultRegistrationGRPCClientOptions() if newRegistrationClientHook != nil { hookOpts, err := newRegistrationClientHook(ctx, clientHookParams{}) if err != nil { @@ -350,42 +515,44 @@ func NewRegistrationClient(ctx context.Context, opts ...option.ClientOption) (*R if err != nil { return nil, err } - c := &RegistrationClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultRegistrationCallOptions(), + client := RegistrationClient{CallOptions: defaultRegistrationCallOptions()} + c := ®istrationGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, registrationClient: servicedirectorypb.NewRegistrationServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *RegistrationClient) Connection() *grpc.ClientConn { +func (c *registrationGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *RegistrationClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *RegistrationClient) setGoogleClientInfo(keyval ...string) { +func (c *registrationGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateNamespace creates a namespace, and returns the new Namespace. -func (c *RegistrationClient) CreateNamespace(ctx context.Context, req *servicedirectorypb.CreateNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *registrationGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *registrationGRPCClient) CreateNamespace(ctx context.Context, req *servicedirectorypb.CreateNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -393,7 +560,7 @@ func (c *RegistrationClient) CreateNamespace(ctx context.Context, req *servicedi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateNamespace[0:len(c.CallOptions.CreateNamespace):len(c.CallOptions.CreateNamespace)], opts...) + opts = append((*c.CallOptions).CreateNamespace[0:len((*c.CallOptions).CreateNamespace):len((*c.CallOptions).CreateNamespace)], opts...) var resp *servicedirectorypb.Namespace err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -406,11 +573,10 @@ func (c *RegistrationClient) CreateNamespace(ctx context.Context, req *servicedi return resp, nil } -// ListNamespaces lists all namespaces. -func (c *RegistrationClient) ListNamespaces(ctx context.Context, req *servicedirectorypb.ListNamespacesRequest, opts ...gax.CallOption) *NamespaceIterator { +func (c *registrationGRPCClient) ListNamespaces(ctx context.Context, req *servicedirectorypb.ListNamespacesRequest, opts ...gax.CallOption) *NamespaceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListNamespaces[0:len(c.CallOptions.ListNamespaces):len(c.CallOptions.ListNamespaces)], opts...) + opts = append((*c.CallOptions).ListNamespaces[0:len((*c.CallOptions).ListNamespaces):len((*c.CallOptions).ListNamespaces)], opts...) it := &NamespaceIterator{} req = proto.Clone(req).(*servicedirectorypb.ListNamespacesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*servicedirectorypb.Namespace, string, error) { @@ -447,8 +613,7 @@ func (c *RegistrationClient) ListNamespaces(ctx context.Context, req *servicedir return it } -// GetNamespace gets a namespace. -func (c *RegistrationClient) GetNamespace(ctx context.Context, req *servicedirectorypb.GetNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { +func (c *registrationGRPCClient) GetNamespace(ctx context.Context, req *servicedirectorypb.GetNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -456,7 +621,7 @@ func (c *RegistrationClient) GetNamespace(ctx context.Context, req *servicedirec } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetNamespace[0:len(c.CallOptions.GetNamespace):len(c.CallOptions.GetNamespace)], opts...) + opts = append((*c.CallOptions).GetNamespace[0:len((*c.CallOptions).GetNamespace):len((*c.CallOptions).GetNamespace)], opts...) var resp *servicedirectorypb.Namespace err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -469,8 +634,7 @@ func (c *RegistrationClient) GetNamespace(ctx context.Context, req *servicedirec return resp, nil } -// UpdateNamespace updates a namespace. -func (c *RegistrationClient) UpdateNamespace(ctx context.Context, req *servicedirectorypb.UpdateNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { +func (c *registrationGRPCClient) UpdateNamespace(ctx context.Context, req *servicedirectorypb.UpdateNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -478,7 +642,7 @@ func (c *RegistrationClient) UpdateNamespace(ctx context.Context, req *servicedi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "namespace.name", url.QueryEscape(req.GetNamespace().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateNamespace[0:len(c.CallOptions.UpdateNamespace):len(c.CallOptions.UpdateNamespace)], opts...) + opts = append((*c.CallOptions).UpdateNamespace[0:len((*c.CallOptions).UpdateNamespace):len((*c.CallOptions).UpdateNamespace)], opts...) var resp *servicedirectorypb.Namespace err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -491,9 +655,7 @@ func (c *RegistrationClient) UpdateNamespace(ctx context.Context, req *servicedi return resp, nil } -// DeleteNamespace deletes a namespace. This also deletes all services and endpoints in -// the namespace. -func (c *RegistrationClient) DeleteNamespace(ctx context.Context, req *servicedirectorypb.DeleteNamespaceRequest, opts ...gax.CallOption) error { +func (c *registrationGRPCClient) DeleteNamespace(ctx context.Context, req *servicedirectorypb.DeleteNamespaceRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -501,7 +663,7 @@ func (c *RegistrationClient) DeleteNamespace(ctx context.Context, req *servicedi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteNamespace[0:len(c.CallOptions.DeleteNamespace):len(c.CallOptions.DeleteNamespace)], opts...) + opts = append((*c.CallOptions).DeleteNamespace[0:len((*c.CallOptions).DeleteNamespace):len((*c.CallOptions).DeleteNamespace)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.registrationClient.DeleteNamespace(ctx, req, settings.GRPC...) @@ -510,8 +672,7 @@ func (c *RegistrationClient) DeleteNamespace(ctx context.Context, req *servicedi return err } -// CreateService creates a service, and returns the new Service. -func (c *RegistrationClient) CreateService(ctx context.Context, req *servicedirectorypb.CreateServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { +func (c *registrationGRPCClient) CreateService(ctx context.Context, req *servicedirectorypb.CreateServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -519,7 +680,7 @@ func (c *RegistrationClient) CreateService(ctx context.Context, req *servicedire } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateService[0:len(c.CallOptions.CreateService):len(c.CallOptions.CreateService)], opts...) + opts = append((*c.CallOptions).CreateService[0:len((*c.CallOptions).CreateService):len((*c.CallOptions).CreateService)], opts...) var resp *servicedirectorypb.Service err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -532,11 +693,10 @@ func (c *RegistrationClient) CreateService(ctx context.Context, req *servicedire return resp, nil } -// ListServices lists all services belonging to a namespace. -func (c *RegistrationClient) ListServices(ctx context.Context, req *servicedirectorypb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { +func (c *registrationGRPCClient) ListServices(ctx context.Context, req *servicedirectorypb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListServices[0:len(c.CallOptions.ListServices):len(c.CallOptions.ListServices)], opts...) + opts = append((*c.CallOptions).ListServices[0:len((*c.CallOptions).ListServices):len((*c.CallOptions).ListServices)], opts...) it := &ServiceIterator{} req = proto.Clone(req).(*servicedirectorypb.ListServicesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*servicedirectorypb.Service, string, error) { @@ -573,8 +733,7 @@ func (c *RegistrationClient) ListServices(ctx context.Context, req *servicedirec return it } -// GetService gets a service. -func (c *RegistrationClient) GetService(ctx context.Context, req *servicedirectorypb.GetServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { +func (c *registrationGRPCClient) GetService(ctx context.Context, req *servicedirectorypb.GetServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -582,7 +741,7 @@ func (c *RegistrationClient) GetService(ctx context.Context, req *servicedirecto } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetService[0:len(c.CallOptions.GetService):len(c.CallOptions.GetService)], opts...) + opts = append((*c.CallOptions).GetService[0:len((*c.CallOptions).GetService):len((*c.CallOptions).GetService)], opts...) var resp *servicedirectorypb.Service err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -595,8 +754,7 @@ func (c *RegistrationClient) GetService(ctx context.Context, req *servicedirecto return resp, nil } -// UpdateService updates a service. -func (c *RegistrationClient) UpdateService(ctx context.Context, req *servicedirectorypb.UpdateServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { +func (c *registrationGRPCClient) UpdateService(ctx context.Context, req *servicedirectorypb.UpdateServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -604,7 +762,7 @@ func (c *RegistrationClient) UpdateService(ctx context.Context, req *servicedire } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service.name", url.QueryEscape(req.GetService().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateService[0:len(c.CallOptions.UpdateService):len(c.CallOptions.UpdateService)], opts...) + opts = append((*c.CallOptions).UpdateService[0:len((*c.CallOptions).UpdateService):len((*c.CallOptions).UpdateService)], opts...) var resp *servicedirectorypb.Service err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -617,9 +775,7 @@ func (c *RegistrationClient) UpdateService(ctx context.Context, req *servicedire return resp, nil } -// DeleteService deletes a service. This also deletes all endpoints associated with -// the service. -func (c *RegistrationClient) DeleteService(ctx context.Context, req *servicedirectorypb.DeleteServiceRequest, opts ...gax.CallOption) error { +func (c *registrationGRPCClient) DeleteService(ctx context.Context, req *servicedirectorypb.DeleteServiceRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -627,7 +783,7 @@ func (c *RegistrationClient) DeleteService(ctx context.Context, req *servicedire } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteService[0:len(c.CallOptions.DeleteService):len(c.CallOptions.DeleteService)], opts...) + opts = append((*c.CallOptions).DeleteService[0:len((*c.CallOptions).DeleteService):len((*c.CallOptions).DeleteService)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.registrationClient.DeleteService(ctx, req, settings.GRPC...) @@ -636,8 +792,7 @@ func (c *RegistrationClient) DeleteService(ctx context.Context, req *servicedire return err } -// CreateEndpoint creates a endpoint, and returns the new Endpoint. -func (c *RegistrationClient) CreateEndpoint(ctx context.Context, req *servicedirectorypb.CreateEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { +func (c *registrationGRPCClient) CreateEndpoint(ctx context.Context, req *servicedirectorypb.CreateEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -645,7 +800,7 @@ func (c *RegistrationClient) CreateEndpoint(ctx context.Context, req *servicedir } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateEndpoint[0:len(c.CallOptions.CreateEndpoint):len(c.CallOptions.CreateEndpoint)], opts...) + opts = append((*c.CallOptions).CreateEndpoint[0:len((*c.CallOptions).CreateEndpoint):len((*c.CallOptions).CreateEndpoint)], opts...) var resp *servicedirectorypb.Endpoint err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -658,11 +813,10 @@ func (c *RegistrationClient) CreateEndpoint(ctx context.Context, req *servicedir return resp, nil } -// ListEndpoints lists all endpoints. -func (c *RegistrationClient) ListEndpoints(ctx context.Context, req *servicedirectorypb.ListEndpointsRequest, opts ...gax.CallOption) *EndpointIterator { +func (c *registrationGRPCClient) ListEndpoints(ctx context.Context, req *servicedirectorypb.ListEndpointsRequest, opts ...gax.CallOption) *EndpointIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListEndpoints[0:len(c.CallOptions.ListEndpoints):len(c.CallOptions.ListEndpoints)], opts...) + opts = append((*c.CallOptions).ListEndpoints[0:len((*c.CallOptions).ListEndpoints):len((*c.CallOptions).ListEndpoints)], opts...) it := &EndpointIterator{} req = proto.Clone(req).(*servicedirectorypb.ListEndpointsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*servicedirectorypb.Endpoint, string, error) { @@ -699,8 +853,7 @@ func (c *RegistrationClient) ListEndpoints(ctx context.Context, req *servicedire return it } -// GetEndpoint gets a endpoint. -func (c *RegistrationClient) GetEndpoint(ctx context.Context, req *servicedirectorypb.GetEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { +func (c *registrationGRPCClient) GetEndpoint(ctx context.Context, req *servicedirectorypb.GetEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -708,7 +861,7 @@ func (c *RegistrationClient) GetEndpoint(ctx context.Context, req *servicedirect } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEndpoint[0:len(c.CallOptions.GetEndpoint):len(c.CallOptions.GetEndpoint)], opts...) + opts = append((*c.CallOptions).GetEndpoint[0:len((*c.CallOptions).GetEndpoint):len((*c.CallOptions).GetEndpoint)], opts...) var resp *servicedirectorypb.Endpoint err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -721,8 +874,7 @@ func (c *RegistrationClient) GetEndpoint(ctx context.Context, req *servicedirect return resp, nil } -// UpdateEndpoint updates a endpoint. -func (c *RegistrationClient) UpdateEndpoint(ctx context.Context, req *servicedirectorypb.UpdateEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { +func (c *registrationGRPCClient) UpdateEndpoint(ctx context.Context, req *servicedirectorypb.UpdateEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -730,7 +882,7 @@ func (c *RegistrationClient) UpdateEndpoint(ctx context.Context, req *servicedir } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "endpoint.name", url.QueryEscape(req.GetEndpoint().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateEndpoint[0:len(c.CallOptions.UpdateEndpoint):len(c.CallOptions.UpdateEndpoint)], opts...) + opts = append((*c.CallOptions).UpdateEndpoint[0:len((*c.CallOptions).UpdateEndpoint):len((*c.CallOptions).UpdateEndpoint)], opts...) var resp *servicedirectorypb.Endpoint err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -743,8 +895,7 @@ func (c *RegistrationClient) UpdateEndpoint(ctx context.Context, req *servicedir return resp, nil } -// DeleteEndpoint deletes a endpoint. -func (c *RegistrationClient) DeleteEndpoint(ctx context.Context, req *servicedirectorypb.DeleteEndpointRequest, opts ...gax.CallOption) error { +func (c *registrationGRPCClient) DeleteEndpoint(ctx context.Context, req *servicedirectorypb.DeleteEndpointRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -752,7 +903,7 @@ func (c *RegistrationClient) DeleteEndpoint(ctx context.Context, req *servicedir } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteEndpoint[0:len(c.CallOptions.DeleteEndpoint):len(c.CallOptions.DeleteEndpoint)], opts...) + opts = append((*c.CallOptions).DeleteEndpoint[0:len((*c.CallOptions).DeleteEndpoint):len((*c.CallOptions).DeleteEndpoint)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.registrationClient.DeleteEndpoint(ctx, req, settings.GRPC...) @@ -761,8 +912,7 @@ func (c *RegistrationClient) DeleteEndpoint(ctx context.Context, req *servicedir return err } -// GetIamPolicy gets the IAM Policy for a resource (namespace or service only). -func (c *RegistrationClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *registrationGRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -770,7 +920,7 @@ func (c *RegistrationClient) GetIamPolicy(ctx context.Context, req *iampb.GetIam } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -783,8 +933,7 @@ func (c *RegistrationClient) GetIamPolicy(ctx context.Context, req *iampb.GetIam return resp, nil } -// SetIamPolicy sets the IAM Policy for a resource (namespace or service only). -func (c *RegistrationClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *registrationGRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -792,7 +941,7 @@ func (c *RegistrationClient) SetIamPolicy(ctx context.Context, req *iampb.SetIam } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -805,8 +954,7 @@ func (c *RegistrationClient) SetIamPolicy(ctx context.Context, req *iampb.SetIam return resp, nil } -// TestIamPermissions tests IAM permissions for a resource (namespace or service only). -func (c *RegistrationClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *registrationGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -814,7 +962,7 @@ func (c *RegistrationClient) TestIamPermissions(ctx context.Context, req *iampb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/servicedirectory/apiv1/registration_client_example_test.go b/servicedirectory/apiv1/registration_client_example_test.go index 07cd99146ef0..d9cb791907eb 100644 --- a/servicedirectory/apiv1/registration_client_example_test.go +++ b/servicedirectory/apiv1/registration_client_example_test.go @@ -31,18 +31,19 @@ func ExampleNewRegistrationClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleRegistrationClient_CreateNamespace() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.CreateNamespaceRequest{ // TODO: Fill request struct fields. @@ -56,14 +57,12 @@ func ExampleRegistrationClient_CreateNamespace() { } func ExampleRegistrationClient_ListNamespaces() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.ListNamespacesRequest{ // TODO: Fill request struct fields. @@ -83,13 +82,12 @@ func ExampleRegistrationClient_ListNamespaces() { } func ExampleRegistrationClient_GetNamespace() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.GetNamespaceRequest{ // TODO: Fill request struct fields. @@ -103,13 +101,12 @@ func ExampleRegistrationClient_GetNamespace() { } func ExampleRegistrationClient_UpdateNamespace() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.UpdateNamespaceRequest{ // TODO: Fill request struct fields. @@ -128,6 +125,7 @@ func ExampleRegistrationClient_DeleteNamespace() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.DeleteNamespaceRequest{ // TODO: Fill request struct fields. @@ -139,13 +137,12 @@ func ExampleRegistrationClient_DeleteNamespace() { } func ExampleRegistrationClient_CreateService() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.CreateServiceRequest{ // TODO: Fill request struct fields. @@ -159,14 +156,12 @@ func ExampleRegistrationClient_CreateService() { } func ExampleRegistrationClient_ListServices() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.ListServicesRequest{ // TODO: Fill request struct fields. @@ -186,13 +181,12 @@ func ExampleRegistrationClient_ListServices() { } func ExampleRegistrationClient_GetService() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.GetServiceRequest{ // TODO: Fill request struct fields. @@ -206,13 +200,12 @@ func ExampleRegistrationClient_GetService() { } func ExampleRegistrationClient_UpdateService() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.UpdateServiceRequest{ // TODO: Fill request struct fields. @@ -231,6 +224,7 @@ func ExampleRegistrationClient_DeleteService() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.DeleteServiceRequest{ // TODO: Fill request struct fields. @@ -242,13 +236,12 @@ func ExampleRegistrationClient_DeleteService() { } func ExampleRegistrationClient_CreateEndpoint() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.CreateEndpointRequest{ // TODO: Fill request struct fields. @@ -262,14 +255,12 @@ func ExampleRegistrationClient_CreateEndpoint() { } func ExampleRegistrationClient_ListEndpoints() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.ListEndpointsRequest{ // TODO: Fill request struct fields. @@ -289,13 +280,12 @@ func ExampleRegistrationClient_ListEndpoints() { } func ExampleRegistrationClient_GetEndpoint() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.GetEndpointRequest{ // TODO: Fill request struct fields. @@ -309,13 +299,12 @@ func ExampleRegistrationClient_GetEndpoint() { } func ExampleRegistrationClient_UpdateEndpoint() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.UpdateEndpointRequest{ // TODO: Fill request struct fields. @@ -334,6 +323,7 @@ func ExampleRegistrationClient_DeleteEndpoint() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.DeleteEndpointRequest{ // TODO: Fill request struct fields. @@ -345,13 +335,12 @@ func ExampleRegistrationClient_DeleteEndpoint() { } func ExampleRegistrationClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -365,13 +354,12 @@ func ExampleRegistrationClient_GetIamPolicy() { } func ExampleRegistrationClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -385,13 +373,12 @@ func ExampleRegistrationClient_SetIamPolicy() { } func ExampleRegistrationClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/servicedirectory/apiv1beta1/doc.go b/servicedirectory/apiv1beta1/doc.go index e26f34e3e9ad..2ac9809c436b 100644 --- a/servicedirectory/apiv1beta1/doc.go +++ b/servicedirectory/apiv1beta1/doc.go @@ -19,6 +19,8 @@ // // Allows the registration and lookup of services. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -28,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package servicedirectory // import "cloud.google.com/go/servicedirectory/apiv1beta1" import ( @@ -48,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/servicedirectory/apiv1beta1/lookup_client.go b/servicedirectory/apiv1beta1/lookup_client.go index 5c1df35f8018..adc0be3af5fb 100644 --- a/servicedirectory/apiv1beta1/lookup_client.go +++ b/servicedirectory/apiv1beta1/lookup_client.go @@ -40,7 +40,7 @@ type LookupCallOptions struct { ResolveService []gax.CallOption } -func defaultLookupClientOptions() []option.ClientOption { +func defaultLookupGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("servicedirectory.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("servicedirectory.mtls.googleapis.com:443"), @@ -69,32 +69,81 @@ func defaultLookupCallOptions() *LookupCallOptions { } } +// internalLookupClient is an interface that defines the methods availaible from Service Directory API. +type internalLookupClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ResolveService(context.Context, *servicedirectorypb.ResolveServiceRequest, ...gax.CallOption) (*servicedirectorypb.ResolveServiceResponse, error) +} + // LookupClient is a client for interacting with Service Directory API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service Directory API for looking up service data at runtime. type LookupClient struct { + // The internal transport-dependent client. + internalClient internalLookupClient + + // The call options for this service. + CallOptions *LookupCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *LookupClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *LookupClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *LookupClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ResolveService returns a service and its +// associated endpoints. +// Resolving a service is not considered an active developer method. +func (c *LookupClient) ResolveService(ctx context.Context, req *servicedirectorypb.ResolveServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.ResolveServiceResponse, error) { + return c.internalClient.ResolveService(ctx, req, opts...) +} + +// lookupGRPCClient is a client for interacting with Service Directory API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type lookupGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing LookupClient + CallOptions **LookupCallOptions + // The gRPC API client. lookupClient servicedirectorypb.LookupServiceClient - // The call options for this service. - CallOptions *LookupCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewLookupClient creates a new lookup service client. +// NewLookupClient creates a new lookup service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service Directory API for looking up service data at runtime. func NewLookupClient(ctx context.Context, opts ...option.ClientOption) (*LookupClient, error) { - clientOpts := defaultLookupClientOptions() - + clientOpts := defaultLookupGRPCClientOptions() if newLookupClientHook != nil { hookOpts, err := newLookupClientHook(ctx, clientHookParams{}) if err != nil { @@ -112,44 +161,44 @@ func NewLookupClient(ctx context.Context, opts ...option.ClientOption) (*LookupC if err != nil { return nil, err } - c := &LookupClient{ + client := LookupClient{CallOptions: defaultLookupCallOptions()} + + c := &lookupGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultLookupCallOptions(), - - lookupClient: servicedirectorypb.NewLookupServiceClient(connPool), + lookupClient: servicedirectorypb.NewLookupServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *LookupClient) Connection() *grpc.ClientConn { +func (c *lookupGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *LookupClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *LookupClient) setGoogleClientInfo(keyval ...string) { +func (c *lookupGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ResolveService returns a service and its -// associated endpoints. -// Resolving a service is not considered an active developer method. -func (c *LookupClient) ResolveService(ctx context.Context, req *servicedirectorypb.ResolveServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.ResolveServiceResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *lookupGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *lookupGRPCClient) ResolveService(ctx context.Context, req *servicedirectorypb.ResolveServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.ResolveServiceResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -157,7 +206,7 @@ func (c *LookupClient) ResolveService(ctx context.Context, req *servicedirectory } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ResolveService[0:len(c.CallOptions.ResolveService):len(c.CallOptions.ResolveService)], opts...) + opts = append((*c.CallOptions).ResolveService[0:len((*c.CallOptions).ResolveService):len((*c.CallOptions).ResolveService)], opts...) var resp *servicedirectorypb.ResolveServiceResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/servicedirectory/apiv1beta1/lookup_client_example_test.go b/servicedirectory/apiv1beta1/lookup_client_example_test.go index bba8e1c3f366..911c705f647c 100644 --- a/servicedirectory/apiv1beta1/lookup_client_example_test.go +++ b/servicedirectory/apiv1beta1/lookup_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewLookupClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleLookupClient_ResolveService() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewLookupClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.ResolveServiceRequest{ // TODO: Fill request struct fields. diff --git a/servicedirectory/apiv1beta1/registration_client.go b/servicedirectory/apiv1beta1/registration_client.go index 75cc3c9a62cb..429842ad30dd 100644 --- a/servicedirectory/apiv1beta1/registration_client.go +++ b/servicedirectory/apiv1beta1/registration_client.go @@ -60,7 +60,7 @@ type RegistrationCallOptions struct { TestIamPermissions []gax.CallOption } -func defaultRegistrationClientOptions() []option.ClientOption { +func defaultRegistrationGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("servicedirectory.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("servicedirectory.mtls.googleapis.com:443"), @@ -293,27 +293,193 @@ func defaultRegistrationCallOptions() *RegistrationCallOptions { } } +// internalRegistrationClient is an interface that defines the methods availaible from Service Directory API. +type internalRegistrationClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateNamespace(context.Context, *servicedirectorypb.CreateNamespaceRequest, ...gax.CallOption) (*servicedirectorypb.Namespace, error) + ListNamespaces(context.Context, *servicedirectorypb.ListNamespacesRequest, ...gax.CallOption) *NamespaceIterator + GetNamespace(context.Context, *servicedirectorypb.GetNamespaceRequest, ...gax.CallOption) (*servicedirectorypb.Namespace, error) + UpdateNamespace(context.Context, *servicedirectorypb.UpdateNamespaceRequest, ...gax.CallOption) (*servicedirectorypb.Namespace, error) + DeleteNamespace(context.Context, *servicedirectorypb.DeleteNamespaceRequest, ...gax.CallOption) error + CreateService(context.Context, *servicedirectorypb.CreateServiceRequest, ...gax.CallOption) (*servicedirectorypb.Service, error) + ListServices(context.Context, *servicedirectorypb.ListServicesRequest, ...gax.CallOption) *ServiceIterator + GetService(context.Context, *servicedirectorypb.GetServiceRequest, ...gax.CallOption) (*servicedirectorypb.Service, error) + UpdateService(context.Context, *servicedirectorypb.UpdateServiceRequest, ...gax.CallOption) (*servicedirectorypb.Service, error) + DeleteService(context.Context, *servicedirectorypb.DeleteServiceRequest, ...gax.CallOption) error + CreateEndpoint(context.Context, *servicedirectorypb.CreateEndpointRequest, ...gax.CallOption) (*servicedirectorypb.Endpoint, error) + ListEndpoints(context.Context, *servicedirectorypb.ListEndpointsRequest, ...gax.CallOption) *EndpointIterator + GetEndpoint(context.Context, *servicedirectorypb.GetEndpointRequest, ...gax.CallOption) (*servicedirectorypb.Endpoint, error) + UpdateEndpoint(context.Context, *servicedirectorypb.UpdateEndpointRequest, ...gax.CallOption) (*servicedirectorypb.Endpoint, error) + DeleteEndpoint(context.Context, *servicedirectorypb.DeleteEndpointRequest, ...gax.CallOption) error + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) +} + // RegistrationClient is a client for interacting with Service Directory API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service Directory API for registering services. It defines the following +// resource model: +// +// The API has a collection of +// Namespace +// resources, named projects/*/locations/*/namespaces/*. +// +// Each Namespace has a collection of +// Service resources, named +// projects/*/locations/*/namespaces/*/services/*. +// +// Each Service has a collection of +// Endpoint +// resources, named +// projects/*/locations/*/namespaces/*/services/*/endpoints/*. type RegistrationClient struct { + // The internal transport-dependent client. + internalClient internalRegistrationClient + + // The call options for this service. + CallOptions *RegistrationCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *RegistrationClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *RegistrationClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *RegistrationClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateNamespace creates a namespace, and returns the new Namespace. +func (c *RegistrationClient) CreateNamespace(ctx context.Context, req *servicedirectorypb.CreateNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { + return c.internalClient.CreateNamespace(ctx, req, opts...) +} + +// ListNamespaces lists all namespaces. +func (c *RegistrationClient) ListNamespaces(ctx context.Context, req *servicedirectorypb.ListNamespacesRequest, opts ...gax.CallOption) *NamespaceIterator { + return c.internalClient.ListNamespaces(ctx, req, opts...) +} + +// GetNamespace gets a namespace. +func (c *RegistrationClient) GetNamespace(ctx context.Context, req *servicedirectorypb.GetNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { + return c.internalClient.GetNamespace(ctx, req, opts...) +} + +// UpdateNamespace updates a namespace. +func (c *RegistrationClient) UpdateNamespace(ctx context.Context, req *servicedirectorypb.UpdateNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { + return c.internalClient.UpdateNamespace(ctx, req, opts...) +} + +// DeleteNamespace deletes a namespace. This also deletes all services and endpoints in +// the namespace. +func (c *RegistrationClient) DeleteNamespace(ctx context.Context, req *servicedirectorypb.DeleteNamespaceRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteNamespace(ctx, req, opts...) +} + +// CreateService creates a service, and returns the new Service. +func (c *RegistrationClient) CreateService(ctx context.Context, req *servicedirectorypb.CreateServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { + return c.internalClient.CreateService(ctx, req, opts...) +} + +// ListServices lists all services belonging to a namespace. +func (c *RegistrationClient) ListServices(ctx context.Context, req *servicedirectorypb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { + return c.internalClient.ListServices(ctx, req, opts...) +} + +// GetService gets a service. +func (c *RegistrationClient) GetService(ctx context.Context, req *servicedirectorypb.GetServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { + return c.internalClient.GetService(ctx, req, opts...) +} + +// UpdateService updates a service. +func (c *RegistrationClient) UpdateService(ctx context.Context, req *servicedirectorypb.UpdateServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { + return c.internalClient.UpdateService(ctx, req, opts...) +} + +// DeleteService deletes a service. This also deletes all endpoints associated with +// the service. +func (c *RegistrationClient) DeleteService(ctx context.Context, req *servicedirectorypb.DeleteServiceRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteService(ctx, req, opts...) +} + +// CreateEndpoint creates a endpoint, and returns the new Endpoint. +func (c *RegistrationClient) CreateEndpoint(ctx context.Context, req *servicedirectorypb.CreateEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { + return c.internalClient.CreateEndpoint(ctx, req, opts...) +} + +// ListEndpoints lists all endpoints. +func (c *RegistrationClient) ListEndpoints(ctx context.Context, req *servicedirectorypb.ListEndpointsRequest, opts ...gax.CallOption) *EndpointIterator { + return c.internalClient.ListEndpoints(ctx, req, opts...) +} + +// GetEndpoint gets a endpoint. +func (c *RegistrationClient) GetEndpoint(ctx context.Context, req *servicedirectorypb.GetEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { + return c.internalClient.GetEndpoint(ctx, req, opts...) +} + +// UpdateEndpoint updates a endpoint. +func (c *RegistrationClient) UpdateEndpoint(ctx context.Context, req *servicedirectorypb.UpdateEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { + return c.internalClient.UpdateEndpoint(ctx, req, opts...) +} + +// DeleteEndpoint deletes a endpoint. +func (c *RegistrationClient) DeleteEndpoint(ctx context.Context, req *servicedirectorypb.DeleteEndpointRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteEndpoint(ctx, req, opts...) +} + +// GetIamPolicy gets the IAM Policy for a resource (namespace or service only). +func (c *RegistrationClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// SetIamPolicy sets the IAM Policy for a resource (namespace or service only). +func (c *RegistrationClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions tests IAM permissions for a resource (namespace or service only). +func (c *RegistrationClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// registrationGRPCClient is a client for interacting with Service Directory API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type registrationGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing RegistrationClient + CallOptions **RegistrationCallOptions + // The gRPC API client. registrationClient servicedirectorypb.RegistrationServiceClient - // The call options for this service. - CallOptions *RegistrationCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewRegistrationClient creates a new registration service client. +// NewRegistrationClient creates a new registration service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service Directory API for registering services. It defines the following // resource model: @@ -331,8 +497,7 @@ type RegistrationClient struct { // resources, named // projects/*/locations/*/namespaces/*/services/*/endpoints/*. func NewRegistrationClient(ctx context.Context, opts ...option.ClientOption) (*RegistrationClient, error) { - clientOpts := defaultRegistrationClientOptions() - + clientOpts := defaultRegistrationGRPCClientOptions() if newRegistrationClientHook != nil { hookOpts, err := newRegistrationClientHook(ctx, clientHookParams{}) if err != nil { @@ -350,42 +515,44 @@ func NewRegistrationClient(ctx context.Context, opts ...option.ClientOption) (*R if err != nil { return nil, err } - c := &RegistrationClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultRegistrationCallOptions(), + client := RegistrationClient{CallOptions: defaultRegistrationCallOptions()} + c := ®istrationGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, registrationClient: servicedirectorypb.NewRegistrationServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *RegistrationClient) Connection() *grpc.ClientConn { +func (c *registrationGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *RegistrationClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *RegistrationClient) setGoogleClientInfo(keyval ...string) { +func (c *registrationGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateNamespace creates a namespace, and returns the new Namespace. -func (c *RegistrationClient) CreateNamespace(ctx context.Context, req *servicedirectorypb.CreateNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *registrationGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *registrationGRPCClient) CreateNamespace(ctx context.Context, req *servicedirectorypb.CreateNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -393,7 +560,7 @@ func (c *RegistrationClient) CreateNamespace(ctx context.Context, req *servicedi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateNamespace[0:len(c.CallOptions.CreateNamespace):len(c.CallOptions.CreateNamespace)], opts...) + opts = append((*c.CallOptions).CreateNamespace[0:len((*c.CallOptions).CreateNamespace):len((*c.CallOptions).CreateNamespace)], opts...) var resp *servicedirectorypb.Namespace err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -406,11 +573,10 @@ func (c *RegistrationClient) CreateNamespace(ctx context.Context, req *servicedi return resp, nil } -// ListNamespaces lists all namespaces. -func (c *RegistrationClient) ListNamespaces(ctx context.Context, req *servicedirectorypb.ListNamespacesRequest, opts ...gax.CallOption) *NamespaceIterator { +func (c *registrationGRPCClient) ListNamespaces(ctx context.Context, req *servicedirectorypb.ListNamespacesRequest, opts ...gax.CallOption) *NamespaceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListNamespaces[0:len(c.CallOptions.ListNamespaces):len(c.CallOptions.ListNamespaces)], opts...) + opts = append((*c.CallOptions).ListNamespaces[0:len((*c.CallOptions).ListNamespaces):len((*c.CallOptions).ListNamespaces)], opts...) it := &NamespaceIterator{} req = proto.Clone(req).(*servicedirectorypb.ListNamespacesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*servicedirectorypb.Namespace, string, error) { @@ -447,8 +613,7 @@ func (c *RegistrationClient) ListNamespaces(ctx context.Context, req *servicedir return it } -// GetNamespace gets a namespace. -func (c *RegistrationClient) GetNamespace(ctx context.Context, req *servicedirectorypb.GetNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { +func (c *registrationGRPCClient) GetNamespace(ctx context.Context, req *servicedirectorypb.GetNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -456,7 +621,7 @@ func (c *RegistrationClient) GetNamespace(ctx context.Context, req *servicedirec } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetNamespace[0:len(c.CallOptions.GetNamespace):len(c.CallOptions.GetNamespace)], opts...) + opts = append((*c.CallOptions).GetNamespace[0:len((*c.CallOptions).GetNamespace):len((*c.CallOptions).GetNamespace)], opts...) var resp *servicedirectorypb.Namespace err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -469,8 +634,7 @@ func (c *RegistrationClient) GetNamespace(ctx context.Context, req *servicedirec return resp, nil } -// UpdateNamespace updates a namespace. -func (c *RegistrationClient) UpdateNamespace(ctx context.Context, req *servicedirectorypb.UpdateNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { +func (c *registrationGRPCClient) UpdateNamespace(ctx context.Context, req *servicedirectorypb.UpdateNamespaceRequest, opts ...gax.CallOption) (*servicedirectorypb.Namespace, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -478,7 +642,7 @@ func (c *RegistrationClient) UpdateNamespace(ctx context.Context, req *servicedi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "namespace.name", url.QueryEscape(req.GetNamespace().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateNamespace[0:len(c.CallOptions.UpdateNamespace):len(c.CallOptions.UpdateNamespace)], opts...) + opts = append((*c.CallOptions).UpdateNamespace[0:len((*c.CallOptions).UpdateNamespace):len((*c.CallOptions).UpdateNamespace)], opts...) var resp *servicedirectorypb.Namespace err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -491,9 +655,7 @@ func (c *RegistrationClient) UpdateNamespace(ctx context.Context, req *servicedi return resp, nil } -// DeleteNamespace deletes a namespace. This also deletes all services and endpoints in -// the namespace. -func (c *RegistrationClient) DeleteNamespace(ctx context.Context, req *servicedirectorypb.DeleteNamespaceRequest, opts ...gax.CallOption) error { +func (c *registrationGRPCClient) DeleteNamespace(ctx context.Context, req *servicedirectorypb.DeleteNamespaceRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -501,7 +663,7 @@ func (c *RegistrationClient) DeleteNamespace(ctx context.Context, req *servicedi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteNamespace[0:len(c.CallOptions.DeleteNamespace):len(c.CallOptions.DeleteNamespace)], opts...) + opts = append((*c.CallOptions).DeleteNamespace[0:len((*c.CallOptions).DeleteNamespace):len((*c.CallOptions).DeleteNamespace)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.registrationClient.DeleteNamespace(ctx, req, settings.GRPC...) @@ -510,8 +672,7 @@ func (c *RegistrationClient) DeleteNamespace(ctx context.Context, req *servicedi return err } -// CreateService creates a service, and returns the new Service. -func (c *RegistrationClient) CreateService(ctx context.Context, req *servicedirectorypb.CreateServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { +func (c *registrationGRPCClient) CreateService(ctx context.Context, req *servicedirectorypb.CreateServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -519,7 +680,7 @@ func (c *RegistrationClient) CreateService(ctx context.Context, req *servicedire } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateService[0:len(c.CallOptions.CreateService):len(c.CallOptions.CreateService)], opts...) + opts = append((*c.CallOptions).CreateService[0:len((*c.CallOptions).CreateService):len((*c.CallOptions).CreateService)], opts...) var resp *servicedirectorypb.Service err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -532,11 +693,10 @@ func (c *RegistrationClient) CreateService(ctx context.Context, req *servicedire return resp, nil } -// ListServices lists all services belonging to a namespace. -func (c *RegistrationClient) ListServices(ctx context.Context, req *servicedirectorypb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { +func (c *registrationGRPCClient) ListServices(ctx context.Context, req *servicedirectorypb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListServices[0:len(c.CallOptions.ListServices):len(c.CallOptions.ListServices)], opts...) + opts = append((*c.CallOptions).ListServices[0:len((*c.CallOptions).ListServices):len((*c.CallOptions).ListServices)], opts...) it := &ServiceIterator{} req = proto.Clone(req).(*servicedirectorypb.ListServicesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*servicedirectorypb.Service, string, error) { @@ -573,8 +733,7 @@ func (c *RegistrationClient) ListServices(ctx context.Context, req *servicedirec return it } -// GetService gets a service. -func (c *RegistrationClient) GetService(ctx context.Context, req *servicedirectorypb.GetServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { +func (c *registrationGRPCClient) GetService(ctx context.Context, req *servicedirectorypb.GetServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -582,7 +741,7 @@ func (c *RegistrationClient) GetService(ctx context.Context, req *servicedirecto } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetService[0:len(c.CallOptions.GetService):len(c.CallOptions.GetService)], opts...) + opts = append((*c.CallOptions).GetService[0:len((*c.CallOptions).GetService):len((*c.CallOptions).GetService)], opts...) var resp *servicedirectorypb.Service err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -595,8 +754,7 @@ func (c *RegistrationClient) GetService(ctx context.Context, req *servicedirecto return resp, nil } -// UpdateService updates a service. -func (c *RegistrationClient) UpdateService(ctx context.Context, req *servicedirectorypb.UpdateServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { +func (c *registrationGRPCClient) UpdateService(ctx context.Context, req *servicedirectorypb.UpdateServiceRequest, opts ...gax.CallOption) (*servicedirectorypb.Service, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -604,7 +762,7 @@ func (c *RegistrationClient) UpdateService(ctx context.Context, req *servicedire } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service.name", url.QueryEscape(req.GetService().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateService[0:len(c.CallOptions.UpdateService):len(c.CallOptions.UpdateService)], opts...) + opts = append((*c.CallOptions).UpdateService[0:len((*c.CallOptions).UpdateService):len((*c.CallOptions).UpdateService)], opts...) var resp *servicedirectorypb.Service err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -617,9 +775,7 @@ func (c *RegistrationClient) UpdateService(ctx context.Context, req *servicedire return resp, nil } -// DeleteService deletes a service. This also deletes all endpoints associated with -// the service. -func (c *RegistrationClient) DeleteService(ctx context.Context, req *servicedirectorypb.DeleteServiceRequest, opts ...gax.CallOption) error { +func (c *registrationGRPCClient) DeleteService(ctx context.Context, req *servicedirectorypb.DeleteServiceRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -627,7 +783,7 @@ func (c *RegistrationClient) DeleteService(ctx context.Context, req *servicedire } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteService[0:len(c.CallOptions.DeleteService):len(c.CallOptions.DeleteService)], opts...) + opts = append((*c.CallOptions).DeleteService[0:len((*c.CallOptions).DeleteService):len((*c.CallOptions).DeleteService)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.registrationClient.DeleteService(ctx, req, settings.GRPC...) @@ -636,8 +792,7 @@ func (c *RegistrationClient) DeleteService(ctx context.Context, req *servicedire return err } -// CreateEndpoint creates a endpoint, and returns the new Endpoint. -func (c *RegistrationClient) CreateEndpoint(ctx context.Context, req *servicedirectorypb.CreateEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { +func (c *registrationGRPCClient) CreateEndpoint(ctx context.Context, req *servicedirectorypb.CreateEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -645,7 +800,7 @@ func (c *RegistrationClient) CreateEndpoint(ctx context.Context, req *servicedir } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateEndpoint[0:len(c.CallOptions.CreateEndpoint):len(c.CallOptions.CreateEndpoint)], opts...) + opts = append((*c.CallOptions).CreateEndpoint[0:len((*c.CallOptions).CreateEndpoint):len((*c.CallOptions).CreateEndpoint)], opts...) var resp *servicedirectorypb.Endpoint err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -658,11 +813,10 @@ func (c *RegistrationClient) CreateEndpoint(ctx context.Context, req *servicedir return resp, nil } -// ListEndpoints lists all endpoints. -func (c *RegistrationClient) ListEndpoints(ctx context.Context, req *servicedirectorypb.ListEndpointsRequest, opts ...gax.CallOption) *EndpointIterator { +func (c *registrationGRPCClient) ListEndpoints(ctx context.Context, req *servicedirectorypb.ListEndpointsRequest, opts ...gax.CallOption) *EndpointIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListEndpoints[0:len(c.CallOptions.ListEndpoints):len(c.CallOptions.ListEndpoints)], opts...) + opts = append((*c.CallOptions).ListEndpoints[0:len((*c.CallOptions).ListEndpoints):len((*c.CallOptions).ListEndpoints)], opts...) it := &EndpointIterator{} req = proto.Clone(req).(*servicedirectorypb.ListEndpointsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*servicedirectorypb.Endpoint, string, error) { @@ -699,8 +853,7 @@ func (c *RegistrationClient) ListEndpoints(ctx context.Context, req *servicedire return it } -// GetEndpoint gets a endpoint. -func (c *RegistrationClient) GetEndpoint(ctx context.Context, req *servicedirectorypb.GetEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { +func (c *registrationGRPCClient) GetEndpoint(ctx context.Context, req *servicedirectorypb.GetEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -708,7 +861,7 @@ func (c *RegistrationClient) GetEndpoint(ctx context.Context, req *servicedirect } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetEndpoint[0:len(c.CallOptions.GetEndpoint):len(c.CallOptions.GetEndpoint)], opts...) + opts = append((*c.CallOptions).GetEndpoint[0:len((*c.CallOptions).GetEndpoint):len((*c.CallOptions).GetEndpoint)], opts...) var resp *servicedirectorypb.Endpoint err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -721,8 +874,7 @@ func (c *RegistrationClient) GetEndpoint(ctx context.Context, req *servicedirect return resp, nil } -// UpdateEndpoint updates a endpoint. -func (c *RegistrationClient) UpdateEndpoint(ctx context.Context, req *servicedirectorypb.UpdateEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { +func (c *registrationGRPCClient) UpdateEndpoint(ctx context.Context, req *servicedirectorypb.UpdateEndpointRequest, opts ...gax.CallOption) (*servicedirectorypb.Endpoint, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -730,7 +882,7 @@ func (c *RegistrationClient) UpdateEndpoint(ctx context.Context, req *servicedir } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "endpoint.name", url.QueryEscape(req.GetEndpoint().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateEndpoint[0:len(c.CallOptions.UpdateEndpoint):len(c.CallOptions.UpdateEndpoint)], opts...) + opts = append((*c.CallOptions).UpdateEndpoint[0:len((*c.CallOptions).UpdateEndpoint):len((*c.CallOptions).UpdateEndpoint)], opts...) var resp *servicedirectorypb.Endpoint err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -743,8 +895,7 @@ func (c *RegistrationClient) UpdateEndpoint(ctx context.Context, req *servicedir return resp, nil } -// DeleteEndpoint deletes a endpoint. -func (c *RegistrationClient) DeleteEndpoint(ctx context.Context, req *servicedirectorypb.DeleteEndpointRequest, opts ...gax.CallOption) error { +func (c *registrationGRPCClient) DeleteEndpoint(ctx context.Context, req *servicedirectorypb.DeleteEndpointRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -752,7 +903,7 @@ func (c *RegistrationClient) DeleteEndpoint(ctx context.Context, req *servicedir } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteEndpoint[0:len(c.CallOptions.DeleteEndpoint):len(c.CallOptions.DeleteEndpoint)], opts...) + opts = append((*c.CallOptions).DeleteEndpoint[0:len((*c.CallOptions).DeleteEndpoint):len((*c.CallOptions).DeleteEndpoint)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.registrationClient.DeleteEndpoint(ctx, req, settings.GRPC...) @@ -761,8 +912,7 @@ func (c *RegistrationClient) DeleteEndpoint(ctx context.Context, req *servicedir return err } -// GetIamPolicy gets the IAM Policy for a resource (namespace or service only). -func (c *RegistrationClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *registrationGRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -770,7 +920,7 @@ func (c *RegistrationClient) GetIamPolicy(ctx context.Context, req *iampb.GetIam } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -783,8 +933,7 @@ func (c *RegistrationClient) GetIamPolicy(ctx context.Context, req *iampb.GetIam return resp, nil } -// SetIamPolicy sets the IAM Policy for a resource (namespace or service only). -func (c *RegistrationClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *registrationGRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -792,7 +941,7 @@ func (c *RegistrationClient) SetIamPolicy(ctx context.Context, req *iampb.SetIam } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -805,8 +954,7 @@ func (c *RegistrationClient) SetIamPolicy(ctx context.Context, req *iampb.SetIam return resp, nil } -// TestIamPermissions tests IAM permissions for a resource (namespace or service only). -func (c *RegistrationClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *registrationGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 15000*time.Millisecond) defer cancel() @@ -814,7 +962,7 @@ func (c *RegistrationClient) TestIamPermissions(ctx context.Context, req *iampb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/servicedirectory/apiv1beta1/registration_client_example_test.go b/servicedirectory/apiv1beta1/registration_client_example_test.go index cf57a7a30fa7..87bb75a2fd33 100644 --- a/servicedirectory/apiv1beta1/registration_client_example_test.go +++ b/servicedirectory/apiv1beta1/registration_client_example_test.go @@ -31,18 +31,19 @@ func ExampleNewRegistrationClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleRegistrationClient_CreateNamespace() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.CreateNamespaceRequest{ // TODO: Fill request struct fields. @@ -56,14 +57,12 @@ func ExampleRegistrationClient_CreateNamespace() { } func ExampleRegistrationClient_ListNamespaces() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.ListNamespacesRequest{ // TODO: Fill request struct fields. @@ -83,13 +82,12 @@ func ExampleRegistrationClient_ListNamespaces() { } func ExampleRegistrationClient_GetNamespace() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.GetNamespaceRequest{ // TODO: Fill request struct fields. @@ -103,13 +101,12 @@ func ExampleRegistrationClient_GetNamespace() { } func ExampleRegistrationClient_UpdateNamespace() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.UpdateNamespaceRequest{ // TODO: Fill request struct fields. @@ -128,6 +125,7 @@ func ExampleRegistrationClient_DeleteNamespace() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.DeleteNamespaceRequest{ // TODO: Fill request struct fields. @@ -139,13 +137,12 @@ func ExampleRegistrationClient_DeleteNamespace() { } func ExampleRegistrationClient_CreateService() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.CreateServiceRequest{ // TODO: Fill request struct fields. @@ -159,14 +156,12 @@ func ExampleRegistrationClient_CreateService() { } func ExampleRegistrationClient_ListServices() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.ListServicesRequest{ // TODO: Fill request struct fields. @@ -186,13 +181,12 @@ func ExampleRegistrationClient_ListServices() { } func ExampleRegistrationClient_GetService() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.GetServiceRequest{ // TODO: Fill request struct fields. @@ -206,13 +200,12 @@ func ExampleRegistrationClient_GetService() { } func ExampleRegistrationClient_UpdateService() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.UpdateServiceRequest{ // TODO: Fill request struct fields. @@ -231,6 +224,7 @@ func ExampleRegistrationClient_DeleteService() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.DeleteServiceRequest{ // TODO: Fill request struct fields. @@ -242,13 +236,12 @@ func ExampleRegistrationClient_DeleteService() { } func ExampleRegistrationClient_CreateEndpoint() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.CreateEndpointRequest{ // TODO: Fill request struct fields. @@ -262,14 +255,12 @@ func ExampleRegistrationClient_CreateEndpoint() { } func ExampleRegistrationClient_ListEndpoints() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.ListEndpointsRequest{ // TODO: Fill request struct fields. @@ -289,13 +280,12 @@ func ExampleRegistrationClient_ListEndpoints() { } func ExampleRegistrationClient_GetEndpoint() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.GetEndpointRequest{ // TODO: Fill request struct fields. @@ -309,13 +299,12 @@ func ExampleRegistrationClient_GetEndpoint() { } func ExampleRegistrationClient_UpdateEndpoint() { - // import servicedirectorypb "google.golang.org/genproto/googleapis/cloud/servicedirectory/v1beta1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.UpdateEndpointRequest{ // TODO: Fill request struct fields. @@ -334,6 +323,7 @@ func ExampleRegistrationClient_DeleteEndpoint() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicedirectorypb.DeleteEndpointRequest{ // TODO: Fill request struct fields. @@ -345,13 +335,12 @@ func ExampleRegistrationClient_DeleteEndpoint() { } func ExampleRegistrationClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -365,13 +354,12 @@ func ExampleRegistrationClient_GetIamPolicy() { } func ExampleRegistrationClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -385,13 +373,12 @@ func ExampleRegistrationClient_SetIamPolicy() { } func ExampleRegistrationClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := servicedirectory.NewRegistrationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/servicemanagement/apiv1/doc.go b/servicemanagement/apiv1/doc.go index a9f4b2336bd6..893d6c3d730b 100644 --- a/servicemanagement/apiv1/doc.go +++ b/servicemanagement/apiv1/doc.go @@ -30,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package servicemanagement // import "cloud.google.com/go/servicemanagement/apiv1" import ( @@ -50,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/servicemanagement/apiv1/service_manager_client.go b/servicemanagement/apiv1/service_manager_client.go index f0a3fd6a34b6..a466e0f4c461 100644 --- a/servicemanagement/apiv1/service_manager_client.go +++ b/servicemanagement/apiv1/service_manager_client.go @@ -59,7 +59,7 @@ type ServiceManagerCallOptions struct { DisableService []gax.CallOption } -func defaultServiceManagerClientOptions() []option.ClientOption { +func defaultServiceManagerGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("servicemanagement.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("servicemanagement.mtls.googleapis.com:443"), @@ -91,37 +91,301 @@ func defaultServiceManagerCallOptions() *ServiceManagerCallOptions { } } +// internalServiceManagerClient is an interface that defines the methods availaible from Service Management API. +type internalServiceManagerClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListServices(context.Context, *servicemanagementpb.ListServicesRequest, ...gax.CallOption) *ManagedServiceIterator + GetService(context.Context, *servicemanagementpb.GetServiceRequest, ...gax.CallOption) (*servicemanagementpb.ManagedService, error) + CreateService(context.Context, *servicemanagementpb.CreateServiceRequest, ...gax.CallOption) (*CreateServiceOperation, error) + CreateServiceOperation(name string) *CreateServiceOperation + DeleteService(context.Context, *servicemanagementpb.DeleteServiceRequest, ...gax.CallOption) (*DeleteServiceOperation, error) + DeleteServiceOperation(name string) *DeleteServiceOperation + UndeleteService(context.Context, *servicemanagementpb.UndeleteServiceRequest, ...gax.CallOption) (*UndeleteServiceOperation, error) + UndeleteServiceOperation(name string) *UndeleteServiceOperation + ListServiceConfigs(context.Context, *servicemanagementpb.ListServiceConfigsRequest, ...gax.CallOption) *ServiceIterator + GetServiceConfig(context.Context, *servicemanagementpb.GetServiceConfigRequest, ...gax.CallOption) (*serviceconfigpb.Service, error) + CreateServiceConfig(context.Context, *servicemanagementpb.CreateServiceConfigRequest, ...gax.CallOption) (*serviceconfigpb.Service, error) + SubmitConfigSource(context.Context, *servicemanagementpb.SubmitConfigSourceRequest, ...gax.CallOption) (*SubmitConfigSourceOperation, error) + SubmitConfigSourceOperation(name string) *SubmitConfigSourceOperation + ListServiceRollouts(context.Context, *servicemanagementpb.ListServiceRolloutsRequest, ...gax.CallOption) *RolloutIterator + GetServiceRollout(context.Context, *servicemanagementpb.GetServiceRolloutRequest, ...gax.CallOption) (*servicemanagementpb.Rollout, error) + CreateServiceRollout(context.Context, *servicemanagementpb.CreateServiceRolloutRequest, ...gax.CallOption) (*CreateServiceRolloutOperation, error) + CreateServiceRolloutOperation(name string) *CreateServiceRolloutOperation + GenerateConfigReport(context.Context, *servicemanagementpb.GenerateConfigReportRequest, ...gax.CallOption) (*servicemanagementpb.GenerateConfigReportResponse, error) + EnableService(context.Context, *servicemanagementpb.EnableServiceRequest, ...gax.CallOption) (*EnableServiceOperation, error) + EnableServiceOperation(name string) *EnableServiceOperation + DisableService(context.Context, *servicemanagementpb.DisableServiceRequest, ...gax.CallOption) (*DisableServiceOperation, error) + DisableServiceOperation(name string) *DisableServiceOperation +} + // ServiceManagerClient is a client for interacting with Service Management API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Google Service Management API (at https://cloud.google.com/service-management/overview) type ServiceManagerClient struct { + // The internal transport-dependent client. + internalClient internalServiceManagerClient + + // The call options for this service. + CallOptions *ServiceManagerCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ServiceManagerClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ServiceManagerClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ServiceManagerClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListServices lists managed services. +// +// Returns all public services. For authenticated users, also returns all +// services the calling user has “servicemanagement.services.get” permission +// for. +// +// BETA: If the caller specifies the consumer_id, it returns only the +// services enabled on the consumer. The consumer_id must have the format +// of “project:{PROJECT-ID}”. +func (c *ServiceManagerClient) ListServices(ctx context.Context, req *servicemanagementpb.ListServicesRequest, opts ...gax.CallOption) *ManagedServiceIterator { + return c.internalClient.ListServices(ctx, req, opts...) +} + +// GetService gets a managed service. Authentication is required unless the service is +// public. +func (c *ServiceManagerClient) GetService(ctx context.Context, req *servicemanagementpb.GetServiceRequest, opts ...gax.CallOption) (*servicemanagementpb.ManagedService, error) { + return c.internalClient.GetService(ctx, req, opts...) +} + +// CreateService creates a new managed service. +// Please note one producer project can own no more than 20 services. +// +// Operation +func (c *ServiceManagerClient) CreateService(ctx context.Context, req *servicemanagementpb.CreateServiceRequest, opts ...gax.CallOption) (*CreateServiceOperation, error) { + return c.internalClient.CreateService(ctx, req, opts...) +} + +// CreateServiceOperation returns a new CreateServiceOperation from a given name. +// The name must be that of a previously created CreateServiceOperation, possibly from a different process. +func (c *ServiceManagerClient) CreateServiceOperation(name string) *CreateServiceOperation { + return c.internalClient.CreateServiceOperation(name) +} + +// DeleteService deletes a managed service. This method will change the service to the +// Soft-Delete state for 30 days. Within this period, service producers may +// call UndeleteService to restore the service. +// After 30 days, the service will be permanently deleted. +// +// Operation +func (c *ServiceManagerClient) DeleteService(ctx context.Context, req *servicemanagementpb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { + return c.internalClient.DeleteService(ctx, req, opts...) +} + +// DeleteServiceOperation returns a new DeleteServiceOperation from a given name. +// The name must be that of a previously created DeleteServiceOperation, possibly from a different process. +func (c *ServiceManagerClient) DeleteServiceOperation(name string) *DeleteServiceOperation { + return c.internalClient.DeleteServiceOperation(name) +} + +// UndeleteService revives a previously deleted managed service. The method restores the +// service using the configuration at the time the service was deleted. +// The target service must exist and must have been deleted within the +// last 30 days. +// +// Operation +func (c *ServiceManagerClient) UndeleteService(ctx context.Context, req *servicemanagementpb.UndeleteServiceRequest, opts ...gax.CallOption) (*UndeleteServiceOperation, error) { + return c.internalClient.UndeleteService(ctx, req, opts...) +} + +// UndeleteServiceOperation returns a new UndeleteServiceOperation from a given name. +// The name must be that of a previously created UndeleteServiceOperation, possibly from a different process. +func (c *ServiceManagerClient) UndeleteServiceOperation(name string) *UndeleteServiceOperation { + return c.internalClient.UndeleteServiceOperation(name) +} + +// ListServiceConfigs lists the history of the service configuration for a managed service, +// from the newest to the oldest. +func (c *ServiceManagerClient) ListServiceConfigs(ctx context.Context, req *servicemanagementpb.ListServiceConfigsRequest, opts ...gax.CallOption) *ServiceIterator { + return c.internalClient.ListServiceConfigs(ctx, req, opts...) +} + +// GetServiceConfig gets a service configuration (version) for a managed service. +func (c *ServiceManagerClient) GetServiceConfig(ctx context.Context, req *servicemanagementpb.GetServiceConfigRequest, opts ...gax.CallOption) (*serviceconfigpb.Service, error) { + return c.internalClient.GetServiceConfig(ctx, req, opts...) +} + +// CreateServiceConfig creates a new service configuration (version) for a managed service. +// This method only stores the service configuration. To roll out the service +// configuration to backend systems please call +// CreateServiceRollout. +// +// Only the 100 most recent service configurations and ones referenced by +// existing rollouts are kept for each service. The rest will be deleted +// eventually. +func (c *ServiceManagerClient) CreateServiceConfig(ctx context.Context, req *servicemanagementpb.CreateServiceConfigRequest, opts ...gax.CallOption) (*serviceconfigpb.Service, error) { + return c.internalClient.CreateServiceConfig(ctx, req, opts...) +} + +// SubmitConfigSource creates a new service configuration (version) for a managed service based +// on +// user-supplied configuration source files (for example: OpenAPI +// Specification). This method stores the source configurations as well as the +// generated service configuration. To rollout the service configuration to +// other services, +// please call CreateServiceRollout. +// +// Only the 100 most recent configuration sources and ones referenced by +// existing service configurtions are kept for each service. The rest will be +// deleted eventually. +// +// Operation +func (c *ServiceManagerClient) SubmitConfigSource(ctx context.Context, req *servicemanagementpb.SubmitConfigSourceRequest, opts ...gax.CallOption) (*SubmitConfigSourceOperation, error) { + return c.internalClient.SubmitConfigSource(ctx, req, opts...) +} + +// SubmitConfigSourceOperation returns a new SubmitConfigSourceOperation from a given name. +// The name must be that of a previously created SubmitConfigSourceOperation, possibly from a different process. +func (c *ServiceManagerClient) SubmitConfigSourceOperation(name string) *SubmitConfigSourceOperation { + return c.internalClient.SubmitConfigSourceOperation(name) +} + +// ListServiceRollouts lists the history of the service configuration rollouts for a managed +// service, from the newest to the oldest. +func (c *ServiceManagerClient) ListServiceRollouts(ctx context.Context, req *servicemanagementpb.ListServiceRolloutsRequest, opts ...gax.CallOption) *RolloutIterator { + return c.internalClient.ListServiceRollouts(ctx, req, opts...) +} + +// GetServiceRollout gets a service configuration rollout. +func (c *ServiceManagerClient) GetServiceRollout(ctx context.Context, req *servicemanagementpb.GetServiceRolloutRequest, opts ...gax.CallOption) (*servicemanagementpb.Rollout, error) { + return c.internalClient.GetServiceRollout(ctx, req, opts...) +} + +// CreateServiceRollout creates a new service configuration rollout. Based on rollout, the +// Google Service Management will roll out the service configurations to +// different backend services. For example, the logging configuration will be +// pushed to Google Cloud Logging. +// +// Please note that any previous pending and running Rollouts and associated +// Operations will be automatically cancelled so that the latest Rollout will +// not be blocked by previous Rollouts. +// +// Only the 100 most recent (in any state) and the last 10 successful (if not +// already part of the set of 100 most recent) rollouts are kept for each +// service. The rest will be deleted eventually. +// +// Operation +func (c *ServiceManagerClient) CreateServiceRollout(ctx context.Context, req *servicemanagementpb.CreateServiceRolloutRequest, opts ...gax.CallOption) (*CreateServiceRolloutOperation, error) { + return c.internalClient.CreateServiceRollout(ctx, req, opts...) +} + +// CreateServiceRolloutOperation returns a new CreateServiceRolloutOperation from a given name. +// The name must be that of a previously created CreateServiceRolloutOperation, possibly from a different process. +func (c *ServiceManagerClient) CreateServiceRolloutOperation(name string) *CreateServiceRolloutOperation { + return c.internalClient.CreateServiceRolloutOperation(name) +} + +// GenerateConfigReport generates and returns a report (errors, warnings and changes from +// existing configurations) associated with +// GenerateConfigReportRequest.new_value +// +// If GenerateConfigReportRequest.old_value is specified, +// GenerateConfigReportRequest will contain a single ChangeReport based on the +// comparison between GenerateConfigReportRequest.new_value and +// GenerateConfigReportRequest.old_value. +// If GenerateConfigReportRequest.old_value is not specified, this method +// will compare GenerateConfigReportRequest.new_value with the last pushed +// service configuration. +func (c *ServiceManagerClient) GenerateConfigReport(ctx context.Context, req *servicemanagementpb.GenerateConfigReportRequest, opts ...gax.CallOption) (*servicemanagementpb.GenerateConfigReportResponse, error) { + return c.internalClient.GenerateConfigReport(ctx, req, opts...) +} + +// EnableService enables a service for a project, so it can be used +// for the project. See +// Cloud Auth Guide (at https://cloud.google.com/docs/authentication) for +// more information. +// +// Operation +// +// Deprecated: EnableService may be removed in a future version. +func (c *ServiceManagerClient) EnableService(ctx context.Context, req *servicemanagementpb.EnableServiceRequest, opts ...gax.CallOption) (*EnableServiceOperation, error) { + return c.internalClient.EnableService(ctx, req, opts...) +} + +// EnableServiceOperation returns a new EnableServiceOperation from a given name. +// The name must be that of a previously created EnableServiceOperation, possibly from a different process. +func (c *ServiceManagerClient) EnableServiceOperation(name string) *EnableServiceOperation { + return c.internalClient.EnableServiceOperation(name) +} + +// DisableService disables a service for a project, so it can no longer be +// be used for the project. It prevents accidental usage that may cause +// unexpected billing charges or security leaks. +// +// Operation +// +// Deprecated: DisableService may be removed in a future version. +func (c *ServiceManagerClient) DisableService(ctx context.Context, req *servicemanagementpb.DisableServiceRequest, opts ...gax.CallOption) (*DisableServiceOperation, error) { + return c.internalClient.DisableService(ctx, req, opts...) +} + +// DisableServiceOperation returns a new DisableServiceOperation from a given name. +// The name must be that of a previously created DisableServiceOperation, possibly from a different process. +func (c *ServiceManagerClient) DisableServiceOperation(name string) *DisableServiceOperation { + return c.internalClient.DisableServiceOperation(name) +} + +// serviceManagerGRPCClient is a client for interacting with Service Management API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type serviceManagerGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ServiceManagerClient + CallOptions **ServiceManagerCallOptions + // The gRPC API client. serviceManagerClient servicemanagementpb.ServiceManagerClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *ServiceManagerCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewServiceManagerClient creates a new service manager client. +// NewServiceManagerClient creates a new service manager client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Google Service Management API (at https://cloud.google.com/service-management/overview) func NewServiceManagerClient(ctx context.Context, opts ...option.ClientOption) (*ServiceManagerClient, error) { - clientOpts := defaultServiceManagerClientOptions() - + clientOpts := defaultServiceManagerGRPCClientOptions() if newServiceManagerClientHook != nil { hookOpts, err := newServiceManagerClientHook(ctx, clientHookParams{}) if err != nil { @@ -139,16 +403,19 @@ func NewServiceManagerClient(ctx context.Context, opts ...option.ClientOption) ( if err != nil { return nil, err } - c := &ServiceManagerClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultServiceManagerCallOptions(), + client := ServiceManagerClient{CallOptions: defaultServiceManagerCallOptions()} + c := &serviceManagerGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, serviceManagerClient: servicemanagementpb.NewServiceManagerClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -158,43 +425,35 @@ func NewServiceManagerClient(ctx context.Context, opts ...option.ClientOption) ( // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ServiceManagerClient) Connection() *grpc.ClientConn { +func (c *serviceManagerGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ServiceManagerClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ServiceManagerClient) setGoogleClientInfo(keyval ...string) { +func (c *serviceManagerGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListServices lists managed services. -// -// Returns all public services. For authenticated users, also returns all -// services the calling user has “servicemanagement.services.get” permission -// for. -// -// BETA: If the caller specifies the consumer_id, it returns only the -// services enabled on the consumer. The consumer_id must have the format -// of “project:{PROJECT-ID}”. -func (c *ServiceManagerClient) ListServices(ctx context.Context, req *servicemanagementpb.ListServicesRequest, opts ...gax.CallOption) *ManagedServiceIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *serviceManagerGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *serviceManagerGRPCClient) ListServices(ctx context.Context, req *servicemanagementpb.ListServicesRequest, opts ...gax.CallOption) *ManagedServiceIterator { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListServices[0:len(c.CallOptions.ListServices):len(c.CallOptions.ListServices)], opts...) + opts = append((*c.CallOptions).ListServices[0:len((*c.CallOptions).ListServices):len((*c.CallOptions).ListServices)], opts...) it := &ManagedServiceIterator{} req = proto.Clone(req).(*servicemanagementpb.ListServicesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*servicemanagementpb.ManagedService, string, error) { @@ -231,9 +490,7 @@ func (c *ServiceManagerClient) ListServices(ctx context.Context, req *serviceman return it } -// GetService gets a managed service. Authentication is required unless the service is -// public. -func (c *ServiceManagerClient) GetService(ctx context.Context, req *servicemanagementpb.GetServiceRequest, opts ...gax.CallOption) (*servicemanagementpb.ManagedService, error) { +func (c *serviceManagerGRPCClient) GetService(ctx context.Context, req *servicemanagementpb.GetServiceRequest, opts ...gax.CallOption) (*servicemanagementpb.ManagedService, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -241,7 +498,7 @@ func (c *ServiceManagerClient) GetService(ctx context.Context, req *servicemanag } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetService[0:len(c.CallOptions.GetService):len(c.CallOptions.GetService)], opts...) + opts = append((*c.CallOptions).GetService[0:len((*c.CallOptions).GetService):len((*c.CallOptions).GetService)], opts...) var resp *servicemanagementpb.ManagedService err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -254,18 +511,14 @@ func (c *ServiceManagerClient) GetService(ctx context.Context, req *servicemanag return resp, nil } -// CreateService creates a new managed service. -// Please note one producer project can own no more than 20 services. -// -// Operation -func (c *ServiceManagerClient) CreateService(ctx context.Context, req *servicemanagementpb.CreateServiceRequest, opts ...gax.CallOption) (*CreateServiceOperation, error) { +func (c *serviceManagerGRPCClient) CreateService(ctx context.Context, req *servicemanagementpb.CreateServiceRequest, opts ...gax.CallOption) (*CreateServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.CreateService[0:len(c.CallOptions.CreateService):len(c.CallOptions.CreateService)], opts...) + opts = append((*c.CallOptions).CreateService[0:len((*c.CallOptions).CreateService):len((*c.CallOptions).CreateService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -276,17 +529,11 @@ func (c *ServiceManagerClient) CreateService(ctx context.Context, req *servicema return nil, err } return &CreateServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteService deletes a managed service. This method will change the service to the -// Soft-Delete state for 30 days. Within this period, service producers may -// call UndeleteService to restore the service. -// After 30 days, the service will be permanently deleted. -// -// Operation -func (c *ServiceManagerClient) DeleteService(ctx context.Context, req *servicemanagementpb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { +func (c *serviceManagerGRPCClient) DeleteService(ctx context.Context, req *servicemanagementpb.DeleteServiceRequest, opts ...gax.CallOption) (*DeleteServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -294,7 +541,7 @@ func (c *ServiceManagerClient) DeleteService(ctx context.Context, req *servicema } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteService[0:len(c.CallOptions.DeleteService):len(c.CallOptions.DeleteService)], opts...) + opts = append((*c.CallOptions).DeleteService[0:len((*c.CallOptions).DeleteService):len((*c.CallOptions).DeleteService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -305,17 +552,11 @@ func (c *ServiceManagerClient) DeleteService(ctx context.Context, req *servicema return nil, err } return &DeleteServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UndeleteService revives a previously deleted managed service. The method restores the -// service using the configuration at the time the service was deleted. -// The target service must exist and must have been deleted within the -// last 30 days. -// -// Operation -func (c *ServiceManagerClient) UndeleteService(ctx context.Context, req *servicemanagementpb.UndeleteServiceRequest, opts ...gax.CallOption) (*UndeleteServiceOperation, error) { +func (c *serviceManagerGRPCClient) UndeleteService(ctx context.Context, req *servicemanagementpb.UndeleteServiceRequest, opts ...gax.CallOption) (*UndeleteServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -323,7 +564,7 @@ func (c *ServiceManagerClient) UndeleteService(ctx context.Context, req *service } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UndeleteService[0:len(c.CallOptions.UndeleteService):len(c.CallOptions.UndeleteService)], opts...) + opts = append((*c.CallOptions).UndeleteService[0:len((*c.CallOptions).UndeleteService):len((*c.CallOptions).UndeleteService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -334,16 +575,14 @@ func (c *ServiceManagerClient) UndeleteService(ctx context.Context, req *service return nil, err } return &UndeleteServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListServiceConfigs lists the history of the service configuration for a managed service, -// from the newest to the oldest. -func (c *ServiceManagerClient) ListServiceConfigs(ctx context.Context, req *servicemanagementpb.ListServiceConfigsRequest, opts ...gax.CallOption) *ServiceIterator { +func (c *serviceManagerGRPCClient) ListServiceConfigs(ctx context.Context, req *servicemanagementpb.ListServiceConfigsRequest, opts ...gax.CallOption) *ServiceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListServiceConfigs[0:len(c.CallOptions.ListServiceConfigs):len(c.CallOptions.ListServiceConfigs)], opts...) + opts = append((*c.CallOptions).ListServiceConfigs[0:len((*c.CallOptions).ListServiceConfigs):len((*c.CallOptions).ListServiceConfigs)], opts...) it := &ServiceIterator{} req = proto.Clone(req).(*servicemanagementpb.ListServiceConfigsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*serviceconfigpb.Service, string, error) { @@ -380,8 +619,7 @@ func (c *ServiceManagerClient) ListServiceConfigs(ctx context.Context, req *serv return it } -// GetServiceConfig gets a service configuration (version) for a managed service. -func (c *ServiceManagerClient) GetServiceConfig(ctx context.Context, req *servicemanagementpb.GetServiceConfigRequest, opts ...gax.CallOption) (*serviceconfigpb.Service, error) { +func (c *serviceManagerGRPCClient) GetServiceConfig(ctx context.Context, req *servicemanagementpb.GetServiceConfigRequest, opts ...gax.CallOption) (*serviceconfigpb.Service, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -389,7 +627,7 @@ func (c *ServiceManagerClient) GetServiceConfig(ctx context.Context, req *servic } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "service_name", url.QueryEscape(req.GetServiceName()), "config_id", url.QueryEscape(req.GetConfigId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetServiceConfig[0:len(c.CallOptions.GetServiceConfig):len(c.CallOptions.GetServiceConfig)], opts...) + opts = append((*c.CallOptions).GetServiceConfig[0:len((*c.CallOptions).GetServiceConfig):len((*c.CallOptions).GetServiceConfig)], opts...) var resp *serviceconfigpb.Service err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -402,15 +640,7 @@ func (c *ServiceManagerClient) GetServiceConfig(ctx context.Context, req *servic return resp, nil } -// CreateServiceConfig creates a new service configuration (version) for a managed service. -// This method only stores the service configuration. To roll out the service -// configuration to backend systems please call -// CreateServiceRollout. -// -// Only the 100 most recent service configurations and ones referenced by -// existing rollouts are kept for each service. The rest will be deleted -// eventually. -func (c *ServiceManagerClient) CreateServiceConfig(ctx context.Context, req *servicemanagementpb.CreateServiceConfigRequest, opts ...gax.CallOption) (*serviceconfigpb.Service, error) { +func (c *serviceManagerGRPCClient) CreateServiceConfig(ctx context.Context, req *servicemanagementpb.CreateServiceConfigRequest, opts ...gax.CallOption) (*serviceconfigpb.Service, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -418,7 +648,7 @@ func (c *ServiceManagerClient) CreateServiceConfig(ctx context.Context, req *ser } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateServiceConfig[0:len(c.CallOptions.CreateServiceConfig):len(c.CallOptions.CreateServiceConfig)], opts...) + opts = append((*c.CallOptions).CreateServiceConfig[0:len((*c.CallOptions).CreateServiceConfig):len((*c.CallOptions).CreateServiceConfig)], opts...) var resp *serviceconfigpb.Service err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -431,20 +661,7 @@ func (c *ServiceManagerClient) CreateServiceConfig(ctx context.Context, req *ser return resp, nil } -// SubmitConfigSource creates a new service configuration (version) for a managed service based -// on -// user-supplied configuration source files (for example: OpenAPI -// Specification). This method stores the source configurations as well as the -// generated service configuration. To rollout the service configuration to -// other services, -// please call CreateServiceRollout. -// -// Only the 100 most recent configuration sources and ones referenced by -// existing service configurtions are kept for each service. The rest will be -// deleted eventually. -// -// Operation -func (c *ServiceManagerClient) SubmitConfigSource(ctx context.Context, req *servicemanagementpb.SubmitConfigSourceRequest, opts ...gax.CallOption) (*SubmitConfigSourceOperation, error) { +func (c *serviceManagerGRPCClient) SubmitConfigSource(ctx context.Context, req *servicemanagementpb.SubmitConfigSourceRequest, opts ...gax.CallOption) (*SubmitConfigSourceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -452,7 +669,7 @@ func (c *ServiceManagerClient) SubmitConfigSource(ctx context.Context, req *serv } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SubmitConfigSource[0:len(c.CallOptions.SubmitConfigSource):len(c.CallOptions.SubmitConfigSource)], opts...) + opts = append((*c.CallOptions).SubmitConfigSource[0:len((*c.CallOptions).SubmitConfigSource):len((*c.CallOptions).SubmitConfigSource)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -463,16 +680,14 @@ func (c *ServiceManagerClient) SubmitConfigSource(ctx context.Context, req *serv return nil, err } return &SubmitConfigSourceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListServiceRollouts lists the history of the service configuration rollouts for a managed -// service, from the newest to the oldest. -func (c *ServiceManagerClient) ListServiceRollouts(ctx context.Context, req *servicemanagementpb.ListServiceRolloutsRequest, opts ...gax.CallOption) *RolloutIterator { +func (c *serviceManagerGRPCClient) ListServiceRollouts(ctx context.Context, req *servicemanagementpb.ListServiceRolloutsRequest, opts ...gax.CallOption) *RolloutIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListServiceRollouts[0:len(c.CallOptions.ListServiceRollouts):len(c.CallOptions.ListServiceRollouts)], opts...) + opts = append((*c.CallOptions).ListServiceRollouts[0:len((*c.CallOptions).ListServiceRollouts):len((*c.CallOptions).ListServiceRollouts)], opts...) it := &RolloutIterator{} req = proto.Clone(req).(*servicemanagementpb.ListServiceRolloutsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*servicemanagementpb.Rollout, string, error) { @@ -509,8 +724,7 @@ func (c *ServiceManagerClient) ListServiceRollouts(ctx context.Context, req *ser return it } -// GetServiceRollout gets a service configuration rollout. -func (c *ServiceManagerClient) GetServiceRollout(ctx context.Context, req *servicemanagementpb.GetServiceRolloutRequest, opts ...gax.CallOption) (*servicemanagementpb.Rollout, error) { +func (c *serviceManagerGRPCClient) GetServiceRollout(ctx context.Context, req *servicemanagementpb.GetServiceRolloutRequest, opts ...gax.CallOption) (*servicemanagementpb.Rollout, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -518,7 +732,7 @@ func (c *ServiceManagerClient) GetServiceRollout(ctx context.Context, req *servi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "service_name", url.QueryEscape(req.GetServiceName()), "rollout_id", url.QueryEscape(req.GetRolloutId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetServiceRollout[0:len(c.CallOptions.GetServiceRollout):len(c.CallOptions.GetServiceRollout)], opts...) + opts = append((*c.CallOptions).GetServiceRollout[0:len((*c.CallOptions).GetServiceRollout):len((*c.CallOptions).GetServiceRollout)], opts...) var resp *servicemanagementpb.Rollout err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -531,21 +745,7 @@ func (c *ServiceManagerClient) GetServiceRollout(ctx context.Context, req *servi return resp, nil } -// CreateServiceRollout creates a new service configuration rollout. Based on rollout, the -// Google Service Management will roll out the service configurations to -// different backend services. For example, the logging configuration will be -// pushed to Google Cloud Logging. -// -// Please note that any previous pending and running Rollouts and associated -// Operations will be automatically cancelled so that the latest Rollout will -// not be blocked by previous Rollouts. -// -// Only the 100 most recent (in any state) and the last 10 successful (if not -// already part of the set of 100 most recent) rollouts are kept for each -// service. The rest will be deleted eventually. -// -// Operation -func (c *ServiceManagerClient) CreateServiceRollout(ctx context.Context, req *servicemanagementpb.CreateServiceRolloutRequest, opts ...gax.CallOption) (*CreateServiceRolloutOperation, error) { +func (c *serviceManagerGRPCClient) CreateServiceRollout(ctx context.Context, req *servicemanagementpb.CreateServiceRolloutRequest, opts ...gax.CallOption) (*CreateServiceRolloutOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -553,7 +753,7 @@ func (c *ServiceManagerClient) CreateServiceRollout(ctx context.Context, req *se } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateServiceRollout[0:len(c.CallOptions.CreateServiceRollout):len(c.CallOptions.CreateServiceRollout)], opts...) + opts = append((*c.CallOptions).CreateServiceRollout[0:len((*c.CallOptions).CreateServiceRollout):len((*c.CallOptions).CreateServiceRollout)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -564,29 +764,18 @@ func (c *ServiceManagerClient) CreateServiceRollout(ctx context.Context, req *se return nil, err } return &CreateServiceRolloutOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GenerateConfigReport generates and returns a report (errors, warnings and changes from -// existing configurations) associated with -// GenerateConfigReportRequest.new_value -// -// If GenerateConfigReportRequest.old_value is specified, -// GenerateConfigReportRequest will contain a single ChangeReport based on the -// comparison between GenerateConfigReportRequest.new_value and -// GenerateConfigReportRequest.old_value. -// If GenerateConfigReportRequest.old_value is not specified, this method -// will compare GenerateConfigReportRequest.new_value with the last pushed -// service configuration. -func (c *ServiceManagerClient) GenerateConfigReport(ctx context.Context, req *servicemanagementpb.GenerateConfigReportRequest, opts ...gax.CallOption) (*servicemanagementpb.GenerateConfigReportResponse, error) { +func (c *serviceManagerGRPCClient) GenerateConfigReport(ctx context.Context, req *servicemanagementpb.GenerateConfigReportRequest, opts ...gax.CallOption) (*servicemanagementpb.GenerateConfigReportResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.GenerateConfigReport[0:len(c.CallOptions.GenerateConfigReport):len(c.CallOptions.GenerateConfigReport)], opts...) + opts = append((*c.CallOptions).GenerateConfigReport[0:len((*c.CallOptions).GenerateConfigReport):len((*c.CallOptions).GenerateConfigReport)], opts...) var resp *servicemanagementpb.GenerateConfigReportResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -599,13 +788,7 @@ func (c *ServiceManagerClient) GenerateConfigReport(ctx context.Context, req *se return resp, nil } -// EnableService enables a service for a project, so it can be used -// for the project. See -// Cloud Auth Guide (at https://cloud.google.com/docs/authentication) for -// more information. -// -// Operation -func (c *ServiceManagerClient) EnableService(ctx context.Context, req *servicemanagementpb.EnableServiceRequest, opts ...gax.CallOption) (*EnableServiceOperation, error) { +func (c *serviceManagerGRPCClient) EnableService(ctx context.Context, req *servicemanagementpb.EnableServiceRequest, opts ...gax.CallOption) (*EnableServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -613,7 +796,7 @@ func (c *ServiceManagerClient) EnableService(ctx context.Context, req *servicema } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.EnableService[0:len(c.CallOptions.EnableService):len(c.CallOptions.EnableService)], opts...) + opts = append((*c.CallOptions).EnableService[0:len((*c.CallOptions).EnableService):len((*c.CallOptions).EnableService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -624,16 +807,11 @@ func (c *ServiceManagerClient) EnableService(ctx context.Context, req *servicema return nil, err } return &EnableServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DisableService disables a service for a project, so it can no longer be -// be used for the project. It prevents accidental usage that may cause -// unexpected billing charges or security leaks. -// -// Operation -func (c *ServiceManagerClient) DisableService(ctx context.Context, req *servicemanagementpb.DisableServiceRequest, opts ...gax.CallOption) (*DisableServiceOperation, error) { +func (c *serviceManagerGRPCClient) DisableService(ctx context.Context, req *servicemanagementpb.DisableServiceRequest, opts ...gax.CallOption) (*DisableServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 10000*time.Millisecond) defer cancel() @@ -641,7 +819,7 @@ func (c *ServiceManagerClient) DisableService(ctx context.Context, req *servicem } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "service_name", url.QueryEscape(req.GetServiceName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DisableService[0:len(c.CallOptions.DisableService):len(c.CallOptions.DisableService)], opts...) + opts = append((*c.CallOptions).DisableService[0:len((*c.CallOptions).DisableService):len((*c.CallOptions).DisableService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -652,7 +830,7 @@ func (c *ServiceManagerClient) DisableService(ctx context.Context, req *servicem return nil, err } return &DisableServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -663,9 +841,9 @@ type CreateServiceOperation struct { // CreateServiceOperation returns a new CreateServiceOperation from a given name. // The name must be that of a previously created CreateServiceOperation, possibly from a different process. -func (c *ServiceManagerClient) CreateServiceOperation(name string) *CreateServiceOperation { +func (c *serviceManagerGRPCClient) CreateServiceOperation(name string) *CreateServiceOperation { return &CreateServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -732,9 +910,9 @@ type CreateServiceRolloutOperation struct { // CreateServiceRolloutOperation returns a new CreateServiceRolloutOperation from a given name. // The name must be that of a previously created CreateServiceRolloutOperation, possibly from a different process. -func (c *ServiceManagerClient) CreateServiceRolloutOperation(name string) *CreateServiceRolloutOperation { +func (c *serviceManagerGRPCClient) CreateServiceRolloutOperation(name string) *CreateServiceRolloutOperation { return &CreateServiceRolloutOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -801,9 +979,9 @@ type DeleteServiceOperation struct { // DeleteServiceOperation returns a new DeleteServiceOperation from a given name. // The name must be that of a previously created DeleteServiceOperation, possibly from a different process. -func (c *ServiceManagerClient) DeleteServiceOperation(name string) *DeleteServiceOperation { +func (c *serviceManagerGRPCClient) DeleteServiceOperation(name string) *DeleteServiceOperation { return &DeleteServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -859,9 +1037,9 @@ type DisableServiceOperation struct { // DisableServiceOperation returns a new DisableServiceOperation from a given name. // The name must be that of a previously created DisableServiceOperation, possibly from a different process. -func (c *ServiceManagerClient) DisableServiceOperation(name string) *DisableServiceOperation { +func (c *serviceManagerGRPCClient) DisableServiceOperation(name string) *DisableServiceOperation { return &DisableServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -928,9 +1106,9 @@ type EnableServiceOperation struct { // EnableServiceOperation returns a new EnableServiceOperation from a given name. // The name must be that of a previously created EnableServiceOperation, possibly from a different process. -func (c *ServiceManagerClient) EnableServiceOperation(name string) *EnableServiceOperation { +func (c *serviceManagerGRPCClient) EnableServiceOperation(name string) *EnableServiceOperation { return &EnableServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -997,9 +1175,9 @@ type SubmitConfigSourceOperation struct { // SubmitConfigSourceOperation returns a new SubmitConfigSourceOperation from a given name. // The name must be that of a previously created SubmitConfigSourceOperation, possibly from a different process. -func (c *ServiceManagerClient) SubmitConfigSourceOperation(name string) *SubmitConfigSourceOperation { +func (c *serviceManagerGRPCClient) SubmitConfigSourceOperation(name string) *SubmitConfigSourceOperation { return &SubmitConfigSourceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1066,9 +1244,9 @@ type UndeleteServiceOperation struct { // UndeleteServiceOperation returns a new UndeleteServiceOperation from a given name. // The name must be that of a previously created UndeleteServiceOperation, possibly from a different process. -func (c *ServiceManagerClient) UndeleteServiceOperation(name string) *UndeleteServiceOperation { +func (c *serviceManagerGRPCClient) UndeleteServiceOperation(name string) *UndeleteServiceOperation { return &UndeleteServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/servicemanagement/apiv1/service_manager_client_example_test.go b/servicemanagement/apiv1/service_manager_client_example_test.go index c85986c67d3e..2229458876b2 100644 --- a/servicemanagement/apiv1/service_manager_client_example_test.go +++ b/servicemanagement/apiv1/service_manager_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewServiceManagerClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleServiceManagerClient_ListServices() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.ListServicesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleServiceManagerClient_ListServices() { } func ExampleServiceManagerClient_GetService() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.GetServiceRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleServiceManagerClient_GetService() { } func ExampleServiceManagerClient_CreateService() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.CreateServiceRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleServiceManagerClient_CreateService() { } func ExampleServiceManagerClient_DeleteService() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.DeleteServiceRequest{ // TODO: Fill request struct fields. @@ -130,13 +127,12 @@ func ExampleServiceManagerClient_DeleteService() { } func ExampleServiceManagerClient_UndeleteService() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.UndeleteServiceRequest{ // TODO: Fill request struct fields. @@ -155,14 +151,12 @@ func ExampleServiceManagerClient_UndeleteService() { } func ExampleServiceManagerClient_ListServiceConfigs() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.ListServiceConfigsRequest{ // TODO: Fill request struct fields. @@ -182,13 +176,12 @@ func ExampleServiceManagerClient_ListServiceConfigs() { } func ExampleServiceManagerClient_GetServiceConfig() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.GetServiceConfigRequest{ // TODO: Fill request struct fields. @@ -202,13 +195,12 @@ func ExampleServiceManagerClient_GetServiceConfig() { } func ExampleServiceManagerClient_CreateServiceConfig() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.CreateServiceConfigRequest{ // TODO: Fill request struct fields. @@ -222,13 +214,12 @@ func ExampleServiceManagerClient_CreateServiceConfig() { } func ExampleServiceManagerClient_SubmitConfigSource() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.SubmitConfigSourceRequest{ // TODO: Fill request struct fields. @@ -247,14 +238,12 @@ func ExampleServiceManagerClient_SubmitConfigSource() { } func ExampleServiceManagerClient_ListServiceRollouts() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.ListServiceRolloutsRequest{ // TODO: Fill request struct fields. @@ -274,13 +263,12 @@ func ExampleServiceManagerClient_ListServiceRollouts() { } func ExampleServiceManagerClient_GetServiceRollout() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.GetServiceRolloutRequest{ // TODO: Fill request struct fields. @@ -294,13 +282,12 @@ func ExampleServiceManagerClient_GetServiceRollout() { } func ExampleServiceManagerClient_CreateServiceRollout() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.CreateServiceRolloutRequest{ // TODO: Fill request struct fields. @@ -319,13 +306,12 @@ func ExampleServiceManagerClient_CreateServiceRollout() { } func ExampleServiceManagerClient_GenerateConfigReport() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.GenerateConfigReportRequest{ // TODO: Fill request struct fields. @@ -339,13 +325,12 @@ func ExampleServiceManagerClient_GenerateConfigReport() { } func ExampleServiceManagerClient_EnableService() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.EnableServiceRequest{ // TODO: Fill request struct fields. @@ -364,13 +349,12 @@ func ExampleServiceManagerClient_EnableService() { } func ExampleServiceManagerClient_DisableService() { - // import servicemanagementpb "google.golang.org/genproto/googleapis/api/servicemanagement/v1" - ctx := context.Background() c, err := servicemanagement.NewServiceManagerClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &servicemanagementpb.DisableServiceRequest{ // TODO: Fill request struct fields. diff --git a/serviceusage/apiv1/doc.go b/serviceusage/apiv1/doc.go index dde41c867c24..6ed17f13e89f 100644 --- a/serviceusage/apiv1/doc.go +++ b/serviceusage/apiv1/doc.go @@ -21,6 +21,8 @@ // Platform, lists the available or enabled services, or disables services // that service consumers no longer use. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -30,7 +32,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package serviceusage // import "cloud.google.com/go/serviceusage/apiv1" import ( @@ -50,7 +52,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/serviceusage/apiv1/gapic_metadata.json b/serviceusage/apiv1/gapic_metadata.json index 9c9213fb2f51..5df488bbece9 100644 --- a/serviceusage/apiv1/gapic_metadata.json +++ b/serviceusage/apiv1/gapic_metadata.json @@ -1,42 +1,42 @@ { - "schema": "1.0", - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods.", - "language": "go", - "protoPackage": "google.api.serviceusage.v1", - "libraryPackage": "cloud.google.com/go/serviceusage/apiv1", - "services": { - "ServiceUsage": { - "clients": { - "grpc": { - "libraryClient": "Client", - "rpcs": { - "BatchEnableServices": { - "methods": [ + "schema": "1.0", + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods.", + "language": "go", + "protoPackage": "google.api.serviceusage.v1", + "libraryPackage": "cloud.google.com/go/serviceusage/apiv1", + "services": { + "ServiceUsage": { + "clients": { + "grpc": { + "libraryClient": "Client", + "rpcs": { + "BatchEnableServices": { + "methods": [ "BatchEnableServices" ] }, - "BatchGetServices": { - "methods": [ + "BatchGetServices": { + "methods": [ "BatchGetServices" ] }, - "DisableService": { - "methods": [ + "DisableService": { + "methods": [ "DisableService" ] }, - "EnableService": { - "methods": [ + "EnableService": { + "methods": [ "EnableService" ] }, - "GetService": { - "methods": [ + "GetService": { + "methods": [ "GetService" ] }, - "ListServices": { - "methods": [ + "ListServices": { + "methods": [ "ListServices" ] } diff --git a/serviceusage/apiv1/service_usage_client.go b/serviceusage/apiv1/service_usage_client.go index 8c55541ec084..3027a2e8ad88 100644 --- a/serviceusage/apiv1/service_usage_client.go +++ b/serviceusage/apiv1/service_usage_client.go @@ -49,7 +49,7 @@ type CallOptions struct { BatchGetServices []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("serviceusage.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("serviceusage.mtls.googleapis.com:443"), @@ -72,37 +72,169 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Service Usage API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + EnableService(context.Context, *serviceusagepb.EnableServiceRequest, ...gax.CallOption) (*EnableServiceOperation, error) + EnableServiceOperation(name string) *EnableServiceOperation + DisableService(context.Context, *serviceusagepb.DisableServiceRequest, ...gax.CallOption) (*DisableServiceOperation, error) + DisableServiceOperation(name string) *DisableServiceOperation + GetService(context.Context, *serviceusagepb.GetServiceRequest, ...gax.CallOption) (*serviceusagepb.Service, error) + ListServices(context.Context, *serviceusagepb.ListServicesRequest, ...gax.CallOption) *ServiceIterator + BatchEnableServices(context.Context, *serviceusagepb.BatchEnableServicesRequest, ...gax.CallOption) (*BatchEnableServicesOperation, error) + BatchEnableServicesOperation(name string) *BatchEnableServicesOperation + BatchGetServices(context.Context, *serviceusagepb.BatchGetServicesRequest, ...gax.CallOption) (*serviceusagepb.BatchGetServicesResponse, error) +} + // Client is a client for interacting with Service Usage API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Enables services that service consumers want to use on Google Cloud Platform, +// lists the available or enabled services, or disables services that service +// consumers no longer use. +// +// See Service Usage API (at https://cloud.google.com/service-usage/docs/overview) type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// EnableService enable a service so that it can be used with a project. +func (c *Client) EnableService(ctx context.Context, req *serviceusagepb.EnableServiceRequest, opts ...gax.CallOption) (*EnableServiceOperation, error) { + return c.internalClient.EnableService(ctx, req, opts...) +} + +// EnableServiceOperation returns a new EnableServiceOperation from a given name. +// The name must be that of a previously created EnableServiceOperation, possibly from a different process. +func (c *Client) EnableServiceOperation(name string) *EnableServiceOperation { + return c.internalClient.EnableServiceOperation(name) +} + +// DisableService disable a service so that it can no longer be used with a project. +// This prevents unintended usage that may cause unexpected billing +// charges or security leaks. +// +// It is not valid to call the disable method on a service that is not +// currently enabled. Callers will receive a FAILED_PRECONDITION status if +// the target service is not currently enabled. +func (c *Client) DisableService(ctx context.Context, req *serviceusagepb.DisableServiceRequest, opts ...gax.CallOption) (*DisableServiceOperation, error) { + return c.internalClient.DisableService(ctx, req, opts...) +} + +// DisableServiceOperation returns a new DisableServiceOperation from a given name. +// The name must be that of a previously created DisableServiceOperation, possibly from a different process. +func (c *Client) DisableServiceOperation(name string) *DisableServiceOperation { + return c.internalClient.DisableServiceOperation(name) +} + +// GetService returns the service configuration and enabled state for a given service. +func (c *Client) GetService(ctx context.Context, req *serviceusagepb.GetServiceRequest, opts ...gax.CallOption) (*serviceusagepb.Service, error) { + return c.internalClient.GetService(ctx, req, opts...) +} + +// ListServices list all services available to the specified project, and the current +// state of those services with respect to the project. The list includes +// all public services, all services for which the calling user has the +// servicemanagement.services.bind permission, and all services that have +// already been enabled on the project. The list can be filtered to +// only include services in a specific state, for example to only include +// services enabled on the project. +// +// WARNING: If you need to query enabled services frequently or across +// an organization, you should use +// Cloud Asset Inventory +// API (at https://cloud.google.com/asset-inventory/docs/apis), which provides +// higher throughput and richer filtering capability. +func (c *Client) ListServices(ctx context.Context, req *serviceusagepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { + return c.internalClient.ListServices(ctx, req, opts...) +} + +// BatchEnableServices enable multiple services on a project. The operation is atomic: if enabling +// any service fails, then the entire batch fails, and no state changes occur. +// To enable a single service, use the EnableService method instead. +func (c *Client) BatchEnableServices(ctx context.Context, req *serviceusagepb.BatchEnableServicesRequest, opts ...gax.CallOption) (*BatchEnableServicesOperation, error) { + return c.internalClient.BatchEnableServices(ctx, req, opts...) +} + +// BatchEnableServicesOperation returns a new BatchEnableServicesOperation from a given name. +// The name must be that of a previously created BatchEnableServicesOperation, possibly from a different process. +func (c *Client) BatchEnableServicesOperation(name string) *BatchEnableServicesOperation { + return c.internalClient.BatchEnableServicesOperation(name) +} + +// BatchGetServices returns the service configurations and enabled states for a given list of +// services. +func (c *Client) BatchGetServices(ctx context.Context, req *serviceusagepb.BatchGetServicesRequest, opts ...gax.CallOption) (*serviceusagepb.BatchGetServicesResponse, error) { + return c.internalClient.BatchGetServices(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Service Usage API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client serviceusagepb.ServiceUsageClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new service usage client. +// NewClient creates a new service usage client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // -// Service Usage API (at /service-usage/docs/overview) +// Enables services that service consumers want to use on Google Cloud Platform, +// lists the available or enabled services, or disables services that service +// consumers no longer use. +// +// See Service Usage API (at https://cloud.google.com/service-usage/docs/overview) func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -120,16 +252,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: serviceusagepb.NewServiceUsageClient(connPool), + client: serviceusagepb.NewServiceUsageClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -139,33 +274,33 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// EnableService enable a service so that it can be used with a project. -func (c *Client) EnableService(ctx context.Context, req *serviceusagepb.EnableServiceRequest, opts ...gax.CallOption) (*EnableServiceOperation, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) EnableService(ctx context.Context, req *serviceusagepb.EnableServiceRequest, opts ...gax.CallOption) (*EnableServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -173,7 +308,7 @@ func (c *Client) EnableService(ctx context.Context, req *serviceusagepb.EnableSe } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.EnableService[0:len(c.CallOptions.EnableService):len(c.CallOptions.EnableService)], opts...) + opts = append((*c.CallOptions).EnableService[0:len((*c.CallOptions).EnableService):len((*c.CallOptions).EnableService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -184,18 +319,11 @@ func (c *Client) EnableService(ctx context.Context, req *serviceusagepb.EnableSe return nil, err } return &EnableServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DisableService disable a service so that it can no longer be used with a project. -// This prevents unintended usage that may cause unexpected billing -// charges or security leaks. -// -// It is not valid to call the disable method on a service that is not -// currently enabled. Callers will receive a FAILED_PRECONDITION status if -// the target service is not currently enabled. -func (c *Client) DisableService(ctx context.Context, req *serviceusagepb.DisableServiceRequest, opts ...gax.CallOption) (*DisableServiceOperation, error) { +func (c *gRPCClient) DisableService(ctx context.Context, req *serviceusagepb.DisableServiceRequest, opts ...gax.CallOption) (*DisableServiceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -203,7 +331,7 @@ func (c *Client) DisableService(ctx context.Context, req *serviceusagepb.Disable } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DisableService[0:len(c.CallOptions.DisableService):len(c.CallOptions.DisableService)], opts...) + opts = append((*c.CallOptions).DisableService[0:len((*c.CallOptions).DisableService):len((*c.CallOptions).DisableService)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -214,12 +342,11 @@ func (c *Client) DisableService(ctx context.Context, req *serviceusagepb.Disable return nil, err } return &DisableServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetService returns the service configuration and enabled state for a given service. -func (c *Client) GetService(ctx context.Context, req *serviceusagepb.GetServiceRequest, opts ...gax.CallOption) (*serviceusagepb.Service, error) { +func (c *gRPCClient) GetService(ctx context.Context, req *serviceusagepb.GetServiceRequest, opts ...gax.CallOption) (*serviceusagepb.Service, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -227,7 +354,7 @@ func (c *Client) GetService(ctx context.Context, req *serviceusagepb.GetServiceR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetService[0:len(c.CallOptions.GetService):len(c.CallOptions.GetService)], opts...) + opts = append((*c.CallOptions).GetService[0:len((*c.CallOptions).GetService):len((*c.CallOptions).GetService)], opts...) var resp *serviceusagepb.Service err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -240,23 +367,10 @@ func (c *Client) GetService(ctx context.Context, req *serviceusagepb.GetServiceR return resp, nil } -// ListServices list all services available to the specified project, and the current -// state of those services with respect to the project. The list includes -// all public services, all services for which the calling user has the -// servicemanagement.services.bind permission, and all services that have -// already been enabled on the project. The list can be filtered to -// only include services in a specific state, for example to only include -// services enabled on the project. -// -// WARNING: If you need to query enabled services frequently or across -// an organization, you should use -// Cloud Asset Inventory -// API (at https://cloud.google.com/asset-inventory/docs/apis), which provides -// higher throughput and richer filtering capability. -func (c *Client) ListServices(ctx context.Context, req *serviceusagepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { +func (c *gRPCClient) ListServices(ctx context.Context, req *serviceusagepb.ListServicesRequest, opts ...gax.CallOption) *ServiceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListServices[0:len(c.CallOptions.ListServices):len(c.CallOptions.ListServices)], opts...) + opts = append((*c.CallOptions).ListServices[0:len((*c.CallOptions).ListServices):len((*c.CallOptions).ListServices)], opts...) it := &ServiceIterator{} req = proto.Clone(req).(*serviceusagepb.ListServicesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*serviceusagepb.Service, string, error) { @@ -293,10 +407,7 @@ func (c *Client) ListServices(ctx context.Context, req *serviceusagepb.ListServi return it } -// BatchEnableServices enable multiple services on a project. The operation is atomic: if enabling -// any service fails, then the entire batch fails, and no state changes occur. -// To enable a single service, use the EnableService method instead. -func (c *Client) BatchEnableServices(ctx context.Context, req *serviceusagepb.BatchEnableServicesRequest, opts ...gax.CallOption) (*BatchEnableServicesOperation, error) { +func (c *gRPCClient) BatchEnableServices(ctx context.Context, req *serviceusagepb.BatchEnableServicesRequest, opts ...gax.CallOption) (*BatchEnableServicesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -304,7 +415,7 @@ func (c *Client) BatchEnableServices(ctx context.Context, req *serviceusagepb.Ba } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchEnableServices[0:len(c.CallOptions.BatchEnableServices):len(c.CallOptions.BatchEnableServices)], opts...) + opts = append((*c.CallOptions).BatchEnableServices[0:len((*c.CallOptions).BatchEnableServices):len((*c.CallOptions).BatchEnableServices)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -315,13 +426,11 @@ func (c *Client) BatchEnableServices(ctx context.Context, req *serviceusagepb.Ba return nil, err } return &BatchEnableServicesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// BatchGetServices returns the service configurations and enabled states for a given list of -// services. -func (c *Client) BatchGetServices(ctx context.Context, req *serviceusagepb.BatchGetServicesRequest, opts ...gax.CallOption) (*serviceusagepb.BatchGetServicesResponse, error) { +func (c *gRPCClient) BatchGetServices(ctx context.Context, req *serviceusagepb.BatchGetServicesRequest, opts ...gax.CallOption) (*serviceusagepb.BatchGetServicesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -329,7 +438,7 @@ func (c *Client) BatchGetServices(ctx context.Context, req *serviceusagepb.Batch } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchGetServices[0:len(c.CallOptions.BatchGetServices):len(c.CallOptions.BatchGetServices)], opts...) + opts = append((*c.CallOptions).BatchGetServices[0:len((*c.CallOptions).BatchGetServices):len((*c.CallOptions).BatchGetServices)], opts...) var resp *serviceusagepb.BatchGetServicesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -349,9 +458,9 @@ type BatchEnableServicesOperation struct { // BatchEnableServicesOperation returns a new BatchEnableServicesOperation from a given name. // The name must be that of a previously created BatchEnableServicesOperation, possibly from a different process. -func (c *Client) BatchEnableServicesOperation(name string) *BatchEnableServicesOperation { +func (c *gRPCClient) BatchEnableServicesOperation(name string) *BatchEnableServicesOperation { return &BatchEnableServicesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -418,9 +527,9 @@ type DisableServiceOperation struct { // DisableServiceOperation returns a new DisableServiceOperation from a given name. // The name must be that of a previously created DisableServiceOperation, possibly from a different process. -func (c *Client) DisableServiceOperation(name string) *DisableServiceOperation { +func (c *gRPCClient) DisableServiceOperation(name string) *DisableServiceOperation { return &DisableServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -487,9 +596,9 @@ type EnableServiceOperation struct { // EnableServiceOperation returns a new EnableServiceOperation from a given name. // The name must be that of a previously created EnableServiceOperation, possibly from a different process. -func (c *Client) EnableServiceOperation(name string) *EnableServiceOperation { +func (c *gRPCClient) EnableServiceOperation(name string) *EnableServiceOperation { return &EnableServiceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/serviceusage/apiv1/service_usage_client_example_test.go b/serviceusage/apiv1/service_usage_client_example_test.go index 819c5ec6f9e4..021c9a717460 100644 --- a/serviceusage/apiv1/service_usage_client_example_test.go +++ b/serviceusage/apiv1/service_usage_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_EnableService() { - // import serviceusagepb "google.golang.org/genproto/googleapis/api/serviceusage/v1" - ctx := context.Background() c, err := serviceusage.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &serviceusagepb.EnableServiceRequest{ // TODO: Fill request struct fields. @@ -60,13 +61,12 @@ func ExampleClient_EnableService() { } func ExampleClient_DisableService() { - // import serviceusagepb "google.golang.org/genproto/googleapis/api/serviceusage/v1" - ctx := context.Background() c, err := serviceusage.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &serviceusagepb.DisableServiceRequest{ // TODO: Fill request struct fields. @@ -85,13 +85,12 @@ func ExampleClient_DisableService() { } func ExampleClient_GetService() { - // import serviceusagepb "google.golang.org/genproto/googleapis/api/serviceusage/v1" - ctx := context.Background() c, err := serviceusage.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &serviceusagepb.GetServiceRequest{ // TODO: Fill request struct fields. @@ -105,14 +104,12 @@ func ExampleClient_GetService() { } func ExampleClient_ListServices() { - // import serviceusagepb "google.golang.org/genproto/googleapis/api/serviceusage/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := serviceusage.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &serviceusagepb.ListServicesRequest{ // TODO: Fill request struct fields. @@ -132,13 +129,12 @@ func ExampleClient_ListServices() { } func ExampleClient_BatchEnableServices() { - // import serviceusagepb "google.golang.org/genproto/googleapis/api/serviceusage/v1" - ctx := context.Background() c, err := serviceusage.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &serviceusagepb.BatchEnableServicesRequest{ // TODO: Fill request struct fields. @@ -157,13 +153,12 @@ func ExampleClient_BatchEnableServices() { } func ExampleClient_BatchGetServices() { - // import serviceusagepb "google.golang.org/genproto/googleapis/api/serviceusage/v1" - ctx := context.Background() c, err := serviceusage.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &serviceusagepb.BatchGetServicesRequest{ // TODO: Fill request struct fields. diff --git a/spanner/admin/database/apiv1/database_admin_client.go b/spanner/admin/database/apiv1/database_admin_client.go index b171a4a0380d..db043d19087f 100644 --- a/spanner/admin/database/apiv1/database_admin_client.go +++ b/spanner/admin/database/apiv1/database_admin_client.go @@ -62,7 +62,7 @@ type DatabaseAdminCallOptions struct { ListBackupOperations []gax.CallOption } -func defaultDatabaseAdminClientOptions() []option.ClientOption { +func defaultDatabaseAdminGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("spanner.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("spanner.mtls.googleapis.com:443"), @@ -228,32 +228,298 @@ func defaultDatabaseAdminCallOptions() *DatabaseAdminCallOptions { } } +// internalDatabaseAdminClient is an interface that defines the methods availaible from Cloud Spanner Database Admin API. +type internalDatabaseAdminClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListDatabases(context.Context, *databasepb.ListDatabasesRequest, ...gax.CallOption) *DatabaseIterator + CreateDatabase(context.Context, *databasepb.CreateDatabaseRequest, ...gax.CallOption) (*CreateDatabaseOperation, error) + CreateDatabaseOperation(name string) *CreateDatabaseOperation + GetDatabase(context.Context, *databasepb.GetDatabaseRequest, ...gax.CallOption) (*databasepb.Database, error) + UpdateDatabaseDdl(context.Context, *databasepb.UpdateDatabaseDdlRequest, ...gax.CallOption) (*UpdateDatabaseDdlOperation, error) + UpdateDatabaseDdlOperation(name string) *UpdateDatabaseDdlOperation + DropDatabase(context.Context, *databasepb.DropDatabaseRequest, ...gax.CallOption) error + GetDatabaseDdl(context.Context, *databasepb.GetDatabaseDdlRequest, ...gax.CallOption) (*databasepb.GetDatabaseDdlResponse, error) + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) + CreateBackup(context.Context, *databasepb.CreateBackupRequest, ...gax.CallOption) (*CreateBackupOperation, error) + CreateBackupOperation(name string) *CreateBackupOperation + GetBackup(context.Context, *databasepb.GetBackupRequest, ...gax.CallOption) (*databasepb.Backup, error) + UpdateBackup(context.Context, *databasepb.UpdateBackupRequest, ...gax.CallOption) (*databasepb.Backup, error) + DeleteBackup(context.Context, *databasepb.DeleteBackupRequest, ...gax.CallOption) error + ListBackups(context.Context, *databasepb.ListBackupsRequest, ...gax.CallOption) *BackupIterator + RestoreDatabase(context.Context, *databasepb.RestoreDatabaseRequest, ...gax.CallOption) (*RestoreDatabaseOperation, error) + RestoreDatabaseOperation(name string) *RestoreDatabaseOperation + ListDatabaseOperations(context.Context, *databasepb.ListDatabaseOperationsRequest, ...gax.CallOption) *OperationIterator + ListBackupOperations(context.Context, *databasepb.ListBackupOperationsRequest, ...gax.CallOption) *OperationIterator +} + // DatabaseAdminClient is a client for interacting with Cloud Spanner Database Admin API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Cloud Spanner Database Admin API +// +// The Cloud Spanner Database Admin API can be used to create, drop, and +// list databases. It also enables updating the schema of pre-existing +// databases. It can be also used to create, delete and list backups for a +// database and to restore from an existing backup. type DatabaseAdminClient struct { + // The internal transport-dependent client. + internalClient internalDatabaseAdminClient + + // The call options for this service. + CallOptions *DatabaseAdminCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *DatabaseAdminClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *DatabaseAdminClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *DatabaseAdminClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListDatabases lists Cloud Spanner databases. +func (c *DatabaseAdminClient) ListDatabases(ctx context.Context, req *databasepb.ListDatabasesRequest, opts ...gax.CallOption) *DatabaseIterator { + return c.internalClient.ListDatabases(ctx, req, opts...) +} + +// CreateDatabase creates a new Cloud Spanner database and starts to prepare it for serving. +// The returned [long-running operation][google.longrunning.Operation] will +// have a name of the format /operations/ and +// can be used to track preparation of the database. The +// metadata field type is +// CreateDatabaseMetadata. The +// response field type is +// Database, if successful. +func (c *DatabaseAdminClient) CreateDatabase(ctx context.Context, req *databasepb.CreateDatabaseRequest, opts ...gax.CallOption) (*CreateDatabaseOperation, error) { + return c.internalClient.CreateDatabase(ctx, req, opts...) +} + +// CreateDatabaseOperation returns a new CreateDatabaseOperation from a given name. +// The name must be that of a previously created CreateDatabaseOperation, possibly from a different process. +func (c *DatabaseAdminClient) CreateDatabaseOperation(name string) *CreateDatabaseOperation { + return c.internalClient.CreateDatabaseOperation(name) +} + +// GetDatabase gets the state of a Cloud Spanner database. +func (c *DatabaseAdminClient) GetDatabase(ctx context.Context, req *databasepb.GetDatabaseRequest, opts ...gax.CallOption) (*databasepb.Database, error) { + return c.internalClient.GetDatabase(ctx, req, opts...) +} + +// UpdateDatabaseDdl updates the schema of a Cloud Spanner database by +// creating/altering/dropping tables, columns, indexes, etc. The returned +// [long-running operation][google.longrunning.Operation] will have a name of +// the format /operations/ and can be used to +// track execution of the schema change(s). The +// metadata field type is +// UpdateDatabaseDdlMetadata. The operation has no response. +func (c *DatabaseAdminClient) UpdateDatabaseDdl(ctx context.Context, req *databasepb.UpdateDatabaseDdlRequest, opts ...gax.CallOption) (*UpdateDatabaseDdlOperation, error) { + return c.internalClient.UpdateDatabaseDdl(ctx, req, opts...) +} + +// UpdateDatabaseDdlOperation returns a new UpdateDatabaseDdlOperation from a given name. +// The name must be that of a previously created UpdateDatabaseDdlOperation, possibly from a different process. +func (c *DatabaseAdminClient) UpdateDatabaseDdlOperation(name string) *UpdateDatabaseDdlOperation { + return c.internalClient.UpdateDatabaseDdlOperation(name) +} + +// DropDatabase drops (aka deletes) a Cloud Spanner database. +// Completed backups for the database will be retained according to their +// expire_time. +func (c *DatabaseAdminClient) DropDatabase(ctx context.Context, req *databasepb.DropDatabaseRequest, opts ...gax.CallOption) error { + return c.internalClient.DropDatabase(ctx, req, opts...) +} + +// GetDatabaseDdl returns the schema of a Cloud Spanner database as a list of formatted +// DDL statements. This method does not show pending schema updates, those may +// be queried using the Operations API. +func (c *DatabaseAdminClient) GetDatabaseDdl(ctx context.Context, req *databasepb.GetDatabaseDdlRequest, opts ...gax.CallOption) (*databasepb.GetDatabaseDdlResponse, error) { + return c.internalClient.GetDatabaseDdl(ctx, req, opts...) +} + +// SetIamPolicy sets the access control policy on a database or backup resource. +// Replaces any existing policy. +// +// Authorization requires spanner.databases.setIamPolicy +// permission on resource. +// For backups, authorization requires spanner.backups.setIamPolicy +// permission on resource. +func (c *DatabaseAdminClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy for a database or backup resource. +// Returns an empty policy if a database or backup exists but does not have a +// policy set. +// +// Authorization requires spanner.databases.getIamPolicy permission on +// resource. +// For backups, authorization requires spanner.backups.getIamPolicy +// permission on resource. +func (c *DatabaseAdminClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns permissions that the caller has on the specified database or backup +// resource. +// +// Attempting this RPC on a non-existent Cloud Spanner database will +// result in a NOT_FOUND error if the user has +// spanner.databases.list permission on the containing Cloud +// Spanner instance. Otherwise returns an empty set of permissions. +// Calling this method on a backup that does not exist will +// result in a NOT_FOUND error if the user has +// spanner.backups.list permission on the containing instance. +func (c *DatabaseAdminClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// CreateBackup starts creating a new Cloud Spanner Backup. +// The returned backup [long-running operation][google.longrunning.Operation] +// will have a name of the format +// projects//instances//backups//operations/ +// and can be used to track creation of the backup. The +// metadata field type is +// CreateBackupMetadata. The +// response field type is +// Backup, if successful. Cancelling the returned operation will stop the +// creation and delete the backup. +// There can be only one pending backup creation per database. Backup creation +// of different databases can run concurrently. +func (c *DatabaseAdminClient) CreateBackup(ctx context.Context, req *databasepb.CreateBackupRequest, opts ...gax.CallOption) (*CreateBackupOperation, error) { + return c.internalClient.CreateBackup(ctx, req, opts...) +} + +// CreateBackupOperation returns a new CreateBackupOperation from a given name. +// The name must be that of a previously created CreateBackupOperation, possibly from a different process. +func (c *DatabaseAdminClient) CreateBackupOperation(name string) *CreateBackupOperation { + return c.internalClient.CreateBackupOperation(name) +} + +// GetBackup gets metadata on a pending or completed Backup. +func (c *DatabaseAdminClient) GetBackup(ctx context.Context, req *databasepb.GetBackupRequest, opts ...gax.CallOption) (*databasepb.Backup, error) { + return c.internalClient.GetBackup(ctx, req, opts...) +} + +// UpdateBackup updates a pending or completed Backup. +func (c *DatabaseAdminClient) UpdateBackup(ctx context.Context, req *databasepb.UpdateBackupRequest, opts ...gax.CallOption) (*databasepb.Backup, error) { + return c.internalClient.UpdateBackup(ctx, req, opts...) +} + +// DeleteBackup deletes a pending or completed Backup. +func (c *DatabaseAdminClient) DeleteBackup(ctx context.Context, req *databasepb.DeleteBackupRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteBackup(ctx, req, opts...) +} + +// ListBackups lists completed and pending backups. +// Backups returned are ordered by create_time in descending order, +// starting from the most recent create_time. +func (c *DatabaseAdminClient) ListBackups(ctx context.Context, req *databasepb.ListBackupsRequest, opts ...gax.CallOption) *BackupIterator { + return c.internalClient.ListBackups(ctx, req, opts...) +} + +// RestoreDatabase create a new database by restoring from a completed backup. The new +// database must be in the same project and in an instance with the same +// instance configuration as the instance containing +// the backup. The returned database [long-running +// operation][google.longrunning.Operation] has a name of the format +// projects//instances//databases//operations/, +// and can be used to track the progress of the operation, and to cancel it. +// The metadata field type is +// RestoreDatabaseMetadata. +// The response type +// is Database, if +// successful. Cancelling the returned operation will stop the restore and +// delete the database. +// There can be only one database being restored into an instance at a time. +// Once the restore operation completes, a new restore operation can be +// initiated, without waiting for the optimize operation associated with the +// first restore to complete. +func (c *DatabaseAdminClient) RestoreDatabase(ctx context.Context, req *databasepb.RestoreDatabaseRequest, opts ...gax.CallOption) (*RestoreDatabaseOperation, error) { + return c.internalClient.RestoreDatabase(ctx, req, opts...) +} + +// RestoreDatabaseOperation returns a new RestoreDatabaseOperation from a given name. +// The name must be that of a previously created RestoreDatabaseOperation, possibly from a different process. +func (c *DatabaseAdminClient) RestoreDatabaseOperation(name string) *RestoreDatabaseOperation { + return c.internalClient.RestoreDatabaseOperation(name) +} + +// ListDatabaseOperations lists database [longrunning-operations][google.longrunning.Operation]. +// A database operation has a name of the form +// projects//instances//databases//operations/. +// The long-running operation +// metadata field type +// metadata.type_url describes the type of the metadata. Operations returned +// include those that have completed/failed/canceled within the last 7 days, +// and pending operations. +func (c *DatabaseAdminClient) ListDatabaseOperations(ctx context.Context, req *databasepb.ListDatabaseOperationsRequest, opts ...gax.CallOption) *OperationIterator { + return c.internalClient.ListDatabaseOperations(ctx, req, opts...) +} + +// ListBackupOperations lists the backup [long-running operations][google.longrunning.Operation] in +// the given instance. A backup operation has a name of the form +// projects//instances//backups//operations/. +// The long-running operation +// metadata field type +// metadata.type_url describes the type of the metadata. Operations returned +// include those that have completed/failed/canceled within the last 7 days, +// and pending operations. Operations returned are ordered by +// operation.metadata.value.progress.start_time in descending order starting +// from the most recently started operation. +func (c *DatabaseAdminClient) ListBackupOperations(ctx context.Context, req *databasepb.ListBackupOperationsRequest, opts ...gax.CallOption) *OperationIterator { + return c.internalClient.ListBackupOperations(ctx, req, opts...) +} + +// databaseAdminGRPCClient is a client for interacting with Cloud Spanner Database Admin API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type databaseAdminGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing DatabaseAdminClient + CallOptions **DatabaseAdminCallOptions + // The gRPC API client. databaseAdminClient databasepb.DatabaseAdminClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *DatabaseAdminCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewDatabaseAdminClient creates a new database admin client. +// NewDatabaseAdminClient creates a new database admin client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Cloud Spanner Database Admin API // @@ -262,8 +528,7 @@ type DatabaseAdminClient struct { // databases. It can be also used to create, delete and list backups for a // database and to restore from an existing backup. func NewDatabaseAdminClient(ctx context.Context, opts ...option.ClientOption) (*DatabaseAdminClient, error) { - clientOpts := defaultDatabaseAdminClientOptions() - + clientOpts := defaultDatabaseAdminGRPCClientOptions() if newDatabaseAdminClientHook != nil { hookOpts, err := newDatabaseAdminClientHook(ctx, clientHookParams{}) if err != nil { @@ -281,16 +546,19 @@ func NewDatabaseAdminClient(ctx context.Context, opts ...option.ClientOption) (* if err != nil { return nil, err } - c := &DatabaseAdminClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultDatabaseAdminCallOptions(), + client := DatabaseAdminClient{CallOptions: defaultDatabaseAdminCallOptions()} + c := &databaseAdminGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, databaseAdminClient: databasepb.NewDatabaseAdminClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -300,36 +568,36 @@ func NewDatabaseAdminClient(ctx context.Context, opts ...option.ClientOption) (* // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *DatabaseAdminClient) Connection() *grpc.ClientConn { +func (c *databaseAdminGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *DatabaseAdminClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *DatabaseAdminClient) setGoogleClientInfo(keyval ...string) { +func (c *databaseAdminGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListDatabases lists Cloud Spanner databases. -func (c *DatabaseAdminClient) ListDatabases(ctx context.Context, req *databasepb.ListDatabasesRequest, opts ...gax.CallOption) *DatabaseIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *databaseAdminGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *databaseAdminGRPCClient) ListDatabases(ctx context.Context, req *databasepb.ListDatabasesRequest, opts ...gax.CallOption) *DatabaseIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDatabases[0:len(c.CallOptions.ListDatabases):len(c.CallOptions.ListDatabases)], opts...) + opts = append((*c.CallOptions).ListDatabases[0:len((*c.CallOptions).ListDatabases):len((*c.CallOptions).ListDatabases)], opts...) it := &DatabaseIterator{} req = proto.Clone(req).(*databasepb.ListDatabasesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*databasepb.Database, string, error) { @@ -366,15 +634,7 @@ func (c *DatabaseAdminClient) ListDatabases(ctx context.Context, req *databasepb return it } -// CreateDatabase creates a new Cloud Spanner database and starts to prepare it for serving. -// The returned [long-running operation][google.longrunning.Operation] will -// have a name of the format /operations/ and -// can be used to track preparation of the database. The -// metadata field type is -// CreateDatabaseMetadata. The -// response field type is -// Database, if successful. -func (c *DatabaseAdminClient) CreateDatabase(ctx context.Context, req *databasepb.CreateDatabaseRequest, opts ...gax.CallOption) (*CreateDatabaseOperation, error) { +func (c *databaseAdminGRPCClient) CreateDatabase(ctx context.Context, req *databasepb.CreateDatabaseRequest, opts ...gax.CallOption) (*CreateDatabaseOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 3600000*time.Millisecond) defer cancel() @@ -382,7 +642,7 @@ func (c *DatabaseAdminClient) CreateDatabase(ctx context.Context, req *databasep } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateDatabase[0:len(c.CallOptions.CreateDatabase):len(c.CallOptions.CreateDatabase)], opts...) + opts = append((*c.CallOptions).CreateDatabase[0:len((*c.CallOptions).CreateDatabase):len((*c.CallOptions).CreateDatabase)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -393,12 +653,11 @@ func (c *DatabaseAdminClient) CreateDatabase(ctx context.Context, req *databasep return nil, err } return &CreateDatabaseOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetDatabase gets the state of a Cloud Spanner database. -func (c *DatabaseAdminClient) GetDatabase(ctx context.Context, req *databasepb.GetDatabaseRequest, opts ...gax.CallOption) (*databasepb.Database, error) { +func (c *databaseAdminGRPCClient) GetDatabase(ctx context.Context, req *databasepb.GetDatabaseRequest, opts ...gax.CallOption) (*databasepb.Database, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 3600000*time.Millisecond) defer cancel() @@ -406,7 +665,7 @@ func (c *DatabaseAdminClient) GetDatabase(ctx context.Context, req *databasepb.G } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetDatabase[0:len(c.CallOptions.GetDatabase):len(c.CallOptions.GetDatabase)], opts...) + opts = append((*c.CallOptions).GetDatabase[0:len((*c.CallOptions).GetDatabase):len((*c.CallOptions).GetDatabase)], opts...) var resp *databasepb.Database err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -419,14 +678,7 @@ func (c *DatabaseAdminClient) GetDatabase(ctx context.Context, req *databasepb.G return resp, nil } -// UpdateDatabaseDdl updates the schema of a Cloud Spanner database by -// creating/altering/dropping tables, columns, indexes, etc. The returned -// [long-running operation][google.longrunning.Operation] will have a name of -// the format /operations/ and can be used to -// track execution of the schema change(s). The -// metadata field type is -// UpdateDatabaseDdlMetadata. The operation has no response. -func (c *DatabaseAdminClient) UpdateDatabaseDdl(ctx context.Context, req *databasepb.UpdateDatabaseDdlRequest, opts ...gax.CallOption) (*UpdateDatabaseDdlOperation, error) { +func (c *databaseAdminGRPCClient) UpdateDatabaseDdl(ctx context.Context, req *databasepb.UpdateDatabaseDdlRequest, opts ...gax.CallOption) (*UpdateDatabaseDdlOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 3600000*time.Millisecond) defer cancel() @@ -434,7 +686,7 @@ func (c *DatabaseAdminClient) UpdateDatabaseDdl(ctx context.Context, req *databa } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateDatabaseDdl[0:len(c.CallOptions.UpdateDatabaseDdl):len(c.CallOptions.UpdateDatabaseDdl)], opts...) + opts = append((*c.CallOptions).UpdateDatabaseDdl[0:len((*c.CallOptions).UpdateDatabaseDdl):len((*c.CallOptions).UpdateDatabaseDdl)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -445,14 +697,11 @@ func (c *DatabaseAdminClient) UpdateDatabaseDdl(ctx context.Context, req *databa return nil, err } return &UpdateDatabaseDdlOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DropDatabase drops (aka deletes) a Cloud Spanner database. -// Completed backups for the database will be retained according to their -// expire_time. -func (c *DatabaseAdminClient) DropDatabase(ctx context.Context, req *databasepb.DropDatabaseRequest, opts ...gax.CallOption) error { +func (c *databaseAdminGRPCClient) DropDatabase(ctx context.Context, req *databasepb.DropDatabaseRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 3600000*time.Millisecond) defer cancel() @@ -460,7 +709,7 @@ func (c *DatabaseAdminClient) DropDatabase(ctx context.Context, req *databasepb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DropDatabase[0:len(c.CallOptions.DropDatabase):len(c.CallOptions.DropDatabase)], opts...) + opts = append((*c.CallOptions).DropDatabase[0:len((*c.CallOptions).DropDatabase):len((*c.CallOptions).DropDatabase)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.databaseAdminClient.DropDatabase(ctx, req, settings.GRPC...) @@ -469,10 +718,7 @@ func (c *DatabaseAdminClient) DropDatabase(ctx context.Context, req *databasepb. return err } -// GetDatabaseDdl returns the schema of a Cloud Spanner database as a list of formatted -// DDL statements. This method does not show pending schema updates, those may -// be queried using the Operations API. -func (c *DatabaseAdminClient) GetDatabaseDdl(ctx context.Context, req *databasepb.GetDatabaseDdlRequest, opts ...gax.CallOption) (*databasepb.GetDatabaseDdlResponse, error) { +func (c *databaseAdminGRPCClient) GetDatabaseDdl(ctx context.Context, req *databasepb.GetDatabaseDdlRequest, opts ...gax.CallOption) (*databasepb.GetDatabaseDdlResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 3600000*time.Millisecond) defer cancel() @@ -480,7 +726,7 @@ func (c *DatabaseAdminClient) GetDatabaseDdl(ctx context.Context, req *databasep } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetDatabaseDdl[0:len(c.CallOptions.GetDatabaseDdl):len(c.CallOptions.GetDatabaseDdl)], opts...) + opts = append((*c.CallOptions).GetDatabaseDdl[0:len((*c.CallOptions).GetDatabaseDdl):len((*c.CallOptions).GetDatabaseDdl)], opts...) var resp *databasepb.GetDatabaseDdlResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -493,14 +739,7 @@ func (c *DatabaseAdminClient) GetDatabaseDdl(ctx context.Context, req *databasep return resp, nil } -// SetIamPolicy sets the access control policy on a database or backup resource. -// Replaces any existing policy. -// -// Authorization requires spanner.databases.setIamPolicy -// permission on resource. -// For backups, authorization requires spanner.backups.setIamPolicy -// permission on resource. -func (c *DatabaseAdminClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *databaseAdminGRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -508,7 +747,7 @@ func (c *DatabaseAdminClient) SetIamPolicy(ctx context.Context, req *iampb.SetIa } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -521,15 +760,7 @@ func (c *DatabaseAdminClient) SetIamPolicy(ctx context.Context, req *iampb.SetIa return resp, nil } -// GetIamPolicy gets the access control policy for a database or backup resource. -// Returns an empty policy if a database or backup exists but does not have a -// policy set. -// -// Authorization requires spanner.databases.getIamPolicy permission on -// resource. -// For backups, authorization requires spanner.backups.getIamPolicy -// permission on resource. -func (c *DatabaseAdminClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *databaseAdminGRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -537,7 +768,7 @@ func (c *DatabaseAdminClient) GetIamPolicy(ctx context.Context, req *iampb.GetIa } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -550,17 +781,7 @@ func (c *DatabaseAdminClient) GetIamPolicy(ctx context.Context, req *iampb.GetIa return resp, nil } -// TestIamPermissions returns permissions that the caller has on the specified database or backup -// resource. -// -// Attempting this RPC on a non-existent Cloud Spanner database will -// result in a NOT_FOUND error if the user has -// spanner.databases.list permission on the containing Cloud -// Spanner instance. Otherwise returns an empty set of permissions. -// Calling this method on a backup that does not exist will -// result in a NOT_FOUND error if the user has -// spanner.backups.list permission on the containing instance. -func (c *DatabaseAdminClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *databaseAdminGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -568,7 +789,7 @@ func (c *DatabaseAdminClient) TestIamPermissions(ctx context.Context, req *iampb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -581,19 +802,7 @@ func (c *DatabaseAdminClient) TestIamPermissions(ctx context.Context, req *iampb return resp, nil } -// CreateBackup starts creating a new Cloud Spanner Backup. -// The returned backup [long-running operation][google.longrunning.Operation] -// will have a name of the format -// projects//instances//backups//operations/ -// and can be used to track creation of the backup. The -// metadata field type is -// CreateBackupMetadata. The -// response field type is -// Backup, if successful. Cancelling the returned operation will stop the -// creation and delete the backup. -// There can be only one pending backup creation per database. Backup creation -// of different databases can run concurrently. -func (c *DatabaseAdminClient) CreateBackup(ctx context.Context, req *databasepb.CreateBackupRequest, opts ...gax.CallOption) (*CreateBackupOperation, error) { +func (c *databaseAdminGRPCClient) CreateBackup(ctx context.Context, req *databasepb.CreateBackupRequest, opts ...gax.CallOption) (*CreateBackupOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 3600000*time.Millisecond) defer cancel() @@ -601,7 +810,7 @@ func (c *DatabaseAdminClient) CreateBackup(ctx context.Context, req *databasepb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateBackup[0:len(c.CallOptions.CreateBackup):len(c.CallOptions.CreateBackup)], opts...) + opts = append((*c.CallOptions).CreateBackup[0:len((*c.CallOptions).CreateBackup):len((*c.CallOptions).CreateBackup)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -612,12 +821,11 @@ func (c *DatabaseAdminClient) CreateBackup(ctx context.Context, req *databasepb. return nil, err } return &CreateBackupOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetBackup gets metadata on a pending or completed Backup. -func (c *DatabaseAdminClient) GetBackup(ctx context.Context, req *databasepb.GetBackupRequest, opts ...gax.CallOption) (*databasepb.Backup, error) { +func (c *databaseAdminGRPCClient) GetBackup(ctx context.Context, req *databasepb.GetBackupRequest, opts ...gax.CallOption) (*databasepb.Backup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 3600000*time.Millisecond) defer cancel() @@ -625,7 +833,7 @@ func (c *DatabaseAdminClient) GetBackup(ctx context.Context, req *databasepb.Get } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetBackup[0:len(c.CallOptions.GetBackup):len(c.CallOptions.GetBackup)], opts...) + opts = append((*c.CallOptions).GetBackup[0:len((*c.CallOptions).GetBackup):len((*c.CallOptions).GetBackup)], opts...) var resp *databasepb.Backup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -638,8 +846,7 @@ func (c *DatabaseAdminClient) GetBackup(ctx context.Context, req *databasepb.Get return resp, nil } -// UpdateBackup updates a pending or completed Backup. -func (c *DatabaseAdminClient) UpdateBackup(ctx context.Context, req *databasepb.UpdateBackupRequest, opts ...gax.CallOption) (*databasepb.Backup, error) { +func (c *databaseAdminGRPCClient) UpdateBackup(ctx context.Context, req *databasepb.UpdateBackupRequest, opts ...gax.CallOption) (*databasepb.Backup, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 3600000*time.Millisecond) defer cancel() @@ -647,7 +854,7 @@ func (c *DatabaseAdminClient) UpdateBackup(ctx context.Context, req *databasepb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "backup.name", url.QueryEscape(req.GetBackup().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateBackup[0:len(c.CallOptions.UpdateBackup):len(c.CallOptions.UpdateBackup)], opts...) + opts = append((*c.CallOptions).UpdateBackup[0:len((*c.CallOptions).UpdateBackup):len((*c.CallOptions).UpdateBackup)], opts...) var resp *databasepb.Backup err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -660,8 +867,7 @@ func (c *DatabaseAdminClient) UpdateBackup(ctx context.Context, req *databasepb. return resp, nil } -// DeleteBackup deletes a pending or completed Backup. -func (c *DatabaseAdminClient) DeleteBackup(ctx context.Context, req *databasepb.DeleteBackupRequest, opts ...gax.CallOption) error { +func (c *databaseAdminGRPCClient) DeleteBackup(ctx context.Context, req *databasepb.DeleteBackupRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 3600000*time.Millisecond) defer cancel() @@ -669,7 +875,7 @@ func (c *DatabaseAdminClient) DeleteBackup(ctx context.Context, req *databasepb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteBackup[0:len(c.CallOptions.DeleteBackup):len(c.CallOptions.DeleteBackup)], opts...) + opts = append((*c.CallOptions).DeleteBackup[0:len((*c.CallOptions).DeleteBackup):len((*c.CallOptions).DeleteBackup)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.databaseAdminClient.DeleteBackup(ctx, req, settings.GRPC...) @@ -678,13 +884,10 @@ func (c *DatabaseAdminClient) DeleteBackup(ctx context.Context, req *databasepb. return err } -// ListBackups lists completed and pending backups. -// Backups returned are ordered by create_time in descending order, -// starting from the most recent create_time. -func (c *DatabaseAdminClient) ListBackups(ctx context.Context, req *databasepb.ListBackupsRequest, opts ...gax.CallOption) *BackupIterator { +func (c *databaseAdminGRPCClient) ListBackups(ctx context.Context, req *databasepb.ListBackupsRequest, opts ...gax.CallOption) *BackupIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListBackups[0:len(c.CallOptions.ListBackups):len(c.CallOptions.ListBackups)], opts...) + opts = append((*c.CallOptions).ListBackups[0:len((*c.CallOptions).ListBackups):len((*c.CallOptions).ListBackups)], opts...) it := &BackupIterator{} req = proto.Clone(req).(*databasepb.ListBackupsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*databasepb.Backup, string, error) { @@ -721,24 +924,7 @@ func (c *DatabaseAdminClient) ListBackups(ctx context.Context, req *databasepb.L return it } -// RestoreDatabase create a new database by restoring from a completed backup. The new -// database must be in the same project and in an instance with the same -// instance configuration as the instance containing -// the backup. The returned database [long-running -// operation][google.longrunning.Operation] has a name of the format -// projects//instances//databases//operations/, -// and can be used to track the progress of the operation, and to cancel it. -// The metadata field type is -// RestoreDatabaseMetadata. -// The response type -// is Database, if -// successful. Cancelling the returned operation will stop the restore and -// delete the database. -// There can be only one database being restored into an instance at a time. -// Once the restore operation completes, a new restore operation can be -// initiated, without waiting for the optimize operation associated with the -// first restore to complete. -func (c *DatabaseAdminClient) RestoreDatabase(ctx context.Context, req *databasepb.RestoreDatabaseRequest, opts ...gax.CallOption) (*RestoreDatabaseOperation, error) { +func (c *databaseAdminGRPCClient) RestoreDatabase(ctx context.Context, req *databasepb.RestoreDatabaseRequest, opts ...gax.CallOption) (*RestoreDatabaseOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 3600000*time.Millisecond) defer cancel() @@ -746,7 +932,7 @@ func (c *DatabaseAdminClient) RestoreDatabase(ctx context.Context, req *database } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RestoreDatabase[0:len(c.CallOptions.RestoreDatabase):len(c.CallOptions.RestoreDatabase)], opts...) + opts = append((*c.CallOptions).RestoreDatabase[0:len((*c.CallOptions).RestoreDatabase):len((*c.CallOptions).RestoreDatabase)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -757,22 +943,14 @@ func (c *DatabaseAdminClient) RestoreDatabase(ctx context.Context, req *database return nil, err } return &RestoreDatabaseOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListDatabaseOperations lists database [longrunning-operations][google.longrunning.Operation]. -// A database operation has a name of the form -// projects//instances//databases//operations/. -// The long-running operation -// metadata field type -// metadata.type_url describes the type of the metadata. Operations returned -// include those that have completed/failed/canceled within the last 7 days, -// and pending operations. -func (c *DatabaseAdminClient) ListDatabaseOperations(ctx context.Context, req *databasepb.ListDatabaseOperationsRequest, opts ...gax.CallOption) *OperationIterator { +func (c *databaseAdminGRPCClient) ListDatabaseOperations(ctx context.Context, req *databasepb.ListDatabaseOperationsRequest, opts ...gax.CallOption) *OperationIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListDatabaseOperations[0:len(c.CallOptions.ListDatabaseOperations):len(c.CallOptions.ListDatabaseOperations)], opts...) + opts = append((*c.CallOptions).ListDatabaseOperations[0:len((*c.CallOptions).ListDatabaseOperations):len((*c.CallOptions).ListDatabaseOperations)], opts...) it := &OperationIterator{} req = proto.Clone(req).(*databasepb.ListDatabaseOperationsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { @@ -809,20 +987,10 @@ func (c *DatabaseAdminClient) ListDatabaseOperations(ctx context.Context, req *d return it } -// ListBackupOperations lists the backup [long-running operations][google.longrunning.Operation] in -// the given instance. A backup operation has a name of the form -// projects//instances//backups//operations/. -// The long-running operation -// metadata field type -// metadata.type_url describes the type of the metadata. Operations returned -// include those that have completed/failed/canceled within the last 7 days, -// and pending operations. Operations returned are ordered by -// operation.metadata.value.progress.start_time in descending order starting -// from the most recently started operation. -func (c *DatabaseAdminClient) ListBackupOperations(ctx context.Context, req *databasepb.ListBackupOperationsRequest, opts ...gax.CallOption) *OperationIterator { +func (c *databaseAdminGRPCClient) ListBackupOperations(ctx context.Context, req *databasepb.ListBackupOperationsRequest, opts ...gax.CallOption) *OperationIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListBackupOperations[0:len(c.CallOptions.ListBackupOperations):len(c.CallOptions.ListBackupOperations)], opts...) + opts = append((*c.CallOptions).ListBackupOperations[0:len((*c.CallOptions).ListBackupOperations):len((*c.CallOptions).ListBackupOperations)], opts...) it := &OperationIterator{} req = proto.Clone(req).(*databasepb.ListBackupOperationsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*longrunningpb.Operation, string, error) { @@ -866,9 +1034,9 @@ type CreateBackupOperation struct { // CreateBackupOperation returns a new CreateBackupOperation from a given name. // The name must be that of a previously created CreateBackupOperation, possibly from a different process. -func (c *DatabaseAdminClient) CreateBackupOperation(name string) *CreateBackupOperation { +func (c *databaseAdminGRPCClient) CreateBackupOperation(name string) *CreateBackupOperation { return &CreateBackupOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -935,9 +1103,9 @@ type CreateDatabaseOperation struct { // CreateDatabaseOperation returns a new CreateDatabaseOperation from a given name. // The name must be that of a previously created CreateDatabaseOperation, possibly from a different process. -func (c *DatabaseAdminClient) CreateDatabaseOperation(name string) *CreateDatabaseOperation { +func (c *databaseAdminGRPCClient) CreateDatabaseOperation(name string) *CreateDatabaseOperation { return &CreateDatabaseOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1004,9 +1172,9 @@ type RestoreDatabaseOperation struct { // RestoreDatabaseOperation returns a new RestoreDatabaseOperation from a given name. // The name must be that of a previously created RestoreDatabaseOperation, possibly from a different process. -func (c *DatabaseAdminClient) RestoreDatabaseOperation(name string) *RestoreDatabaseOperation { +func (c *databaseAdminGRPCClient) RestoreDatabaseOperation(name string) *RestoreDatabaseOperation { return &RestoreDatabaseOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1073,9 +1241,9 @@ type UpdateDatabaseDdlOperation struct { // UpdateDatabaseDdlOperation returns a new UpdateDatabaseDdlOperation from a given name. // The name must be that of a previously created UpdateDatabaseDdlOperation, possibly from a different process. -func (c *DatabaseAdminClient) UpdateDatabaseDdlOperation(name string) *UpdateDatabaseDdlOperation { +func (c *databaseAdminGRPCClient) UpdateDatabaseDdlOperation(name string) *UpdateDatabaseDdlOperation { return &UpdateDatabaseDdlOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/spanner/admin/database/apiv1/database_admin_client_example_test.go b/spanner/admin/database/apiv1/database_admin_client_example_test.go index d35fdc6b7043..e17ad14f4559 100644 --- a/spanner/admin/database/apiv1/database_admin_client_example_test.go +++ b/spanner/admin/database/apiv1/database_admin_client_example_test.go @@ -31,19 +31,19 @@ func ExampleNewDatabaseAdminClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleDatabaseAdminClient_ListDatabases() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.ListDatabasesRequest{ // TODO: Fill request struct fields. @@ -63,13 +63,12 @@ func ExampleDatabaseAdminClient_ListDatabases() { } func ExampleDatabaseAdminClient_CreateDatabase() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.CreateDatabaseRequest{ // TODO: Fill request struct fields. @@ -88,13 +87,12 @@ func ExampleDatabaseAdminClient_CreateDatabase() { } func ExampleDatabaseAdminClient_GetDatabase() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.GetDatabaseRequest{ // TODO: Fill request struct fields. @@ -108,13 +106,12 @@ func ExampleDatabaseAdminClient_GetDatabase() { } func ExampleDatabaseAdminClient_UpdateDatabaseDdl() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.UpdateDatabaseDdlRequest{ // TODO: Fill request struct fields. @@ -136,6 +133,7 @@ func ExampleDatabaseAdminClient_DropDatabase() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.DropDatabaseRequest{ // TODO: Fill request struct fields. @@ -147,13 +145,12 @@ func ExampleDatabaseAdminClient_DropDatabase() { } func ExampleDatabaseAdminClient_GetDatabaseDdl() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.GetDatabaseDdlRequest{ // TODO: Fill request struct fields. @@ -167,13 +164,12 @@ func ExampleDatabaseAdminClient_GetDatabaseDdl() { } func ExampleDatabaseAdminClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -187,13 +183,12 @@ func ExampleDatabaseAdminClient_SetIamPolicy() { } func ExampleDatabaseAdminClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -207,13 +202,12 @@ func ExampleDatabaseAdminClient_GetIamPolicy() { } func ExampleDatabaseAdminClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. @@ -227,13 +221,12 @@ func ExampleDatabaseAdminClient_TestIamPermissions() { } func ExampleDatabaseAdminClient_CreateBackup() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.CreateBackupRequest{ // TODO: Fill request struct fields. @@ -252,13 +245,12 @@ func ExampleDatabaseAdminClient_CreateBackup() { } func ExampleDatabaseAdminClient_GetBackup() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.GetBackupRequest{ // TODO: Fill request struct fields. @@ -272,13 +264,12 @@ func ExampleDatabaseAdminClient_GetBackup() { } func ExampleDatabaseAdminClient_UpdateBackup() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.UpdateBackupRequest{ // TODO: Fill request struct fields. @@ -297,6 +288,7 @@ func ExampleDatabaseAdminClient_DeleteBackup() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.DeleteBackupRequest{ // TODO: Fill request struct fields. @@ -308,14 +300,12 @@ func ExampleDatabaseAdminClient_DeleteBackup() { } func ExampleDatabaseAdminClient_ListBackups() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.ListBackupsRequest{ // TODO: Fill request struct fields. @@ -335,13 +325,12 @@ func ExampleDatabaseAdminClient_ListBackups() { } func ExampleDatabaseAdminClient_RestoreDatabase() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.RestoreDatabaseRequest{ // TODO: Fill request struct fields. @@ -360,14 +349,12 @@ func ExampleDatabaseAdminClient_RestoreDatabase() { } func ExampleDatabaseAdminClient_ListDatabaseOperations() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.ListDatabaseOperationsRequest{ // TODO: Fill request struct fields. @@ -387,14 +374,12 @@ func ExampleDatabaseAdminClient_ListDatabaseOperations() { } func ExampleDatabaseAdminClient_ListBackupOperations() { - // import databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &databasepb.ListBackupOperationsRequest{ // TODO: Fill request struct fields. diff --git a/spanner/admin/database/apiv1/doc.go b/spanner/admin/database/apiv1/doc.go index 9a596fc928d1..3eb58b524bc8 100644 --- a/spanner/admin/database/apiv1/doc.go +++ b/spanner/admin/database/apiv1/doc.go @@ -26,7 +26,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package database // import "cloud.google.com/go/spanner/admin/database/apiv1" import ( @@ -46,7 +46,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/spanner/admin/instance/apiv1/doc.go b/spanner/admin/instance/apiv1/doc.go index 9944b6f0c025..f951c52e5f5a 100644 --- a/spanner/admin/instance/apiv1/doc.go +++ b/spanner/admin/instance/apiv1/doc.go @@ -26,7 +26,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package instance // import "cloud.google.com/go/spanner/admin/instance/apiv1" import ( @@ -46,7 +46,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/spanner/admin/instance/apiv1/instance_admin_client.go b/spanner/admin/instance/apiv1/instance_admin_client.go index 85e40a7d0db3..bc777b32745d 100644 --- a/spanner/admin/instance/apiv1/instance_admin_client.go +++ b/spanner/admin/instance/apiv1/instance_admin_client.go @@ -55,7 +55,7 @@ type InstanceAdminCallOptions struct { TestIamPermissions []gax.CallOption } -func defaultInstanceAdminClientOptions() []option.ClientOption { +func defaultInstanceAdminGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("spanner.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("spanner.mtls.googleapis.com:443"), @@ -148,32 +148,277 @@ func defaultInstanceAdminCallOptions() *InstanceAdminCallOptions { } } +// internalInstanceAdminClient is an interface that defines the methods availaible from Cloud Spanner Instance Admin API. +type internalInstanceAdminClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListInstanceConfigs(context.Context, *instancepb.ListInstanceConfigsRequest, ...gax.CallOption) *InstanceConfigIterator + GetInstanceConfig(context.Context, *instancepb.GetInstanceConfigRequest, ...gax.CallOption) (*instancepb.InstanceConfig, error) + ListInstances(context.Context, *instancepb.ListInstancesRequest, ...gax.CallOption) *InstanceIterator + GetInstance(context.Context, *instancepb.GetInstanceRequest, ...gax.CallOption) (*instancepb.Instance, error) + CreateInstance(context.Context, *instancepb.CreateInstanceRequest, ...gax.CallOption) (*CreateInstanceOperation, error) + CreateInstanceOperation(name string) *CreateInstanceOperation + UpdateInstance(context.Context, *instancepb.UpdateInstanceRequest, ...gax.CallOption) (*UpdateInstanceOperation, error) + UpdateInstanceOperation(name string) *UpdateInstanceOperation + DeleteInstance(context.Context, *instancepb.DeleteInstanceRequest, ...gax.CallOption) error + SetIamPolicy(context.Context, *iampb.SetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + GetIamPolicy(context.Context, *iampb.GetIamPolicyRequest, ...gax.CallOption) (*iampb.Policy, error) + TestIamPermissions(context.Context, *iampb.TestIamPermissionsRequest, ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) +} + // InstanceAdminClient is a client for interacting with Cloud Spanner Instance Admin API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Cloud Spanner Instance Admin API +// +// The Cloud Spanner Instance Admin API can be used to create, delete, +// modify and list instances. Instances are dedicated Cloud Spanner serving +// and storage resources to be used by Cloud Spanner databases. +// +// Each instance has a “configuration”, which dictates where the +// serving resources for the Cloud Spanner instance are located (e.g., +// US-central, Europe). Configurations are created by Google based on +// resource availability. +// +// Cloud Spanner billing is based on the instances that exist and their +// sizes. After an instance exists, there are no additional +// per-database or per-operation charges for use of the instance +// (though there may be additional network bandwidth charges). +// Instances offer isolation: problems with databases in one instance +// will not affect other instances. However, within an instance +// databases can affect each other. For example, if one database in an +// instance receives a lot of requests and consumes most of the +// instance resources, fewer resources are available for other +// databases in that instance, and their performance may suffer. type InstanceAdminClient struct { + // The internal transport-dependent client. + internalClient internalInstanceAdminClient + + // The call options for this service. + CallOptions *InstanceAdminCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *InstanceAdminClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *InstanceAdminClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *InstanceAdminClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListInstanceConfigs lists the supported instance configurations for a given project. +func (c *InstanceAdminClient) ListInstanceConfigs(ctx context.Context, req *instancepb.ListInstanceConfigsRequest, opts ...gax.CallOption) *InstanceConfigIterator { + return c.internalClient.ListInstanceConfigs(ctx, req, opts...) +} + +// GetInstanceConfig gets information about a particular instance configuration. +func (c *InstanceAdminClient) GetInstanceConfig(ctx context.Context, req *instancepb.GetInstanceConfigRequest, opts ...gax.CallOption) (*instancepb.InstanceConfig, error) { + return c.internalClient.GetInstanceConfig(ctx, req, opts...) +} + +// ListInstances lists all instances in the given project. +func (c *InstanceAdminClient) ListInstances(ctx context.Context, req *instancepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { + return c.internalClient.ListInstances(ctx, req, opts...) +} + +// GetInstance gets information about a particular instance. +func (c *InstanceAdminClient) GetInstance(ctx context.Context, req *instancepb.GetInstanceRequest, opts ...gax.CallOption) (*instancepb.Instance, error) { + return c.internalClient.GetInstance(ctx, req, opts...) +} + +// CreateInstance creates an instance and begins preparing it to begin serving. The +// returned [long-running operation][google.longrunning.Operation] +// can be used to track the progress of preparing the new +// instance. The instance name is assigned by the caller. If the +// named instance already exists, CreateInstance returns +// ALREADY_EXISTS. +// +// Immediately upon completion of this request: +// +// The instance is readable via the API, with all requested attributes +// but no allocated resources. Its state is CREATING. +// +// Until completion of the returned operation: +// +// Cancelling the operation renders the instance immediately unreadable +// via the API. +// +// The instance can be deleted. +// +// All other attempts to modify the instance are rejected. +// +// Upon completion of the returned operation: +// +// Billing for all successfully-allocated resources begins (some types +// may have lower than the requested levels). +// +// Databases can be created in the instance. +// +// The instance’s allocated resource levels are readable via the API. +// +// The instance’s state becomes READY. +// +// The returned [long-running operation][google.longrunning.Operation] will +// have a name of the format /operations/ and +// can be used to track creation of the instance. The +// metadata field type is +// CreateInstanceMetadata. +// The response field type is +// Instance, if successful. +func (c *InstanceAdminClient) CreateInstance(ctx context.Context, req *instancepb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { + return c.internalClient.CreateInstance(ctx, req, opts...) +} + +// CreateInstanceOperation returns a new CreateInstanceOperation from a given name. +// The name must be that of a previously created CreateInstanceOperation, possibly from a different process. +func (c *InstanceAdminClient) CreateInstanceOperation(name string) *CreateInstanceOperation { + return c.internalClient.CreateInstanceOperation(name) +} + +// UpdateInstance updates an instance, and begins allocating or releasing resources +// as requested. The returned [long-running +// operation][google.longrunning.Operation] can be used to track the +// progress of updating the instance. If the named instance does not +// exist, returns NOT_FOUND. +// +// Immediately upon completion of this request: +// +// For resource types for which a decrease in the instance’s allocation +// has been requested, billing is based on the newly-requested level. +// +// Until completion of the returned operation: +// +// Cancelling the operation sets its metadata’s +// cancel_time, and begins +// restoring resources to their pre-request values. The operation +// is guaranteed to succeed at undoing all resource changes, +// after which point it terminates with a CANCELLED status. +// +// All other attempts to modify the instance are rejected. +// +// Reading the instance via the API continues to give the pre-request +// resource levels. +// +// Upon completion of the returned operation: +// +// Billing begins for all successfully-allocated resources (some types +// may have lower than the requested levels). +// +// All newly-reserved resources are available for serving the instance’s +// tables. +// +// The instance’s new resource levels are readable via the API. +// +// The returned [long-running operation][google.longrunning.Operation] will +// have a name of the format /operations/ and +// can be used to track the instance modification. The +// metadata field type is +// UpdateInstanceMetadata. +// The response field type is +// Instance, if successful. +// +// Authorization requires spanner.instances.update permission on +// resource [name][google.spanner.admin.instance.v1.Instance.name (at http://google.spanner.admin.instance.v1.Instance.name)]. +func (c *InstanceAdminClient) UpdateInstance(ctx context.Context, req *instancepb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { + return c.internalClient.UpdateInstance(ctx, req, opts...) +} + +// UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. +// The name must be that of a previously created UpdateInstanceOperation, possibly from a different process. +func (c *InstanceAdminClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { + return c.internalClient.UpdateInstanceOperation(name) +} + +// DeleteInstance deletes an instance. +// +// Immediately upon completion of the request: +// +// Billing ceases for all of the instance’s reserved resources. +// +// Soon afterward: +// +// The instance and all of its databases immediately and +// irrevocably disappear from the API. All data in the databases +// is permanently deleted. +func (c *InstanceAdminClient) DeleteInstance(ctx context.Context, req *instancepb.DeleteInstanceRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteInstance(ctx, req, opts...) +} + +// SetIamPolicy sets the access control policy on an instance resource. Replaces any +// existing policy. +// +// Authorization requires spanner.instances.setIamPolicy on +// resource. +func (c *InstanceAdminClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.SetIamPolicy(ctx, req, opts...) +} + +// GetIamPolicy gets the access control policy for an instance resource. Returns an empty +// policy if an instance exists but does not have a policy set. +// +// Authorization requires spanner.instances.getIamPolicy on +// resource. +func (c *InstanceAdminClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { + return c.internalClient.GetIamPolicy(ctx, req, opts...) +} + +// TestIamPermissions returns permissions that the caller has on the specified instance resource. +// +// Attempting this RPC on a non-existent Cloud Spanner instance resource will +// result in a NOT_FOUND error if the user has spanner.instances.list +// permission on the containing Google Cloud Project. Otherwise returns an +// empty set of permissions. +func (c *InstanceAdminClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { + return c.internalClient.TestIamPermissions(ctx, req, opts...) +} + +// instanceAdminGRPCClient is a client for interacting with Cloud Spanner Instance Admin API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type instanceAdminGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing InstanceAdminClient + CallOptions **InstanceAdminCallOptions + // The gRPC API client. instanceAdminClient instancepb.InstanceAdminClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *InstanceAdminCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewInstanceAdminClient creates a new instance admin client. +// NewInstanceAdminClient creates a new instance admin client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Cloud Spanner Instance Admin API // @@ -197,8 +442,7 @@ type InstanceAdminClient struct { // instance resources, fewer resources are available for other // databases in that instance, and their performance may suffer. func NewInstanceAdminClient(ctx context.Context, opts ...option.ClientOption) (*InstanceAdminClient, error) { - clientOpts := defaultInstanceAdminClientOptions() - + clientOpts := defaultInstanceAdminGRPCClientOptions() if newInstanceAdminClientHook != nil { hookOpts, err := newInstanceAdminClientHook(ctx, clientHookParams{}) if err != nil { @@ -216,16 +460,19 @@ func NewInstanceAdminClient(ctx context.Context, opts ...option.ClientOption) (* if err != nil { return nil, err } - c := &InstanceAdminClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultInstanceAdminCallOptions(), + client := InstanceAdminClient{CallOptions: defaultInstanceAdminCallOptions()} + c := &instanceAdminGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, instanceAdminClient: instancepb.NewInstanceAdminClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -235,36 +482,36 @@ func NewInstanceAdminClient(ctx context.Context, opts ...option.ClientOption) (* // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *InstanceAdminClient) Connection() *grpc.ClientConn { +func (c *instanceAdminGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *InstanceAdminClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *InstanceAdminClient) setGoogleClientInfo(keyval ...string) { +func (c *instanceAdminGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListInstanceConfigs lists the supported instance configurations for a given project. -func (c *InstanceAdminClient) ListInstanceConfigs(ctx context.Context, req *instancepb.ListInstanceConfigsRequest, opts ...gax.CallOption) *InstanceConfigIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *instanceAdminGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *instanceAdminGRPCClient) ListInstanceConfigs(ctx context.Context, req *instancepb.ListInstanceConfigsRequest, opts ...gax.CallOption) *InstanceConfigIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListInstanceConfigs[0:len(c.CallOptions.ListInstanceConfigs):len(c.CallOptions.ListInstanceConfigs)], opts...) + opts = append((*c.CallOptions).ListInstanceConfigs[0:len((*c.CallOptions).ListInstanceConfigs):len((*c.CallOptions).ListInstanceConfigs)], opts...) it := &InstanceConfigIterator{} req = proto.Clone(req).(*instancepb.ListInstanceConfigsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*instancepb.InstanceConfig, string, error) { @@ -301,8 +548,7 @@ func (c *InstanceAdminClient) ListInstanceConfigs(ctx context.Context, req *inst return it } -// GetInstanceConfig gets information about a particular instance configuration. -func (c *InstanceAdminClient) GetInstanceConfig(ctx context.Context, req *instancepb.GetInstanceConfigRequest, opts ...gax.CallOption) (*instancepb.InstanceConfig, error) { +func (c *instanceAdminGRPCClient) GetInstanceConfig(ctx context.Context, req *instancepb.GetInstanceConfigRequest, opts ...gax.CallOption) (*instancepb.InstanceConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 3600000*time.Millisecond) defer cancel() @@ -310,7 +556,7 @@ func (c *InstanceAdminClient) GetInstanceConfig(ctx context.Context, req *instan } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetInstanceConfig[0:len(c.CallOptions.GetInstanceConfig):len(c.CallOptions.GetInstanceConfig)], opts...) + opts = append((*c.CallOptions).GetInstanceConfig[0:len((*c.CallOptions).GetInstanceConfig):len((*c.CallOptions).GetInstanceConfig)], opts...) var resp *instancepb.InstanceConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -323,11 +569,10 @@ func (c *InstanceAdminClient) GetInstanceConfig(ctx context.Context, req *instan return resp, nil } -// ListInstances lists all instances in the given project. -func (c *InstanceAdminClient) ListInstances(ctx context.Context, req *instancepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { +func (c *instanceAdminGRPCClient) ListInstances(ctx context.Context, req *instancepb.ListInstancesRequest, opts ...gax.CallOption) *InstanceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListInstances[0:len(c.CallOptions.ListInstances):len(c.CallOptions.ListInstances)], opts...) + opts = append((*c.CallOptions).ListInstances[0:len((*c.CallOptions).ListInstances):len((*c.CallOptions).ListInstances)], opts...) it := &InstanceIterator{} req = proto.Clone(req).(*instancepb.ListInstancesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*instancepb.Instance, string, error) { @@ -364,8 +609,7 @@ func (c *InstanceAdminClient) ListInstances(ctx context.Context, req *instancepb return it } -// GetInstance gets information about a particular instance. -func (c *InstanceAdminClient) GetInstance(ctx context.Context, req *instancepb.GetInstanceRequest, opts ...gax.CallOption) (*instancepb.Instance, error) { +func (c *instanceAdminGRPCClient) GetInstance(ctx context.Context, req *instancepb.GetInstanceRequest, opts ...gax.CallOption) (*instancepb.Instance, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 3600000*time.Millisecond) defer cancel() @@ -373,7 +617,7 @@ func (c *InstanceAdminClient) GetInstance(ctx context.Context, req *instancepb.G } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetInstance[0:len(c.CallOptions.GetInstance):len(c.CallOptions.GetInstance)], opts...) + opts = append((*c.CallOptions).GetInstance[0:len((*c.CallOptions).GetInstance):len((*c.CallOptions).GetInstance)], opts...) var resp *instancepb.Instance err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -386,46 +630,7 @@ func (c *InstanceAdminClient) GetInstance(ctx context.Context, req *instancepb.G return resp, nil } -// CreateInstance creates an instance and begins preparing it to begin serving. The -// returned [long-running operation][google.longrunning.Operation] -// can be used to track the progress of preparing the new -// instance. The instance name is assigned by the caller. If the -// named instance already exists, CreateInstance returns -// ALREADY_EXISTS. -// -// Immediately upon completion of this request: -// -// The instance is readable via the API, with all requested attributes -// but no allocated resources. Its state is CREATING. -// -// Until completion of the returned operation: -// -// Cancelling the operation renders the instance immediately unreadable -// via the API. -// -// The instance can be deleted. -// -// All other attempts to modify the instance are rejected. -// -// Upon completion of the returned operation: -// -// Billing for all successfully-allocated resources begins (some types -// may have lower than the requested levels). -// -// Databases can be created in the instance. -// -// The instance’s allocated resource levels are readable via the API. -// -// The instance’s state becomes READY. -// -// The returned [long-running operation][google.longrunning.Operation] will -// have a name of the format /operations/ and -// can be used to track creation of the instance. The -// metadata field type is -// CreateInstanceMetadata. -// The response field type is -// Instance, if successful. -func (c *InstanceAdminClient) CreateInstance(ctx context.Context, req *instancepb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { +func (c *instanceAdminGRPCClient) CreateInstance(ctx context.Context, req *instancepb.CreateInstanceRequest, opts ...gax.CallOption) (*CreateInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 3600000*time.Millisecond) defer cancel() @@ -433,7 +638,7 @@ func (c *InstanceAdminClient) CreateInstance(ctx context.Context, req *instancep } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateInstance[0:len(c.CallOptions.CreateInstance):len(c.CallOptions.CreateInstance)], opts...) + opts = append((*c.CallOptions).CreateInstance[0:len((*c.CallOptions).CreateInstance):len((*c.CallOptions).CreateInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -444,55 +649,11 @@ func (c *InstanceAdminClient) CreateInstance(ctx context.Context, req *instancep return nil, err } return &CreateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateInstance updates an instance, and begins allocating or releasing resources -// as requested. The returned [long-running -// operation][google.longrunning.Operation] can be used to track the -// progress of updating the instance. If the named instance does not -// exist, returns NOT_FOUND. -// -// Immediately upon completion of this request: -// -// For resource types for which a decrease in the instance’s allocation -// has been requested, billing is based on the newly-requested level. -// -// Until completion of the returned operation: -// -// Cancelling the operation sets its metadata’s -// cancel_time, and begins -// restoring resources to their pre-request values. The operation -// is guaranteed to succeed at undoing all resource changes, -// after which point it terminates with a CANCELLED status. -// -// All other attempts to modify the instance are rejected. -// -// Reading the instance via the API continues to give the pre-request -// resource levels. -// -// Upon completion of the returned operation: -// -// Billing begins for all successfully-allocated resources (some types -// may have lower than the requested levels). -// -// All newly-reserved resources are available for serving the instance’s -// tables. -// -// The instance’s new resource levels are readable via the API. -// -// The returned [long-running operation][google.longrunning.Operation] will -// have a name of the format /operations/ and -// can be used to track the instance modification. The -// metadata field type is -// UpdateInstanceMetadata. -// The response field type is -// Instance, if successful. -// -// Authorization requires spanner.instances.update permission on -// resource [name][google.spanner.admin.instance.v1.Instance.name (at http://google.spanner.admin.instance.v1.Instance.name)]. -func (c *InstanceAdminClient) UpdateInstance(ctx context.Context, req *instancepb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { +func (c *instanceAdminGRPCClient) UpdateInstance(ctx context.Context, req *instancepb.UpdateInstanceRequest, opts ...gax.CallOption) (*UpdateInstanceOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 3600000*time.Millisecond) defer cancel() @@ -500,7 +661,7 @@ func (c *InstanceAdminClient) UpdateInstance(ctx context.Context, req *instancep } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "instance.name", url.QueryEscape(req.GetInstance().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateInstance[0:len(c.CallOptions.UpdateInstance):len(c.CallOptions.UpdateInstance)], opts...) + opts = append((*c.CallOptions).UpdateInstance[0:len((*c.CallOptions).UpdateInstance):len((*c.CallOptions).UpdateInstance)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -511,22 +672,11 @@ func (c *InstanceAdminClient) UpdateInstance(ctx context.Context, req *instancep return nil, err } return &UpdateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteInstance deletes an instance. -// -// Immediately upon completion of the request: -// -// Billing ceases for all of the instance’s reserved resources. -// -// Soon afterward: -// -// The instance and all of its databases immediately and -// irrevocably disappear from the API. All data in the databases -// is permanently deleted. -func (c *InstanceAdminClient) DeleteInstance(ctx context.Context, req *instancepb.DeleteInstanceRequest, opts ...gax.CallOption) error { +func (c *instanceAdminGRPCClient) DeleteInstance(ctx context.Context, req *instancepb.DeleteInstanceRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 3600000*time.Millisecond) defer cancel() @@ -534,7 +684,7 @@ func (c *InstanceAdminClient) DeleteInstance(ctx context.Context, req *instancep } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteInstance[0:len(c.CallOptions.DeleteInstance):len(c.CallOptions.DeleteInstance)], opts...) + opts = append((*c.CallOptions).DeleteInstance[0:len((*c.CallOptions).DeleteInstance):len((*c.CallOptions).DeleteInstance)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.instanceAdminClient.DeleteInstance(ctx, req, settings.GRPC...) @@ -543,12 +693,7 @@ func (c *InstanceAdminClient) DeleteInstance(ctx context.Context, req *instancep return err } -// SetIamPolicy sets the access control policy on an instance resource. Replaces any -// existing policy. -// -// Authorization requires spanner.instances.setIamPolicy on -// resource. -func (c *InstanceAdminClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *instanceAdminGRPCClient) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -556,7 +701,7 @@ func (c *InstanceAdminClient) SetIamPolicy(ctx context.Context, req *iampb.SetIa } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) + opts = append((*c.CallOptions).SetIamPolicy[0:len((*c.CallOptions).SetIamPolicy):len((*c.CallOptions).SetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -569,12 +714,7 @@ func (c *InstanceAdminClient) SetIamPolicy(ctx context.Context, req *iampb.SetIa return resp, nil } -// GetIamPolicy gets the access control policy for an instance resource. Returns an empty -// policy if an instance exists but does not have a policy set. -// -// Authorization requires spanner.instances.getIamPolicy on -// resource. -func (c *InstanceAdminClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { +func (c *instanceAdminGRPCClient) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -582,7 +722,7 @@ func (c *InstanceAdminClient) GetIamPolicy(ctx context.Context, req *iampb.GetIa } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) + opts = append((*c.CallOptions).GetIamPolicy[0:len((*c.CallOptions).GetIamPolicy):len((*c.CallOptions).GetIamPolicy)], opts...) var resp *iampb.Policy err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -595,13 +735,7 @@ func (c *InstanceAdminClient) GetIamPolicy(ctx context.Context, req *iampb.GetIa return resp, nil } -// TestIamPermissions returns permissions that the caller has on the specified instance resource. -// -// Attempting this RPC on a non-existent Cloud Spanner instance resource will -// result in a NOT_FOUND error if the user has spanner.instances.list -// permission on the containing Google Cloud Project. Otherwise returns an -// empty set of permissions. -func (c *InstanceAdminClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { +func (c *instanceAdminGRPCClient) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -609,7 +743,7 @@ func (c *InstanceAdminClient) TestIamPermissions(ctx context.Context, req *iampb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) + opts = append((*c.CallOptions).TestIamPermissions[0:len((*c.CallOptions).TestIamPermissions):len((*c.CallOptions).TestIamPermissions)], opts...) var resp *iampb.TestIamPermissionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -629,9 +763,9 @@ type CreateInstanceOperation struct { // CreateInstanceOperation returns a new CreateInstanceOperation from a given name. // The name must be that of a previously created CreateInstanceOperation, possibly from a different process. -func (c *InstanceAdminClient) CreateInstanceOperation(name string) *CreateInstanceOperation { +func (c *instanceAdminGRPCClient) CreateInstanceOperation(name string) *CreateInstanceOperation { return &CreateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -698,9 +832,9 @@ type UpdateInstanceOperation struct { // UpdateInstanceOperation returns a new UpdateInstanceOperation from a given name. // The name must be that of a previously created UpdateInstanceOperation, possibly from a different process. -func (c *InstanceAdminClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { +func (c *instanceAdminGRPCClient) UpdateInstanceOperation(name string) *UpdateInstanceOperation { return &UpdateInstanceOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/spanner/admin/instance/apiv1/instance_admin_client_example_test.go b/spanner/admin/instance/apiv1/instance_admin_client_example_test.go index 9de0f98c601d..cb8f230f9bcc 100644 --- a/spanner/admin/instance/apiv1/instance_admin_client_example_test.go +++ b/spanner/admin/instance/apiv1/instance_admin_client_example_test.go @@ -31,19 +31,19 @@ func ExampleNewInstanceAdminClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleInstanceAdminClient_ListInstanceConfigs() { - // import instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &instancepb.ListInstanceConfigsRequest{ // TODO: Fill request struct fields. @@ -63,13 +63,12 @@ func ExampleInstanceAdminClient_ListInstanceConfigs() { } func ExampleInstanceAdminClient_GetInstanceConfig() { - // import instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &instancepb.GetInstanceConfigRequest{ // TODO: Fill request struct fields. @@ -83,14 +82,12 @@ func ExampleInstanceAdminClient_GetInstanceConfig() { } func ExampleInstanceAdminClient_ListInstances() { - // import instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &instancepb.ListInstancesRequest{ // TODO: Fill request struct fields. @@ -110,13 +107,12 @@ func ExampleInstanceAdminClient_ListInstances() { } func ExampleInstanceAdminClient_GetInstance() { - // import instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &instancepb.GetInstanceRequest{ // TODO: Fill request struct fields. @@ -130,13 +126,12 @@ func ExampleInstanceAdminClient_GetInstance() { } func ExampleInstanceAdminClient_CreateInstance() { - // import instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &instancepb.CreateInstanceRequest{ // TODO: Fill request struct fields. @@ -155,13 +150,12 @@ func ExampleInstanceAdminClient_CreateInstance() { } func ExampleInstanceAdminClient_UpdateInstance() { - // import instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &instancepb.UpdateInstanceRequest{ // TODO: Fill request struct fields. @@ -185,6 +179,7 @@ func ExampleInstanceAdminClient_DeleteInstance() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &instancepb.DeleteInstanceRequest{ // TODO: Fill request struct fields. @@ -196,13 +191,12 @@ func ExampleInstanceAdminClient_DeleteInstance() { } func ExampleInstanceAdminClient_SetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.SetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -216,13 +210,12 @@ func ExampleInstanceAdminClient_SetIamPolicy() { } func ExampleInstanceAdminClient_GetIamPolicy() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.GetIamPolicyRequest{ // TODO: Fill request struct fields. @@ -236,13 +229,12 @@ func ExampleInstanceAdminClient_GetIamPolicy() { } func ExampleInstanceAdminClient_TestIamPermissions() { - // import iampb "google.golang.org/genproto/googleapis/iam/v1" - ctx := context.Background() c, err := instance.NewInstanceAdminClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &iampb.TestIamPermissionsRequest{ // TODO: Fill request struct fields. diff --git a/spanner/apiv1/doc.go b/spanner/apiv1/doc.go index a70c6dbad315..e34b3d2b1f3e 100644 --- a/spanner/apiv1/doc.go +++ b/spanner/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package spanner // import "cloud.google.com/go/spanner/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/spanner/apiv1/spanner_client.go b/spanner/apiv1/spanner_client.go index 12646832968f..577ccbf19098 100644 --- a/spanner/apiv1/spanner_client.go +++ b/spanner/apiv1/spanner_client.go @@ -56,7 +56,7 @@ type CallOptions struct { PartitionRead []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("spanner.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("spanner.mtls.googleapis.com:443"), @@ -218,35 +218,279 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Spanner API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateSession(context.Context, *spannerpb.CreateSessionRequest, ...gax.CallOption) (*spannerpb.Session, error) + BatchCreateSessions(context.Context, *spannerpb.BatchCreateSessionsRequest, ...gax.CallOption) (*spannerpb.BatchCreateSessionsResponse, error) + GetSession(context.Context, *spannerpb.GetSessionRequest, ...gax.CallOption) (*spannerpb.Session, error) + ListSessions(context.Context, *spannerpb.ListSessionsRequest, ...gax.CallOption) *SessionIterator + DeleteSession(context.Context, *spannerpb.DeleteSessionRequest, ...gax.CallOption) error + ExecuteSql(context.Context, *spannerpb.ExecuteSqlRequest, ...gax.CallOption) (*spannerpb.ResultSet, error) + ExecuteStreamingSql(context.Context, *spannerpb.ExecuteSqlRequest, ...gax.CallOption) (spannerpb.Spanner_ExecuteStreamingSqlClient, error) + ExecuteBatchDml(context.Context, *spannerpb.ExecuteBatchDmlRequest, ...gax.CallOption) (*spannerpb.ExecuteBatchDmlResponse, error) + Read(context.Context, *spannerpb.ReadRequest, ...gax.CallOption) (*spannerpb.ResultSet, error) + StreamingRead(context.Context, *spannerpb.ReadRequest, ...gax.CallOption) (spannerpb.Spanner_StreamingReadClient, error) + BeginTransaction(context.Context, *spannerpb.BeginTransactionRequest, ...gax.CallOption) (*spannerpb.Transaction, error) + Commit(context.Context, *spannerpb.CommitRequest, ...gax.CallOption) (*spannerpb.CommitResponse, error) + Rollback(context.Context, *spannerpb.RollbackRequest, ...gax.CallOption) error + PartitionQuery(context.Context, *spannerpb.PartitionQueryRequest, ...gax.CallOption) (*spannerpb.PartitionResponse, error) + PartitionRead(context.Context, *spannerpb.PartitionReadRequest, ...gax.CallOption) (*spannerpb.PartitionResponse, error) +} + // Client is a client for interacting with Cloud Spanner API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Cloud Spanner API +// +// The Cloud Spanner API can be used to manage sessions and execute +// transactions on data stored in Cloud Spanner databases. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateSession creates a new session. A session can be used to perform +// transactions that read and/or modify data in a Cloud Spanner database. +// Sessions are meant to be reused for many consecutive +// transactions. +// +// Sessions can only execute one transaction at a time. To execute +// multiple concurrent read-write/write-only transactions, create +// multiple sessions. Note that standalone reads and queries use a +// transaction internally, and count toward the one transaction +// limit. +// +// Active sessions use additional server resources, so it is a good idea to +// delete idle and unneeded sessions. +// Aside from explicit deletes, Cloud Spanner may delete sessions for which no +// operations are sent for more than an hour. If a session is deleted, +// requests to it return NOT_FOUND. +// +// Idle sessions can be kept alive by sending a trivial SQL query +// periodically, e.g., "SELECT 1". +func (c *Client) CreateSession(ctx context.Context, req *spannerpb.CreateSessionRequest, opts ...gax.CallOption) (*spannerpb.Session, error) { + return c.internalClient.CreateSession(ctx, req, opts...) +} + +// BatchCreateSessions creates multiple new sessions. +// +// This API can be used to initialize a session cache on the clients. +// See https://goo.gl/TgSFN2 (at https://goo.gl/TgSFN2) for best practices on session cache management. +func (c *Client) BatchCreateSessions(ctx context.Context, req *spannerpb.BatchCreateSessionsRequest, opts ...gax.CallOption) (*spannerpb.BatchCreateSessionsResponse, error) { + return c.internalClient.BatchCreateSessions(ctx, req, opts...) +} + +// GetSession gets a session. Returns NOT_FOUND if the session does not exist. +// This is mainly useful for determining whether a session is still +// alive. +func (c *Client) GetSession(ctx context.Context, req *spannerpb.GetSessionRequest, opts ...gax.CallOption) (*spannerpb.Session, error) { + return c.internalClient.GetSession(ctx, req, opts...) +} + +// ListSessions lists all sessions in a given database. +func (c *Client) ListSessions(ctx context.Context, req *spannerpb.ListSessionsRequest, opts ...gax.CallOption) *SessionIterator { + return c.internalClient.ListSessions(ctx, req, opts...) +} + +// DeleteSession ends a session, releasing server resources associated with it. This will +// asynchronously trigger cancellation of any operations that are running with +// this session. +func (c *Client) DeleteSession(ctx context.Context, req *spannerpb.DeleteSessionRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteSession(ctx, req, opts...) +} + +// ExecuteSql executes an SQL statement, returning all results in a single reply. This +// method cannot be used to return a result set larger than 10 MiB; +// if the query yields more data than that, the query fails with +// a FAILED_PRECONDITION error. +// +// Operations inside read-write transactions might return ABORTED. If +// this occurs, the application should restart the transaction from +// the beginning. See Transaction for more details. +// +// Larger result sets can be fetched in streaming fashion by calling +// ExecuteStreamingSql instead. +func (c *Client) ExecuteSql(ctx context.Context, req *spannerpb.ExecuteSqlRequest, opts ...gax.CallOption) (*spannerpb.ResultSet, error) { + return c.internalClient.ExecuteSql(ctx, req, opts...) +} + +// ExecuteStreamingSql like ExecuteSql, except returns the result +// set as a stream. Unlike ExecuteSql, there +// is no limit on the size of the returned result set. However, no +// individual row in the result set can exceed 100 MiB, and no +// column value can exceed 10 MiB. +func (c *Client) ExecuteStreamingSql(ctx context.Context, req *spannerpb.ExecuteSqlRequest, opts ...gax.CallOption) (spannerpb.Spanner_ExecuteStreamingSqlClient, error) { + return c.internalClient.ExecuteStreamingSql(ctx, req, opts...) +} + +// ExecuteBatchDml executes a batch of SQL DML statements. This method allows many statements +// to be run with lower latency than submitting them sequentially with +// ExecuteSql. +// +// Statements are executed in sequential order. A request can succeed even if +// a statement fails. The ExecuteBatchDmlResponse.status field in the +// response provides information about the statement that failed. Clients must +// inspect this field to determine whether an error occurred. +// +// Execution stops after the first failed statement; the remaining statements +// are not executed. +func (c *Client) ExecuteBatchDml(ctx context.Context, req *spannerpb.ExecuteBatchDmlRequest, opts ...gax.CallOption) (*spannerpb.ExecuteBatchDmlResponse, error) { + return c.internalClient.ExecuteBatchDml(ctx, req, opts...) +} + +// Read reads rows from the database using key lookups and scans, as a +// simple key/value style alternative to +// ExecuteSql. This method cannot be used to +// return a result set larger than 10 MiB; if the read matches more +// data than that, the read fails with a FAILED_PRECONDITION +// error. +// +// Reads inside read-write transactions might return ABORTED. If +// this occurs, the application should restart the transaction from +// the beginning. See Transaction for more details. +// +// Larger result sets can be yielded in streaming fashion by calling +// StreamingRead instead. +func (c *Client) Read(ctx context.Context, req *spannerpb.ReadRequest, opts ...gax.CallOption) (*spannerpb.ResultSet, error) { + return c.internalClient.Read(ctx, req, opts...) +} + +// StreamingRead like Read, except returns the result set as a +// stream. Unlike Read, there is no limit on the +// size of the returned result set. However, no individual row in +// the result set can exceed 100 MiB, and no column value can exceed +// 10 MiB. +func (c *Client) StreamingRead(ctx context.Context, req *spannerpb.ReadRequest, opts ...gax.CallOption) (spannerpb.Spanner_StreamingReadClient, error) { + return c.internalClient.StreamingRead(ctx, req, opts...) +} + +// BeginTransaction begins a new transaction. This step can often be skipped: +// Read, ExecuteSql and +// Commit can begin a new transaction as a +// side-effect. +func (c *Client) BeginTransaction(ctx context.Context, req *spannerpb.BeginTransactionRequest, opts ...gax.CallOption) (*spannerpb.Transaction, error) { + return c.internalClient.BeginTransaction(ctx, req, opts...) +} + +// Commit commits a transaction. The request includes the mutations to be +// applied to rows in the database. +// +// Commit might return an ABORTED error. This can occur at any time; +// commonly, the cause is conflicts with concurrent +// transactions. However, it can also happen for a variety of other +// reasons. If Commit returns ABORTED, the caller should re-attempt +// the transaction from the beginning, re-using the same session. +// +// On very rare occasions, Commit might return UNKNOWN. This can happen, +// for example, if the client job experiences a 1+ hour networking failure. +// At that point, Cloud Spanner has lost track of the transaction outcome and +// we recommend that you perform another read from the database to see the +// state of things as they are now. +func (c *Client) Commit(ctx context.Context, req *spannerpb.CommitRequest, opts ...gax.CallOption) (*spannerpb.CommitResponse, error) { + return c.internalClient.Commit(ctx, req, opts...) +} + +// Rollback rolls back a transaction, releasing any locks it holds. It is a good +// idea to call this for any transaction that includes one or more +// Read or ExecuteSql requests and +// ultimately decides not to commit. +// +// Rollback returns OK if it successfully aborts the transaction, the +// transaction was already aborted, or the transaction is not +// found. Rollback never returns ABORTED. +func (c *Client) Rollback(ctx context.Context, req *spannerpb.RollbackRequest, opts ...gax.CallOption) error { + return c.internalClient.Rollback(ctx, req, opts...) +} + +// PartitionQuery creates a set of partition tokens that can be used to execute a query +// operation in parallel. Each of the returned partition tokens can be used +// by ExecuteStreamingSql to specify a subset +// of the query result to read. The same session and read-only transaction +// must be used by the PartitionQueryRequest used to create the +// partition tokens and the ExecuteSqlRequests that use the partition tokens. +// +// Partition tokens become invalid when the session used to create them +// is deleted, is idle for too long, begins a new transaction, or becomes too +// old. When any of these happen, it is not possible to resume the query, and +// the whole operation must be restarted from the beginning. +func (c *Client) PartitionQuery(ctx context.Context, req *spannerpb.PartitionQueryRequest, opts ...gax.CallOption) (*spannerpb.PartitionResponse, error) { + return c.internalClient.PartitionQuery(ctx, req, opts...) +} + +// PartitionRead creates a set of partition tokens that can be used to execute a read +// operation in parallel. Each of the returned partition tokens can be used +// by StreamingRead to specify a subset of the read +// result to read. The same session and read-only transaction must be used by +// the PartitionReadRequest used to create the partition tokens and the +// ReadRequests that use the partition tokens. There are no ordering +// guarantees on rows returned among the returned partition tokens, or even +// within each individual StreamingRead call issued with a partition_token. +// +// Partition tokens become invalid when the session used to create them +// is deleted, is idle for too long, begins a new transaction, or becomes too +// old. When any of these happen, it is not possible to resume the read, and +// the whole operation must be restarted from the beginning. +func (c *Client) PartitionRead(ctx context.Context, req *spannerpb.PartitionReadRequest, opts ...gax.CallOption) (*spannerpb.PartitionResponse, error) { + return c.internalClient.PartitionRead(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud Spanner API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client spannerpb.SpannerClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new spanner client. +// NewClient creates a new spanner client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Cloud Spanner API // // The Cloud Spanner API can be used to manage sessions and execute // transactions on data stored in Cloud Spanner databases. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -264,60 +508,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: spannerpb.NewSpannerClient(connPool), + client: spannerpb.NewSpannerClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateSession creates a new session. A session can be used to perform -// transactions that read and/or modify data in a Cloud Spanner database. -// Sessions are meant to be reused for many consecutive -// transactions. -// -// Sessions can only execute one transaction at a time. To execute -// multiple concurrent read-write/write-only transactions, create -// multiple sessions. Note that standalone reads and queries use a -// transaction internally, and count toward the one transaction -// limit. -// -// Active sessions use additional server resources, so it is a good idea to -// delete idle and unneeded sessions. -// Aside from explicit deletes, Cloud Spanner may delete sessions for which no -// operations are sent for more than an hour. If a session is deleted, -// requests to it return NOT_FOUND. -// -// Idle sessions can be kept alive by sending a trivial SQL query -// periodically, e.g., "SELECT 1". -func (c *Client) CreateSession(ctx context.Context, req *spannerpb.CreateSessionRequest, opts ...gax.CallOption) (*spannerpb.Session, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateSession(ctx context.Context, req *spannerpb.CreateSessionRequest, opts ...gax.CallOption) (*spannerpb.Session, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -325,7 +553,7 @@ func (c *Client) CreateSession(ctx context.Context, req *spannerpb.CreateSession } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSession[0:len(c.CallOptions.CreateSession):len(c.CallOptions.CreateSession)], opts...) + opts = append((*c.CallOptions).CreateSession[0:len((*c.CallOptions).CreateSession):len((*c.CallOptions).CreateSession)], opts...) var resp *spannerpb.Session err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -338,11 +566,7 @@ func (c *Client) CreateSession(ctx context.Context, req *spannerpb.CreateSession return resp, nil } -// BatchCreateSessions creates multiple new sessions. -// -// This API can be used to initialize a session cache on the clients. -// See https://goo.gl/TgSFN2 (at https://goo.gl/TgSFN2) for best practices on session cache management. -func (c *Client) BatchCreateSessions(ctx context.Context, req *spannerpb.BatchCreateSessionsRequest, opts ...gax.CallOption) (*spannerpb.BatchCreateSessionsResponse, error) { +func (c *gRPCClient) BatchCreateSessions(ctx context.Context, req *spannerpb.BatchCreateSessionsRequest, opts ...gax.CallOption) (*spannerpb.BatchCreateSessionsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -350,7 +574,7 @@ func (c *Client) BatchCreateSessions(ctx context.Context, req *spannerpb.BatchCr } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchCreateSessions[0:len(c.CallOptions.BatchCreateSessions):len(c.CallOptions.BatchCreateSessions)], opts...) + opts = append((*c.CallOptions).BatchCreateSessions[0:len((*c.CallOptions).BatchCreateSessions):len((*c.CallOptions).BatchCreateSessions)], opts...) var resp *spannerpb.BatchCreateSessionsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -363,10 +587,7 @@ func (c *Client) BatchCreateSessions(ctx context.Context, req *spannerpb.BatchCr return resp, nil } -// GetSession gets a session. Returns NOT_FOUND if the session does not exist. -// This is mainly useful for determining whether a session is still -// alive. -func (c *Client) GetSession(ctx context.Context, req *spannerpb.GetSessionRequest, opts ...gax.CallOption) (*spannerpb.Session, error) { +func (c *gRPCClient) GetSession(ctx context.Context, req *spannerpb.GetSessionRequest, opts ...gax.CallOption) (*spannerpb.Session, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -374,7 +595,7 @@ func (c *Client) GetSession(ctx context.Context, req *spannerpb.GetSessionReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSession[0:len(c.CallOptions.GetSession):len(c.CallOptions.GetSession)], opts...) + opts = append((*c.CallOptions).GetSession[0:len((*c.CallOptions).GetSession):len((*c.CallOptions).GetSession)], opts...) var resp *spannerpb.Session err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -387,11 +608,10 @@ func (c *Client) GetSession(ctx context.Context, req *spannerpb.GetSessionReques return resp, nil } -// ListSessions lists all sessions in a given database. -func (c *Client) ListSessions(ctx context.Context, req *spannerpb.ListSessionsRequest, opts ...gax.CallOption) *SessionIterator { +func (c *gRPCClient) ListSessions(ctx context.Context, req *spannerpb.ListSessionsRequest, opts ...gax.CallOption) *SessionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "database", url.QueryEscape(req.GetDatabase()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSessions[0:len(c.CallOptions.ListSessions):len(c.CallOptions.ListSessions)], opts...) + opts = append((*c.CallOptions).ListSessions[0:len((*c.CallOptions).ListSessions):len((*c.CallOptions).ListSessions)], opts...) it := &SessionIterator{} req = proto.Clone(req).(*spannerpb.ListSessionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*spannerpb.Session, string, error) { @@ -428,10 +648,7 @@ func (c *Client) ListSessions(ctx context.Context, req *spannerpb.ListSessionsRe return it } -// DeleteSession ends a session, releasing server resources associated with it. This will -// asynchronously trigger cancellation of any operations that are running with -// this session. -func (c *Client) DeleteSession(ctx context.Context, req *spannerpb.DeleteSessionRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteSession(ctx context.Context, req *spannerpb.DeleteSessionRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -439,7 +656,7 @@ func (c *Client) DeleteSession(ctx context.Context, req *spannerpb.DeleteSession } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteSession[0:len(c.CallOptions.DeleteSession):len(c.CallOptions.DeleteSession)], opts...) + opts = append((*c.CallOptions).DeleteSession[0:len((*c.CallOptions).DeleteSession):len((*c.CallOptions).DeleteSession)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteSession(ctx, req, settings.GRPC...) @@ -448,18 +665,7 @@ func (c *Client) DeleteSession(ctx context.Context, req *spannerpb.DeleteSession return err } -// ExecuteSql executes an SQL statement, returning all results in a single reply. This -// method cannot be used to return a result set larger than 10 MiB; -// if the query yields more data than that, the query fails with -// a FAILED_PRECONDITION error. -// -// Operations inside read-write transactions might return ABORTED. If -// this occurs, the application should restart the transaction from -// the beginning. See Transaction for more details. -// -// Larger result sets can be fetched in streaming fashion by calling -// ExecuteStreamingSql instead. -func (c *Client) ExecuteSql(ctx context.Context, req *spannerpb.ExecuteSqlRequest, opts ...gax.CallOption) (*spannerpb.ResultSet, error) { +func (c *gRPCClient) ExecuteSql(ctx context.Context, req *spannerpb.ExecuteSqlRequest, opts ...gax.CallOption) (*spannerpb.ResultSet, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -467,7 +673,7 @@ func (c *Client) ExecuteSql(ctx context.Context, req *spannerpb.ExecuteSqlReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExecuteSql[0:len(c.CallOptions.ExecuteSql):len(c.CallOptions.ExecuteSql)], opts...) + opts = append((*c.CallOptions).ExecuteSql[0:len((*c.CallOptions).ExecuteSql):len((*c.CallOptions).ExecuteSql)], opts...) var resp *spannerpb.ResultSet err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -480,15 +686,9 @@ func (c *Client) ExecuteSql(ctx context.Context, req *spannerpb.ExecuteSqlReques return resp, nil } -// ExecuteStreamingSql like ExecuteSql, except returns the result -// set as a stream. Unlike ExecuteSql, there -// is no limit on the size of the returned result set. However, no -// individual row in the result set can exceed 100 MiB, and no -// column value can exceed 10 MiB. -func (c *Client) ExecuteStreamingSql(ctx context.Context, req *spannerpb.ExecuteSqlRequest, opts ...gax.CallOption) (spannerpb.Spanner_ExecuteStreamingSqlClient, error) { +func (c *gRPCClient) ExecuteStreamingSql(ctx context.Context, req *spannerpb.ExecuteSqlRequest, opts ...gax.CallOption) (spannerpb.Spanner_ExecuteStreamingSqlClient, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExecuteStreamingSql[0:len(c.CallOptions.ExecuteStreamingSql):len(c.CallOptions.ExecuteStreamingSql)], opts...) var resp spannerpb.Spanner_ExecuteStreamingSqlClient err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -501,18 +701,7 @@ func (c *Client) ExecuteStreamingSql(ctx context.Context, req *spannerpb.Execute return resp, nil } -// ExecuteBatchDml executes a batch of SQL DML statements. This method allows many statements -// to be run with lower latency than submitting them sequentially with -// ExecuteSql. -// -// Statements are executed in sequential order. A request can succeed even if -// a statement fails. The ExecuteBatchDmlResponse.status field in the -// response provides information about the statement that failed. Clients must -// inspect this field to determine whether an error occurred. -// -// Execution stops after the first failed statement; the remaining statements -// are not executed. -func (c *Client) ExecuteBatchDml(ctx context.Context, req *spannerpb.ExecuteBatchDmlRequest, opts ...gax.CallOption) (*spannerpb.ExecuteBatchDmlResponse, error) { +func (c *gRPCClient) ExecuteBatchDml(ctx context.Context, req *spannerpb.ExecuteBatchDmlRequest, opts ...gax.CallOption) (*spannerpb.ExecuteBatchDmlResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -520,7 +709,7 @@ func (c *Client) ExecuteBatchDml(ctx context.Context, req *spannerpb.ExecuteBatc } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ExecuteBatchDml[0:len(c.CallOptions.ExecuteBatchDml):len(c.CallOptions.ExecuteBatchDml)], opts...) + opts = append((*c.CallOptions).ExecuteBatchDml[0:len((*c.CallOptions).ExecuteBatchDml):len((*c.CallOptions).ExecuteBatchDml)], opts...) var resp *spannerpb.ExecuteBatchDmlResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -533,20 +722,7 @@ func (c *Client) ExecuteBatchDml(ctx context.Context, req *spannerpb.ExecuteBatc return resp, nil } -// Read reads rows from the database using key lookups and scans, as a -// simple key/value style alternative to -// ExecuteSql. This method cannot be used to -// return a result set larger than 10 MiB; if the read matches more -// data than that, the read fails with a FAILED_PRECONDITION -// error. -// -// Reads inside read-write transactions might return ABORTED. If -// this occurs, the application should restart the transaction from -// the beginning. See Transaction for more details. -// -// Larger result sets can be yielded in streaming fashion by calling -// StreamingRead instead. -func (c *Client) Read(ctx context.Context, req *spannerpb.ReadRequest, opts ...gax.CallOption) (*spannerpb.ResultSet, error) { +func (c *gRPCClient) Read(ctx context.Context, req *spannerpb.ReadRequest, opts ...gax.CallOption) (*spannerpb.ResultSet, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -554,7 +730,7 @@ func (c *Client) Read(ctx context.Context, req *spannerpb.ReadRequest, opts ...g } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.Read[0:len(c.CallOptions.Read):len(c.CallOptions.Read)], opts...) + opts = append((*c.CallOptions).Read[0:len((*c.CallOptions).Read):len((*c.CallOptions).Read)], opts...) var resp *spannerpb.ResultSet err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -567,15 +743,9 @@ func (c *Client) Read(ctx context.Context, req *spannerpb.ReadRequest, opts ...g return resp, nil } -// StreamingRead like Read, except returns the result set as a -// stream. Unlike Read, there is no limit on the -// size of the returned result set. However, no individual row in -// the result set can exceed 100 MiB, and no column value can exceed -// 10 MiB. -func (c *Client) StreamingRead(ctx context.Context, req *spannerpb.ReadRequest, opts ...gax.CallOption) (spannerpb.Spanner_StreamingReadClient, error) { +func (c *gRPCClient) StreamingRead(ctx context.Context, req *spannerpb.ReadRequest, opts ...gax.CallOption) (spannerpb.Spanner_StreamingReadClient, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.StreamingRead[0:len(c.CallOptions.StreamingRead):len(c.CallOptions.StreamingRead)], opts...) var resp spannerpb.Spanner_StreamingReadClient err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -588,11 +758,7 @@ func (c *Client) StreamingRead(ctx context.Context, req *spannerpb.ReadRequest, return resp, nil } -// BeginTransaction begins a new transaction. This step can often be skipped: -// Read, ExecuteSql and -// Commit can begin a new transaction as a -// side-effect. -func (c *Client) BeginTransaction(ctx context.Context, req *spannerpb.BeginTransactionRequest, opts ...gax.CallOption) (*spannerpb.Transaction, error) { +func (c *gRPCClient) BeginTransaction(ctx context.Context, req *spannerpb.BeginTransactionRequest, opts ...gax.CallOption) (*spannerpb.Transaction, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -600,7 +766,7 @@ func (c *Client) BeginTransaction(ctx context.Context, req *spannerpb.BeginTrans } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BeginTransaction[0:len(c.CallOptions.BeginTransaction):len(c.CallOptions.BeginTransaction)], opts...) + opts = append((*c.CallOptions).BeginTransaction[0:len((*c.CallOptions).BeginTransaction):len((*c.CallOptions).BeginTransaction)], opts...) var resp *spannerpb.Transaction err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -613,21 +779,7 @@ func (c *Client) BeginTransaction(ctx context.Context, req *spannerpb.BeginTrans return resp, nil } -// Commit commits a transaction. The request includes the mutations to be -// applied to rows in the database. -// -// Commit might return an ABORTED error. This can occur at any time; -// commonly, the cause is conflicts with concurrent -// transactions. However, it can also happen for a variety of other -// reasons. If Commit returns ABORTED, the caller should re-attempt -// the transaction from the beginning, re-using the same session. -// -// On very rare occasions, Commit might return UNKNOWN. This can happen, -// for example, if the client job experiences a 1+ hour networking failure. -// At that point, Cloud Spanner has lost track of the transaction outcome and -// we recommend that you perform another read from the database to see the -// state of things as they are now. -func (c *Client) Commit(ctx context.Context, req *spannerpb.CommitRequest, opts ...gax.CallOption) (*spannerpb.CommitResponse, error) { +func (c *gRPCClient) Commit(ctx context.Context, req *spannerpb.CommitRequest, opts ...gax.CallOption) (*spannerpb.CommitResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 3600000*time.Millisecond) defer cancel() @@ -635,7 +787,7 @@ func (c *Client) Commit(ctx context.Context, req *spannerpb.CommitRequest, opts } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.Commit[0:len(c.CallOptions.Commit):len(c.CallOptions.Commit)], opts...) + opts = append((*c.CallOptions).Commit[0:len((*c.CallOptions).Commit):len((*c.CallOptions).Commit)], opts...) var resp *spannerpb.CommitResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -648,15 +800,7 @@ func (c *Client) Commit(ctx context.Context, req *spannerpb.CommitRequest, opts return resp, nil } -// Rollback rolls back a transaction, releasing any locks it holds. It is a good -// idea to call this for any transaction that includes one or more -// Read or ExecuteSql requests and -// ultimately decides not to commit. -// -// Rollback returns OK if it successfully aborts the transaction, the -// transaction was already aborted, or the transaction is not -// found. Rollback never returns ABORTED. -func (c *Client) Rollback(ctx context.Context, req *spannerpb.RollbackRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) Rollback(ctx context.Context, req *spannerpb.RollbackRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -664,7 +808,7 @@ func (c *Client) Rollback(ctx context.Context, req *spannerpb.RollbackRequest, o } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.Rollback[0:len(c.CallOptions.Rollback):len(c.CallOptions.Rollback)], opts...) + opts = append((*c.CallOptions).Rollback[0:len((*c.CallOptions).Rollback):len((*c.CallOptions).Rollback)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.Rollback(ctx, req, settings.GRPC...) @@ -673,18 +817,7 @@ func (c *Client) Rollback(ctx context.Context, req *spannerpb.RollbackRequest, o return err } -// PartitionQuery creates a set of partition tokens that can be used to execute a query -// operation in parallel. Each of the returned partition tokens can be used -// by ExecuteStreamingSql to specify a subset -// of the query result to read. The same session and read-only transaction -// must be used by the PartitionQueryRequest used to create the -// partition tokens and the ExecuteSqlRequests that use the partition tokens. -// -// Partition tokens become invalid when the session used to create them -// is deleted, is idle for too long, begins a new transaction, or becomes too -// old. When any of these happen, it is not possible to resume the query, and -// the whole operation must be restarted from the beginning. -func (c *Client) PartitionQuery(ctx context.Context, req *spannerpb.PartitionQueryRequest, opts ...gax.CallOption) (*spannerpb.PartitionResponse, error) { +func (c *gRPCClient) PartitionQuery(ctx context.Context, req *spannerpb.PartitionQueryRequest, opts ...gax.CallOption) (*spannerpb.PartitionResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -692,7 +825,7 @@ func (c *Client) PartitionQuery(ctx context.Context, req *spannerpb.PartitionQue } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PartitionQuery[0:len(c.CallOptions.PartitionQuery):len(c.CallOptions.PartitionQuery)], opts...) + opts = append((*c.CallOptions).PartitionQuery[0:len((*c.CallOptions).PartitionQuery):len((*c.CallOptions).PartitionQuery)], opts...) var resp *spannerpb.PartitionResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -705,20 +838,7 @@ func (c *Client) PartitionQuery(ctx context.Context, req *spannerpb.PartitionQue return resp, nil } -// PartitionRead creates a set of partition tokens that can be used to execute a read -// operation in parallel. Each of the returned partition tokens can be used -// by StreamingRead to specify a subset of the read -// result to read. The same session and read-only transaction must be used by -// the PartitionReadRequest used to create the partition tokens and the -// ReadRequests that use the partition tokens. There are no ordering -// guarantees on rows returned among the returned partition tokens, or even -// within each individual StreamingRead call issued with a partition_token. -// -// Partition tokens become invalid when the session used to create them -// is deleted, is idle for too long, begins a new transaction, or becomes too -// old. When any of these happen, it is not possible to resume the read, and -// the whole operation must be restarted from the beginning. -func (c *Client) PartitionRead(ctx context.Context, req *spannerpb.PartitionReadRequest, opts ...gax.CallOption) (*spannerpb.PartitionResponse, error) { +func (c *gRPCClient) PartitionRead(ctx context.Context, req *spannerpb.PartitionReadRequest, opts ...gax.CallOption) (*spannerpb.PartitionResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -726,7 +846,7 @@ func (c *Client) PartitionRead(ctx context.Context, req *spannerpb.PartitionRead } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "session", url.QueryEscape(req.GetSession()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PartitionRead[0:len(c.CallOptions.PartitionRead):len(c.CallOptions.PartitionRead)], opts...) + opts = append((*c.CallOptions).PartitionRead[0:len((*c.CallOptions).PartitionRead):len((*c.CallOptions).PartitionRead)], opts...) var resp *spannerpb.PartitionResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/spanner/apiv1/spanner_client_example_test.go b/spanner/apiv1/spanner_client_example_test.go index d29a53a91460..79c11af77e8a 100644 --- a/spanner/apiv1/spanner_client_example_test.go +++ b/spanner/apiv1/spanner_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateSession() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.CreateSessionRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleClient_CreateSession() { } func ExampleClient_BatchCreateSessions() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.BatchCreateSessionsRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleClient_BatchCreateSessions() { } func ExampleClient_GetSession() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.GetSessionRequest{ // TODO: Fill request struct fields. @@ -95,14 +94,12 @@ func ExampleClient_GetSession() { } func ExampleClient_ListSessions() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.ListSessionsRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleClient_DeleteSession() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.DeleteSessionRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleClient_DeleteSession() { } func ExampleClient_ExecuteSql() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.ExecuteSqlRequest{ // TODO: Fill request struct fields. @@ -158,13 +155,12 @@ func ExampleClient_ExecuteSql() { } func ExampleClient_ExecuteBatchDml() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.ExecuteBatchDmlRequest{ // TODO: Fill request struct fields. @@ -178,13 +174,12 @@ func ExampleClient_ExecuteBatchDml() { } func ExampleClient_Read() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.ReadRequest{ // TODO: Fill request struct fields. @@ -198,13 +193,12 @@ func ExampleClient_Read() { } func ExampleClient_BeginTransaction() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.BeginTransactionRequest{ // TODO: Fill request struct fields. @@ -218,13 +212,12 @@ func ExampleClient_BeginTransaction() { } func ExampleClient_Commit() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.CommitRequest{ // TODO: Fill request struct fields. @@ -243,6 +236,7 @@ func ExampleClient_Rollback() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.RollbackRequest{ // TODO: Fill request struct fields. @@ -254,13 +248,12 @@ func ExampleClient_Rollback() { } func ExampleClient_PartitionQuery() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.PartitionQueryRequest{ // TODO: Fill request struct fields. @@ -274,13 +267,12 @@ func ExampleClient_PartitionQuery() { } func ExampleClient_PartitionRead() { - // import spannerpb "google.golang.org/genproto/googleapis/spanner/v1" - ctx := context.Background() c, err := spanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &spannerpb.PartitionReadRequest{ // TODO: Fill request struct fields. diff --git a/spanner/apiv1/spanner_client_options.go b/spanner/apiv1/spanner_client_options.go index 639e890d4d83..5b924b5d1d74 100644 --- a/spanner/apiv1/spanner_client_options.go +++ b/spanner/apiv1/spanner_client_options.go @@ -21,5 +21,5 @@ import "google.golang.org/api/option" // This function is only intended for use by the client library, and may be // removed at any time without any warning. func DefaultClientOptions() []option.ClientOption { - return defaultClientOptions() + return defaultGRPCClientOptions() } diff --git a/spanner/go.mod b/spanner/go.mod index e16586e0cda7..a889414f9ff5 100644 --- a/spanner/go.mod +++ b/spanner/go.mod @@ -9,8 +9,8 @@ require ( github.com/googleapis/gax-go/v2 v2.0.5 go.opencensus.io v0.23.0 golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 - google.golang.org/api v0.46.0 - google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a + google.golang.org/api v0.47.0 + google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d google.golang.org/grpc v1.37.1 google.golang.org/protobuf v1.26.0 ) diff --git a/spanner/go.sum b/spanner/go.sum index 21f3a0377fc0..259241ea7f17 100644 --- a/spanner/go.sum +++ b/spanner/go.sum @@ -144,6 +144,7 @@ github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -179,8 +180,9 @@ golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHl golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5 h1:2M3HP5CCK1Si9FQhwnzYhXdG6DXeebvUHFpre8QvbyI= golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 h1:VLliZ0d+/avPrXXH+OakdXhpJuEoBZuwh1m2j7U6Iug= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= @@ -190,8 +192,9 @@ golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.1 h1:Kvvh58BN8Y9/lBi7hTekvtMpm07eUZ0ck5pRHpsMWrY= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -225,6 +228,7 @@ golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420 h1:a8jGStKg0XqKDlKqjLrXn0ioF5MH36pT7Z0BRTqLhbk= golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -238,8 +242,8 @@ golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210427180440-81ed05c6b58c h1:SgVl/sCtkicsS7psKkje4H9YtjdEl3xsYh7N+5TDHqY= -golang.org/x/oauth2 v0.0.0-20210427180440-81ed05c6b58c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c h1:pkQiBZBvdos9qq4wBAHqlzuZHEXo07pqV06ef90u1WI= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -286,9 +290,11 @@ golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210503080704-8803ae5d1324 h1:pAwJxDByZctfPwzlNGrDN2BQLsdPb9NkhoTJtUkAO28= -golang.org/x/sys v0.0.0-20210503080704-8803ae5d1324/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015 h1:hZR0X1kPW+nwyJ9xRxqZk1vx5RUObAPBdKVvXPDUH/E= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -347,8 +353,9 @@ golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.0 h1:po9/4sTYwZU9lPhi1tOrb4hCv3qrhiQ77LZfGa2OjwY= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.1 h1:wGiQel/hW0NnEkJUk8lbzkX2gFJU6PFxf1v5OlCfuOs= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -375,8 +382,8 @@ google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34q google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= -google.golang.org/api v0.46.0 h1:jkDWHOBIoNSD0OQpq4rtBVu+Rh325MPjXG1rakAp8JU= -google.golang.org/api v0.46.0/go.mod h1:ceL4oozhkAiTID8XMmJBsIxID/9wMXJVVFXPg4ylg3I= +google.golang.org/api v0.47.0 h1:sQLWZQvP6jPGIP4JGPkJu4zHswrv81iobiyszr3b/0I= +google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -424,9 +431,9 @@ google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= -google.golang.org/genproto v0.0.0-20210429181445-86c259c2b4ab/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= -google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a h1:VA0wtJaR+W1I11P2f535J7D/YxyvEFMTMvcmyeZ9FBE= -google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d h1:bRz6UmsZEz/CzoTjUDp4ZcdguhSWi6CyU299wMQBpZU= +google.golang.org/genproto v0.0.0-20210518161634-ec7691c0a37d/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= @@ -445,7 +452,6 @@ google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA5 google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/grpc v1.37.1 h1:ARnQJNWxGyYJpdf/JXscNlQr/uv607ZPU9Z7ogHi+iI= google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= diff --git a/speech/apiv1/doc.go b/speech/apiv1/doc.go index f057f756b62b..954e8c119041 100644 --- a/speech/apiv1/doc.go +++ b/speech/apiv1/doc.go @@ -28,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package speech // import "cloud.google.com/go/speech/apiv1" import ( @@ -48,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/speech/apiv1/speech_client.go b/speech/apiv1/speech_client.go index 25917a05d574..fe9c71ad6d35 100644 --- a/speech/apiv1/speech_client.go +++ b/speech/apiv1/speech_client.go @@ -43,7 +43,7 @@ type CallOptions struct { StreamingRecognize []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("speech.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("speech.mtls.googleapis.com:443"), @@ -85,37 +85,115 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Speech-to-Text API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + Recognize(context.Context, *speechpb.RecognizeRequest, ...gax.CallOption) (*speechpb.RecognizeResponse, error) + LongRunningRecognize(context.Context, *speechpb.LongRunningRecognizeRequest, ...gax.CallOption) (*LongRunningRecognizeOperation, error) + LongRunningRecognizeOperation(name string) *LongRunningRecognizeOperation + StreamingRecognize(context.Context, ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) +} + // Client is a client for interacting with Cloud Speech-to-Text API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service that implements Google Cloud Speech API. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// Recognize performs synchronous speech recognition: receive results after all audio +// has been sent and processed. +func (c *Client) Recognize(ctx context.Context, req *speechpb.RecognizeRequest, opts ...gax.CallOption) (*speechpb.RecognizeResponse, error) { + return c.internalClient.Recognize(ctx, req, opts...) +} + +// LongRunningRecognize performs asynchronous speech recognition: receive results via the +// google.longrunning.Operations interface. Returns either an +// Operation.error or an Operation.response which contains +// a LongRunningRecognizeResponse message. +// For more information on asynchronous speech recognition, see the +// how-to (at https://cloud.google.com/speech-to-text/docs/async-recognize). +func (c *Client) LongRunningRecognize(ctx context.Context, req *speechpb.LongRunningRecognizeRequest, opts ...gax.CallOption) (*LongRunningRecognizeOperation, error) { + return c.internalClient.LongRunningRecognize(ctx, req, opts...) +} + +// LongRunningRecognizeOperation returns a new LongRunningRecognizeOperation from a given name. +// The name must be that of a previously created LongRunningRecognizeOperation, possibly from a different process. +func (c *Client) LongRunningRecognizeOperation(name string) *LongRunningRecognizeOperation { + return c.internalClient.LongRunningRecognizeOperation(name) +} + +// StreamingRecognize performs bidirectional streaming speech recognition: receive results while +// sending audio. This method is only available via the gRPC API (not REST). +func (c *Client) StreamingRecognize(ctx context.Context, opts ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) { + return c.internalClient.StreamingRecognize(ctx, opts...) +} + +// gRPCClient is a client for interacting with Cloud Speech-to-Text API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client speechpb.SpeechClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new speech client. +// NewClient creates a new speech client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service that implements Google Cloud Speech API. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -133,16 +211,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: speechpb.NewSpeechClient(connPool), + client: speechpb.NewSpeechClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -152,41 +233,40 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// Recognize performs synchronous speech recognition: receive results after all audio -// has been sent and processed. -func (c *Client) Recognize(ctx context.Context, req *speechpb.RecognizeRequest, opts ...gax.CallOption) (*speechpb.RecognizeResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) Recognize(ctx context.Context, req *speechpb.RecognizeRequest, opts ...gax.CallOption) (*speechpb.RecognizeResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.Recognize[0:len(c.CallOptions.Recognize):len(c.CallOptions.Recognize)], opts...) + opts = append((*c.CallOptions).Recognize[0:len((*c.CallOptions).Recognize):len((*c.CallOptions).Recognize)], opts...) var resp *speechpb.RecognizeResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -199,20 +279,14 @@ func (c *Client) Recognize(ctx context.Context, req *speechpb.RecognizeRequest, return resp, nil } -// LongRunningRecognize performs asynchronous speech recognition: receive results via the -// google.longrunning.Operations interface. Returns either an -// Operation.error or an Operation.response which contains -// a LongRunningRecognizeResponse message. -// For more information on asynchronous speech recognition, see the -// how-to (at https://cloud.google.com/speech-to-text/docs/async-recognize). -func (c *Client) LongRunningRecognize(ctx context.Context, req *speechpb.LongRunningRecognizeRequest, opts ...gax.CallOption) (*LongRunningRecognizeOperation, error) { +func (c *gRPCClient) LongRunningRecognize(ctx context.Context, req *speechpb.LongRunningRecognizeRequest, opts ...gax.CallOption) (*LongRunningRecognizeOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.LongRunningRecognize[0:len(c.CallOptions.LongRunningRecognize):len(c.CallOptions.LongRunningRecognize)], opts...) + opts = append((*c.CallOptions).LongRunningRecognize[0:len((*c.CallOptions).LongRunningRecognize):len((*c.CallOptions).LongRunningRecognize)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -223,16 +297,14 @@ func (c *Client) LongRunningRecognize(ctx context.Context, req *speechpb.LongRun return nil, err } return &LongRunningRecognizeOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// StreamingRecognize performs bidirectional streaming speech recognition: receive results while -// sending audio. This method is only available via the gRPC API (not REST). -func (c *Client) StreamingRecognize(ctx context.Context, opts ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) { +func (c *gRPCClient) StreamingRecognize(ctx context.Context, opts ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.StreamingRecognize[0:len(c.CallOptions.StreamingRecognize):len(c.CallOptions.StreamingRecognize)], opts...) var resp speechpb.Speech_StreamingRecognizeClient + opts = append((*c.CallOptions).StreamingRecognize[0:len((*c.CallOptions).StreamingRecognize):len((*c.CallOptions).StreamingRecognize)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.client.StreamingRecognize(ctx, settings.GRPC...) @@ -251,9 +323,9 @@ type LongRunningRecognizeOperation struct { // LongRunningRecognizeOperation returns a new LongRunningRecognizeOperation from a given name. // The name must be that of a previously created LongRunningRecognizeOperation, possibly from a different process. -func (c *Client) LongRunningRecognizeOperation(name string) *LongRunningRecognizeOperation { +func (c *gRPCClient) LongRunningRecognizeOperation(name string) *LongRunningRecognizeOperation { return &LongRunningRecognizeOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/speech/apiv1/speech_client_example_test.go b/speech/apiv1/speech_client_example_test.go index dcb9fe2ee93f..efe5f9245646 100644 --- a/speech/apiv1/speech_client_example_test.go +++ b/speech/apiv1/speech_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_Recognize() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1" - ctx := context.Background() c, err := speech.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.RecognizeRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleClient_Recognize() { } func ExampleClient_LongRunningRecognize() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1" - ctx := context.Background() c, err := speech.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.LongRunningRecognizeRequest{ // TODO: Fill request struct fields. @@ -80,13 +80,12 @@ func ExampleClient_LongRunningRecognize() { } func ExampleClient_StreamingRecognize() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1" - ctx := context.Background() c, err := speech.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.StreamingRecognize(ctx) if err != nil { // TODO: Handle error. diff --git a/speech/apiv1p1beta1/adaptation_client.go b/speech/apiv1p1beta1/adaptation_client.go index 94dbdccfeeac..2fa6e340c9f8 100644 --- a/speech/apiv1p1beta1/adaptation_client.go +++ b/speech/apiv1p1beta1/adaptation_client.go @@ -49,7 +49,7 @@ type AdaptationCallOptions struct { DeleteCustomClass []gax.CallOption } -func defaultAdaptationClientOptions() []option.ClientOption { +func defaultAdaptationGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("speech.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("speech.mtls.googleapis.com:443"), @@ -76,32 +76,135 @@ func defaultAdaptationCallOptions() *AdaptationCallOptions { } } +// internalAdaptationClient is an interface that defines the methods availaible from Cloud Speech-to-Text API. +type internalAdaptationClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreatePhraseSet(context.Context, *speechpb.CreatePhraseSetRequest, ...gax.CallOption) (*speechpb.PhraseSet, error) + GetPhraseSet(context.Context, *speechpb.GetPhraseSetRequest, ...gax.CallOption) (*speechpb.PhraseSet, error) + ListPhraseSet(context.Context, *speechpb.ListPhraseSetRequest, ...gax.CallOption) *PhraseSetIterator + UpdatePhraseSet(context.Context, *speechpb.UpdatePhraseSetRequest, ...gax.CallOption) (*speechpb.PhraseSet, error) + DeletePhraseSet(context.Context, *speechpb.DeletePhraseSetRequest, ...gax.CallOption) error + CreateCustomClass(context.Context, *speechpb.CreateCustomClassRequest, ...gax.CallOption) (*speechpb.CustomClass, error) + GetCustomClass(context.Context, *speechpb.GetCustomClassRequest, ...gax.CallOption) (*speechpb.CustomClass, error) + ListCustomClasses(context.Context, *speechpb.ListCustomClassesRequest, ...gax.CallOption) *CustomClassIterator + UpdateCustomClass(context.Context, *speechpb.UpdateCustomClassRequest, ...gax.CallOption) (*speechpb.CustomClass, error) + DeleteCustomClass(context.Context, *speechpb.DeleteCustomClassRequest, ...gax.CallOption) error +} + // AdaptationClient is a client for interacting with Cloud Speech-to-Text API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service that implements Google Cloud Speech Adaptation API. type AdaptationClient struct { + // The internal transport-dependent client. + internalClient internalAdaptationClient + + // The call options for this service. + CallOptions *AdaptationCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *AdaptationClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *AdaptationClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *AdaptationClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreatePhraseSet create a set of phrase hints. Each item in the set can be a single word or +// a multi-word phrase. The items in the PhraseSet are favored by the +// recognition model when you send a call that includes the PhraseSet. +func (c *AdaptationClient) CreatePhraseSet(ctx context.Context, req *speechpb.CreatePhraseSetRequest, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { + return c.internalClient.CreatePhraseSet(ctx, req, opts...) +} + +// GetPhraseSet get a phrase set. +func (c *AdaptationClient) GetPhraseSet(ctx context.Context, req *speechpb.GetPhraseSetRequest, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { + return c.internalClient.GetPhraseSet(ctx, req, opts...) +} + +// ListPhraseSet list phrase sets. +func (c *AdaptationClient) ListPhraseSet(ctx context.Context, req *speechpb.ListPhraseSetRequest, opts ...gax.CallOption) *PhraseSetIterator { + return c.internalClient.ListPhraseSet(ctx, req, opts...) +} + +// UpdatePhraseSet update a phrase set. +func (c *AdaptationClient) UpdatePhraseSet(ctx context.Context, req *speechpb.UpdatePhraseSetRequest, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { + return c.internalClient.UpdatePhraseSet(ctx, req, opts...) +} + +// DeletePhraseSet delete a phrase set. +func (c *AdaptationClient) DeletePhraseSet(ctx context.Context, req *speechpb.DeletePhraseSetRequest, opts ...gax.CallOption) error { + return c.internalClient.DeletePhraseSet(ctx, req, opts...) +} + +// CreateCustomClass create a custom class. +func (c *AdaptationClient) CreateCustomClass(ctx context.Context, req *speechpb.CreateCustomClassRequest, opts ...gax.CallOption) (*speechpb.CustomClass, error) { + return c.internalClient.CreateCustomClass(ctx, req, opts...) +} + +// GetCustomClass get a custom class. +func (c *AdaptationClient) GetCustomClass(ctx context.Context, req *speechpb.GetCustomClassRequest, opts ...gax.CallOption) (*speechpb.CustomClass, error) { + return c.internalClient.GetCustomClass(ctx, req, opts...) +} + +// ListCustomClasses list custom classes. +func (c *AdaptationClient) ListCustomClasses(ctx context.Context, req *speechpb.ListCustomClassesRequest, opts ...gax.CallOption) *CustomClassIterator { + return c.internalClient.ListCustomClasses(ctx, req, opts...) +} + +// UpdateCustomClass update a custom class. +func (c *AdaptationClient) UpdateCustomClass(ctx context.Context, req *speechpb.UpdateCustomClassRequest, opts ...gax.CallOption) (*speechpb.CustomClass, error) { + return c.internalClient.UpdateCustomClass(ctx, req, opts...) +} + +// DeleteCustomClass delete a custom class. +func (c *AdaptationClient) DeleteCustomClass(ctx context.Context, req *speechpb.DeleteCustomClassRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteCustomClass(ctx, req, opts...) +} + +// adaptationGRPCClient is a client for interacting with Cloud Speech-to-Text API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type adaptationGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing AdaptationClient + CallOptions **AdaptationCallOptions + // The gRPC API client. adaptationClient speechpb.AdaptationClient - // The call options for this service. - CallOptions *AdaptationCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewAdaptationClient creates a new adaptation client. +// NewAdaptationClient creates a new adaptation client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service that implements Google Cloud Speech Adaptation API. func NewAdaptationClient(ctx context.Context, opts ...option.ClientOption) (*AdaptationClient, error) { - clientOpts := defaultAdaptationClientOptions() - + clientOpts := defaultAdaptationGRPCClientOptions() if newAdaptationClientHook != nil { hookOpts, err := newAdaptationClientHook(ctx, clientHookParams{}) if err != nil { @@ -119,47 +222,47 @@ func NewAdaptationClient(ctx context.Context, opts ...option.ClientOption) (*Ada if err != nil { return nil, err } - c := &AdaptationClient{ + client := AdaptationClient{CallOptions: defaultAdaptationCallOptions()} + + c := &adaptationGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultAdaptationCallOptions(), - adaptationClient: speechpb.NewAdaptationClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *AdaptationClient) Connection() *grpc.ClientConn { +func (c *adaptationGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *AdaptationClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *AdaptationClient) setGoogleClientInfo(keyval ...string) { +func (c *adaptationGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreatePhraseSet create a set of phrase hints. Each item in the set can be a single word or -// a multi-word phrase. The items in the PhraseSet are favored by the -// recognition model when you send a call that includes the PhraseSet. -func (c *AdaptationClient) CreatePhraseSet(ctx context.Context, req *speechpb.CreatePhraseSetRequest, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *adaptationGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *adaptationGRPCClient) CreatePhraseSet(ctx context.Context, req *speechpb.CreatePhraseSetRequest, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreatePhraseSet[0:len(c.CallOptions.CreatePhraseSet):len(c.CallOptions.CreatePhraseSet)], opts...) + opts = append((*c.CallOptions).CreatePhraseSet[0:len((*c.CallOptions).CreatePhraseSet):len((*c.CallOptions).CreatePhraseSet)], opts...) var resp *speechpb.PhraseSet err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -172,11 +275,10 @@ func (c *AdaptationClient) CreatePhraseSet(ctx context.Context, req *speechpb.Cr return resp, nil } -// GetPhraseSet get a phrase set. -func (c *AdaptationClient) GetPhraseSet(ctx context.Context, req *speechpb.GetPhraseSetRequest, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { +func (c *adaptationGRPCClient) GetPhraseSet(ctx context.Context, req *speechpb.GetPhraseSetRequest, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetPhraseSet[0:len(c.CallOptions.GetPhraseSet):len(c.CallOptions.GetPhraseSet)], opts...) + opts = append((*c.CallOptions).GetPhraseSet[0:len((*c.CallOptions).GetPhraseSet):len((*c.CallOptions).GetPhraseSet)], opts...) var resp *speechpb.PhraseSet err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -189,11 +291,10 @@ func (c *AdaptationClient) GetPhraseSet(ctx context.Context, req *speechpb.GetPh return resp, nil } -// ListPhraseSet list phrase sets. -func (c *AdaptationClient) ListPhraseSet(ctx context.Context, req *speechpb.ListPhraseSetRequest, opts ...gax.CallOption) *PhraseSetIterator { +func (c *adaptationGRPCClient) ListPhraseSet(ctx context.Context, req *speechpb.ListPhraseSetRequest, opts ...gax.CallOption) *PhraseSetIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListPhraseSet[0:len(c.CallOptions.ListPhraseSet):len(c.CallOptions.ListPhraseSet)], opts...) + opts = append((*c.CallOptions).ListPhraseSet[0:len((*c.CallOptions).ListPhraseSet):len((*c.CallOptions).ListPhraseSet)], opts...) it := &PhraseSetIterator{} req = proto.Clone(req).(*speechpb.ListPhraseSetRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*speechpb.PhraseSet, string, error) { @@ -230,11 +331,10 @@ func (c *AdaptationClient) ListPhraseSet(ctx context.Context, req *speechpb.List return it } -// UpdatePhraseSet update a phrase set. -func (c *AdaptationClient) UpdatePhraseSet(ctx context.Context, req *speechpb.UpdatePhraseSetRequest, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { +func (c *adaptationGRPCClient) UpdatePhraseSet(ctx context.Context, req *speechpb.UpdatePhraseSetRequest, opts ...gax.CallOption) (*speechpb.PhraseSet, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "phrase_set.name", url.QueryEscape(req.GetPhraseSet().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdatePhraseSet[0:len(c.CallOptions.UpdatePhraseSet):len(c.CallOptions.UpdatePhraseSet)], opts...) + opts = append((*c.CallOptions).UpdatePhraseSet[0:len((*c.CallOptions).UpdatePhraseSet):len((*c.CallOptions).UpdatePhraseSet)], opts...) var resp *speechpb.PhraseSet err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -247,11 +347,10 @@ func (c *AdaptationClient) UpdatePhraseSet(ctx context.Context, req *speechpb.Up return resp, nil } -// DeletePhraseSet delete a phrase set. -func (c *AdaptationClient) DeletePhraseSet(ctx context.Context, req *speechpb.DeletePhraseSetRequest, opts ...gax.CallOption) error { +func (c *adaptationGRPCClient) DeletePhraseSet(ctx context.Context, req *speechpb.DeletePhraseSetRequest, opts ...gax.CallOption) error { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeletePhraseSet[0:len(c.CallOptions.DeletePhraseSet):len(c.CallOptions.DeletePhraseSet)], opts...) + opts = append((*c.CallOptions).DeletePhraseSet[0:len((*c.CallOptions).DeletePhraseSet):len((*c.CallOptions).DeletePhraseSet)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.adaptationClient.DeletePhraseSet(ctx, req, settings.GRPC...) @@ -260,11 +359,10 @@ func (c *AdaptationClient) DeletePhraseSet(ctx context.Context, req *speechpb.De return err } -// CreateCustomClass create a custom class. -func (c *AdaptationClient) CreateCustomClass(ctx context.Context, req *speechpb.CreateCustomClassRequest, opts ...gax.CallOption) (*speechpb.CustomClass, error) { +func (c *adaptationGRPCClient) CreateCustomClass(ctx context.Context, req *speechpb.CreateCustomClassRequest, opts ...gax.CallOption) (*speechpb.CustomClass, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCustomClass[0:len(c.CallOptions.CreateCustomClass):len(c.CallOptions.CreateCustomClass)], opts...) + opts = append((*c.CallOptions).CreateCustomClass[0:len((*c.CallOptions).CreateCustomClass):len((*c.CallOptions).CreateCustomClass)], opts...) var resp *speechpb.CustomClass err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -277,11 +375,10 @@ func (c *AdaptationClient) CreateCustomClass(ctx context.Context, req *speechpb. return resp, nil } -// GetCustomClass get a custom class. -func (c *AdaptationClient) GetCustomClass(ctx context.Context, req *speechpb.GetCustomClassRequest, opts ...gax.CallOption) (*speechpb.CustomClass, error) { +func (c *adaptationGRPCClient) GetCustomClass(ctx context.Context, req *speechpb.GetCustomClassRequest, opts ...gax.CallOption) (*speechpb.CustomClass, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCustomClass[0:len(c.CallOptions.GetCustomClass):len(c.CallOptions.GetCustomClass)], opts...) + opts = append((*c.CallOptions).GetCustomClass[0:len((*c.CallOptions).GetCustomClass):len((*c.CallOptions).GetCustomClass)], opts...) var resp *speechpb.CustomClass err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -294,11 +391,10 @@ func (c *AdaptationClient) GetCustomClass(ctx context.Context, req *speechpb.Get return resp, nil } -// ListCustomClasses list custom classes. -func (c *AdaptationClient) ListCustomClasses(ctx context.Context, req *speechpb.ListCustomClassesRequest, opts ...gax.CallOption) *CustomClassIterator { +func (c *adaptationGRPCClient) ListCustomClasses(ctx context.Context, req *speechpb.ListCustomClassesRequest, opts ...gax.CallOption) *CustomClassIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCustomClasses[0:len(c.CallOptions.ListCustomClasses):len(c.CallOptions.ListCustomClasses)], opts...) + opts = append((*c.CallOptions).ListCustomClasses[0:len((*c.CallOptions).ListCustomClasses):len((*c.CallOptions).ListCustomClasses)], opts...) it := &CustomClassIterator{} req = proto.Clone(req).(*speechpb.ListCustomClassesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*speechpb.CustomClass, string, error) { @@ -335,11 +431,10 @@ func (c *AdaptationClient) ListCustomClasses(ctx context.Context, req *speechpb. return it } -// UpdateCustomClass update a custom class. -func (c *AdaptationClient) UpdateCustomClass(ctx context.Context, req *speechpb.UpdateCustomClassRequest, opts ...gax.CallOption) (*speechpb.CustomClass, error) { +func (c *adaptationGRPCClient) UpdateCustomClass(ctx context.Context, req *speechpb.UpdateCustomClassRequest, opts ...gax.CallOption) (*speechpb.CustomClass, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "custom_class.name", url.QueryEscape(req.GetCustomClass().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCustomClass[0:len(c.CallOptions.UpdateCustomClass):len(c.CallOptions.UpdateCustomClass)], opts...) + opts = append((*c.CallOptions).UpdateCustomClass[0:len((*c.CallOptions).UpdateCustomClass):len((*c.CallOptions).UpdateCustomClass)], opts...) var resp *speechpb.CustomClass err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -352,11 +447,10 @@ func (c *AdaptationClient) UpdateCustomClass(ctx context.Context, req *speechpb. return resp, nil } -// DeleteCustomClass delete a custom class. -func (c *AdaptationClient) DeleteCustomClass(ctx context.Context, req *speechpb.DeleteCustomClassRequest, opts ...gax.CallOption) error { +func (c *adaptationGRPCClient) DeleteCustomClass(ctx context.Context, req *speechpb.DeleteCustomClassRequest, opts ...gax.CallOption) error { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteCustomClass[0:len(c.CallOptions.DeleteCustomClass):len(c.CallOptions.DeleteCustomClass)], opts...) + opts = append((*c.CallOptions).DeleteCustomClass[0:len((*c.CallOptions).DeleteCustomClass):len((*c.CallOptions).DeleteCustomClass)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.adaptationClient.DeleteCustomClass(ctx, req, settings.GRPC...) diff --git a/speech/apiv1p1beta1/adaptation_client_example_test.go b/speech/apiv1p1beta1/adaptation_client_example_test.go index 8fd678320cbd..690393e149f6 100644 --- a/speech/apiv1p1beta1/adaptation_client_example_test.go +++ b/speech/apiv1p1beta1/adaptation_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewAdaptationClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleAdaptationClient_CreatePhraseSet() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewAdaptationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.CreatePhraseSetRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleAdaptationClient_CreatePhraseSet() { } func ExampleAdaptationClient_GetPhraseSet() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewAdaptationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.GetPhraseSetRequest{ // TODO: Fill request struct fields. @@ -75,14 +75,12 @@ func ExampleAdaptationClient_GetPhraseSet() { } func ExampleAdaptationClient_ListPhraseSet() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := speech.NewAdaptationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.ListPhraseSetRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleAdaptationClient_ListPhraseSet() { } func ExampleAdaptationClient_UpdatePhraseSet() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewAdaptationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.UpdatePhraseSetRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleAdaptationClient_DeletePhraseSet() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.DeletePhraseSetRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleAdaptationClient_DeletePhraseSet() { } func ExampleAdaptationClient_CreateCustomClass() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewAdaptationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.CreateCustomClassRequest{ // TODO: Fill request struct fields. @@ -158,13 +155,12 @@ func ExampleAdaptationClient_CreateCustomClass() { } func ExampleAdaptationClient_GetCustomClass() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewAdaptationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.GetCustomClassRequest{ // TODO: Fill request struct fields. @@ -178,14 +174,12 @@ func ExampleAdaptationClient_GetCustomClass() { } func ExampleAdaptationClient_ListCustomClasses() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := speech.NewAdaptationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.ListCustomClassesRequest{ // TODO: Fill request struct fields. @@ -205,13 +199,12 @@ func ExampleAdaptationClient_ListCustomClasses() { } func ExampleAdaptationClient_UpdateCustomClass() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewAdaptationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.UpdateCustomClassRequest{ // TODO: Fill request struct fields. @@ -230,6 +223,7 @@ func ExampleAdaptationClient_DeleteCustomClass() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.DeleteCustomClassRequest{ // TODO: Fill request struct fields. diff --git a/speech/apiv1p1beta1/doc.go b/speech/apiv1p1beta1/doc.go index 13a140e2f7df..7a11ad4dcf44 100644 --- a/speech/apiv1p1beta1/doc.go +++ b/speech/apiv1p1beta1/doc.go @@ -19,6 +19,8 @@ // // Converts audio to text by applying powerful neural network models. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -28,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package speech // import "cloud.google.com/go/speech/apiv1p1beta1" import ( @@ -48,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/speech/apiv1p1beta1/speech_client.go b/speech/apiv1p1beta1/speech_client.go index 92caf8631fa5..396ebc3d263f 100644 --- a/speech/apiv1p1beta1/speech_client.go +++ b/speech/apiv1p1beta1/speech_client.go @@ -43,7 +43,7 @@ type CallOptions struct { StreamingRecognize []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("speech.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("speech.mtls.googleapis.com:443"), @@ -85,37 +85,115 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Speech-to-Text API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + Recognize(context.Context, *speechpb.RecognizeRequest, ...gax.CallOption) (*speechpb.RecognizeResponse, error) + LongRunningRecognize(context.Context, *speechpb.LongRunningRecognizeRequest, ...gax.CallOption) (*LongRunningRecognizeOperation, error) + LongRunningRecognizeOperation(name string) *LongRunningRecognizeOperation + StreamingRecognize(context.Context, ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) +} + // Client is a client for interacting with Cloud Speech-to-Text API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service that implements Google Cloud Speech API. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// Recognize performs synchronous speech recognition: receive results after all audio +// has been sent and processed. +func (c *Client) Recognize(ctx context.Context, req *speechpb.RecognizeRequest, opts ...gax.CallOption) (*speechpb.RecognizeResponse, error) { + return c.internalClient.Recognize(ctx, req, opts...) +} + +// LongRunningRecognize performs asynchronous speech recognition: receive results via the +// google.longrunning.Operations interface. Returns either an +// Operation.error or an Operation.response which contains +// a LongRunningRecognizeResponse message. +// For more information on asynchronous speech recognition, see the +// how-to (at https://cloud.google.com/speech-to-text/docs/async-recognize). +func (c *Client) LongRunningRecognize(ctx context.Context, req *speechpb.LongRunningRecognizeRequest, opts ...gax.CallOption) (*LongRunningRecognizeOperation, error) { + return c.internalClient.LongRunningRecognize(ctx, req, opts...) +} + +// LongRunningRecognizeOperation returns a new LongRunningRecognizeOperation from a given name. +// The name must be that of a previously created LongRunningRecognizeOperation, possibly from a different process. +func (c *Client) LongRunningRecognizeOperation(name string) *LongRunningRecognizeOperation { + return c.internalClient.LongRunningRecognizeOperation(name) +} + +// StreamingRecognize performs bidirectional streaming speech recognition: receive results while +// sending audio. This method is only available via the gRPC API (not REST). +func (c *Client) StreamingRecognize(ctx context.Context, opts ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) { + return c.internalClient.StreamingRecognize(ctx, opts...) +} + +// gRPCClient is a client for interacting with Cloud Speech-to-Text API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client speechpb.SpeechClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new speech client. +// NewClient creates a new speech client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service that implements Google Cloud Speech API. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -133,16 +211,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: speechpb.NewSpeechClient(connPool), + client: speechpb.NewSpeechClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -152,41 +233,40 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// Recognize performs synchronous speech recognition: receive results after all audio -// has been sent and processed. -func (c *Client) Recognize(ctx context.Context, req *speechpb.RecognizeRequest, opts ...gax.CallOption) (*speechpb.RecognizeResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) Recognize(ctx context.Context, req *speechpb.RecognizeRequest, opts ...gax.CallOption) (*speechpb.RecognizeResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.Recognize[0:len(c.CallOptions.Recognize):len(c.CallOptions.Recognize)], opts...) + opts = append((*c.CallOptions).Recognize[0:len((*c.CallOptions).Recognize):len((*c.CallOptions).Recognize)], opts...) var resp *speechpb.RecognizeResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -199,20 +279,14 @@ func (c *Client) Recognize(ctx context.Context, req *speechpb.RecognizeRequest, return resp, nil } -// LongRunningRecognize performs asynchronous speech recognition: receive results via the -// google.longrunning.Operations interface. Returns either an -// Operation.error or an Operation.response which contains -// a LongRunningRecognizeResponse message. -// For more information on asynchronous speech recognition, see the -// how-to (at https://cloud.google.com/speech-to-text/docs/async-recognize). -func (c *Client) LongRunningRecognize(ctx context.Context, req *speechpb.LongRunningRecognizeRequest, opts ...gax.CallOption) (*LongRunningRecognizeOperation, error) { +func (c *gRPCClient) LongRunningRecognize(ctx context.Context, req *speechpb.LongRunningRecognizeRequest, opts ...gax.CallOption) (*LongRunningRecognizeOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 5000000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.LongRunningRecognize[0:len(c.CallOptions.LongRunningRecognize):len(c.CallOptions.LongRunningRecognize)], opts...) + opts = append((*c.CallOptions).LongRunningRecognize[0:len((*c.CallOptions).LongRunningRecognize):len((*c.CallOptions).LongRunningRecognize)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -223,16 +297,14 @@ func (c *Client) LongRunningRecognize(ctx context.Context, req *speechpb.LongRun return nil, err } return &LongRunningRecognizeOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// StreamingRecognize performs bidirectional streaming speech recognition: receive results while -// sending audio. This method is only available via the gRPC API (not REST). -func (c *Client) StreamingRecognize(ctx context.Context, opts ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) { +func (c *gRPCClient) StreamingRecognize(ctx context.Context, opts ...gax.CallOption) (speechpb.Speech_StreamingRecognizeClient, error) { ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.StreamingRecognize[0:len(c.CallOptions.StreamingRecognize):len(c.CallOptions.StreamingRecognize)], opts...) var resp speechpb.Speech_StreamingRecognizeClient + opts = append((*c.CallOptions).StreamingRecognize[0:len((*c.CallOptions).StreamingRecognize):len((*c.CallOptions).StreamingRecognize)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.client.StreamingRecognize(ctx, settings.GRPC...) @@ -251,9 +323,9 @@ type LongRunningRecognizeOperation struct { // LongRunningRecognizeOperation returns a new LongRunningRecognizeOperation from a given name. // The name must be that of a previously created LongRunningRecognizeOperation, possibly from a different process. -func (c *Client) LongRunningRecognizeOperation(name string) *LongRunningRecognizeOperation { +func (c *gRPCClient) LongRunningRecognizeOperation(name string) *LongRunningRecognizeOperation { return &LongRunningRecognizeOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/speech/apiv1p1beta1/speech_client_example_test.go b/speech/apiv1p1beta1/speech_client_example_test.go index 121bc5f16f6f..db55b79cdbc3 100644 --- a/speech/apiv1p1beta1/speech_client_example_test.go +++ b/speech/apiv1p1beta1/speech_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_Recognize() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.RecognizeRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleClient_Recognize() { } func ExampleClient_LongRunningRecognize() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &speechpb.LongRunningRecognizeRequest{ // TODO: Fill request struct fields. @@ -80,13 +80,12 @@ func ExampleClient_LongRunningRecognize() { } func ExampleClient_StreamingRecognize() { - // import speechpb "google.golang.org/genproto/googleapis/cloud/speech/v1p1beta1" - ctx := context.Background() c, err := speech.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() stream, err := c.StreamingRecognize(ctx) if err != nil { // TODO: Handle error. diff --git a/talent/apiv4/company_client.go b/talent/apiv4/company_client.go index 08b3a538ec51..f50e8cb70f21 100644 --- a/talent/apiv4/company_client.go +++ b/talent/apiv4/company_client.go @@ -46,7 +46,7 @@ type CompanyCallOptions struct { ListCompanies []gax.CallOption } -func defaultCompanyClientOptions() []option.ClientOption { +func defaultCompanyGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("jobs.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("jobs.mtls.googleapis.com:443"), @@ -101,32 +101,104 @@ func defaultCompanyCallOptions() *CompanyCallOptions { } } +// internalCompanyClient is an interface that defines the methods availaible from Cloud Talent Solution API. +type internalCompanyClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateCompany(context.Context, *talentpb.CreateCompanyRequest, ...gax.CallOption) (*talentpb.Company, error) + GetCompany(context.Context, *talentpb.GetCompanyRequest, ...gax.CallOption) (*talentpb.Company, error) + UpdateCompany(context.Context, *talentpb.UpdateCompanyRequest, ...gax.CallOption) (*talentpb.Company, error) + DeleteCompany(context.Context, *talentpb.DeleteCompanyRequest, ...gax.CallOption) error + ListCompanies(context.Context, *talentpb.ListCompaniesRequest, ...gax.CallOption) *CompanyIterator +} + // CompanyClient is a client for interacting with Cloud Talent Solution API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A service that handles company management, including CRUD and enumeration. type CompanyClient struct { + // The internal transport-dependent client. + internalClient internalCompanyClient + + // The call options for this service. + CallOptions *CompanyCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CompanyClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CompanyClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CompanyClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateCompany creates a new company entity. +func (c *CompanyClient) CreateCompany(ctx context.Context, req *talentpb.CreateCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { + return c.internalClient.CreateCompany(ctx, req, opts...) +} + +// GetCompany retrieves specified company. +func (c *CompanyClient) GetCompany(ctx context.Context, req *talentpb.GetCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { + return c.internalClient.GetCompany(ctx, req, opts...) +} + +// UpdateCompany updates specified company. +func (c *CompanyClient) UpdateCompany(ctx context.Context, req *talentpb.UpdateCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { + return c.internalClient.UpdateCompany(ctx, req, opts...) +} + +// DeleteCompany deletes specified company. +// Prerequisite: The company has no jobs associated with it. +func (c *CompanyClient) DeleteCompany(ctx context.Context, req *talentpb.DeleteCompanyRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteCompany(ctx, req, opts...) +} + +// ListCompanies lists all companies associated with the project. +func (c *CompanyClient) ListCompanies(ctx context.Context, req *talentpb.ListCompaniesRequest, opts ...gax.CallOption) *CompanyIterator { + return c.internalClient.ListCompanies(ctx, req, opts...) +} + +// companyGRPCClient is a client for interacting with Cloud Talent Solution API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type companyGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CompanyClient + CallOptions **CompanyCallOptions + // The gRPC API client. companyClient talentpb.CompanyServiceClient - // The call options for this service. - CallOptions *CompanyCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCompanyClient creates a new company service client. +// NewCompanyClient creates a new company service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A service that handles company management, including CRUD and enumeration. func NewCompanyClient(ctx context.Context, opts ...option.ClientOption) (*CompanyClient, error) { - clientOpts := defaultCompanyClientOptions() - + clientOpts := defaultCompanyGRPCClientOptions() if newCompanyClientHook != nil { hookOpts, err := newCompanyClientHook(ctx, clientHookParams{}) if err != nil { @@ -144,42 +216,44 @@ func NewCompanyClient(ctx context.Context, opts ...option.ClientOption) (*Compan if err != nil { return nil, err } - c := &CompanyClient{ + client := CompanyClient{CallOptions: defaultCompanyCallOptions()} + + c := &companyGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCompanyCallOptions(), - - companyClient: talentpb.NewCompanyServiceClient(connPool), + companyClient: talentpb.NewCompanyServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CompanyClient) Connection() *grpc.ClientConn { +func (c *companyGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CompanyClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CompanyClient) setGoogleClientInfo(keyval ...string) { +func (c *companyGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateCompany creates a new company entity. -func (c *CompanyClient) CreateCompany(ctx context.Context, req *talentpb.CreateCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *companyGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *companyGRPCClient) CreateCompany(ctx context.Context, req *talentpb.CreateCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -187,7 +261,7 @@ func (c *CompanyClient) CreateCompany(ctx context.Context, req *talentpb.CreateC } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCompany[0:len(c.CallOptions.CreateCompany):len(c.CallOptions.CreateCompany)], opts...) + opts = append((*c.CallOptions).CreateCompany[0:len((*c.CallOptions).CreateCompany):len((*c.CallOptions).CreateCompany)], opts...) var resp *talentpb.Company err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -200,8 +274,7 @@ func (c *CompanyClient) CreateCompany(ctx context.Context, req *talentpb.CreateC return resp, nil } -// GetCompany retrieves specified company. -func (c *CompanyClient) GetCompany(ctx context.Context, req *talentpb.GetCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { +func (c *companyGRPCClient) GetCompany(ctx context.Context, req *talentpb.GetCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -209,7 +282,7 @@ func (c *CompanyClient) GetCompany(ctx context.Context, req *talentpb.GetCompany } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCompany[0:len(c.CallOptions.GetCompany):len(c.CallOptions.GetCompany)], opts...) + opts = append((*c.CallOptions).GetCompany[0:len((*c.CallOptions).GetCompany):len((*c.CallOptions).GetCompany)], opts...) var resp *talentpb.Company err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -222,8 +295,7 @@ func (c *CompanyClient) GetCompany(ctx context.Context, req *talentpb.GetCompany return resp, nil } -// UpdateCompany updates specified company. -func (c *CompanyClient) UpdateCompany(ctx context.Context, req *talentpb.UpdateCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { +func (c *companyGRPCClient) UpdateCompany(ctx context.Context, req *talentpb.UpdateCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -231,7 +303,7 @@ func (c *CompanyClient) UpdateCompany(ctx context.Context, req *talentpb.UpdateC } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "company.name", url.QueryEscape(req.GetCompany().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCompany[0:len(c.CallOptions.UpdateCompany):len(c.CallOptions.UpdateCompany)], opts...) + opts = append((*c.CallOptions).UpdateCompany[0:len((*c.CallOptions).UpdateCompany):len((*c.CallOptions).UpdateCompany)], opts...) var resp *talentpb.Company err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -244,9 +316,7 @@ func (c *CompanyClient) UpdateCompany(ctx context.Context, req *talentpb.UpdateC return resp, nil } -// DeleteCompany deletes specified company. -// Prerequisite: The company has no jobs associated with it. -func (c *CompanyClient) DeleteCompany(ctx context.Context, req *talentpb.DeleteCompanyRequest, opts ...gax.CallOption) error { +func (c *companyGRPCClient) DeleteCompany(ctx context.Context, req *talentpb.DeleteCompanyRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -254,7 +324,7 @@ func (c *CompanyClient) DeleteCompany(ctx context.Context, req *talentpb.DeleteC } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteCompany[0:len(c.CallOptions.DeleteCompany):len(c.CallOptions.DeleteCompany)], opts...) + opts = append((*c.CallOptions).DeleteCompany[0:len((*c.CallOptions).DeleteCompany):len((*c.CallOptions).DeleteCompany)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.companyClient.DeleteCompany(ctx, req, settings.GRPC...) @@ -263,11 +333,10 @@ func (c *CompanyClient) DeleteCompany(ctx context.Context, req *talentpb.DeleteC return err } -// ListCompanies lists all companies associated with the project. -func (c *CompanyClient) ListCompanies(ctx context.Context, req *talentpb.ListCompaniesRequest, opts ...gax.CallOption) *CompanyIterator { +func (c *companyGRPCClient) ListCompanies(ctx context.Context, req *talentpb.ListCompaniesRequest, opts ...gax.CallOption) *CompanyIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCompanies[0:len(c.CallOptions.ListCompanies):len(c.CallOptions.ListCompanies)], opts...) + opts = append((*c.CallOptions).ListCompanies[0:len((*c.CallOptions).ListCompanies):len((*c.CallOptions).ListCompanies)], opts...) it := &CompanyIterator{} req = proto.Clone(req).(*talentpb.ListCompaniesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*talentpb.Company, string, error) { diff --git a/talent/apiv4/company_client_example_test.go b/talent/apiv4/company_client_example_test.go index 9753bc1c03eb..7af77472227d 100644 --- a/talent/apiv4/company_client_example_test.go +++ b/talent/apiv4/company_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewCompanyClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCompanyClient_CreateCompany() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewCompanyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateCompanyRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleCompanyClient_CreateCompany() { } func ExampleCompanyClient_GetCompany() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewCompanyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.GetCompanyRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleCompanyClient_GetCompany() { } func ExampleCompanyClient_UpdateCompany() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewCompanyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.UpdateCompanyRequest{ // TODO: Fill request struct fields. @@ -100,6 +99,7 @@ func ExampleCompanyClient_DeleteCompany() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.DeleteCompanyRequest{ // TODO: Fill request struct fields. @@ -111,14 +111,12 @@ func ExampleCompanyClient_DeleteCompany() { } func ExampleCompanyClient_ListCompanies() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewCompanyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.ListCompaniesRequest{ // TODO: Fill request struct fields. diff --git a/talent/apiv4/completion_client.go b/talent/apiv4/completion_client.go index 466de52c7aaa..f1b841f26a38 100644 --- a/talent/apiv4/completion_client.go +++ b/talent/apiv4/completion_client.go @@ -40,7 +40,7 @@ type CompletionCallOptions struct { CompleteQuery []gax.CallOption } -func defaultCompletionClientOptions() []option.ClientOption { +func defaultCompletionGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("jobs.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("jobs.mtls.googleapis.com:443"), @@ -69,32 +69,80 @@ func defaultCompletionCallOptions() *CompletionCallOptions { } } +// internalCompletionClient is an interface that defines the methods availaible from Cloud Talent Solution API. +type internalCompletionClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CompleteQuery(context.Context, *talentpb.CompleteQueryRequest, ...gax.CallOption) (*talentpb.CompleteQueryResponse, error) +} + // CompletionClient is a client for interacting with Cloud Talent Solution API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A service handles auto completion. type CompletionClient struct { + // The internal transport-dependent client. + internalClient internalCompletionClient + + // The call options for this service. + CallOptions *CompletionCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CompletionClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CompletionClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CompletionClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CompleteQuery completes the specified prefix with keyword suggestions. +// Intended for use by a job search auto-complete search box. +func (c *CompletionClient) CompleteQuery(ctx context.Context, req *talentpb.CompleteQueryRequest, opts ...gax.CallOption) (*talentpb.CompleteQueryResponse, error) { + return c.internalClient.CompleteQuery(ctx, req, opts...) +} + +// completionGRPCClient is a client for interacting with Cloud Talent Solution API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type completionGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CompletionClient + CallOptions **CompletionCallOptions + // The gRPC API client. completionClient talentpb.CompletionClient - // The call options for this service. - CallOptions *CompletionCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCompletionClient creates a new completion client. +// NewCompletionClient creates a new completion client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A service handles auto completion. func NewCompletionClient(ctx context.Context, opts ...option.ClientOption) (*CompletionClient, error) { - clientOpts := defaultCompletionClientOptions() - + clientOpts := defaultCompletionGRPCClientOptions() if newCompletionClientHook != nil { hookOpts, err := newCompletionClientHook(ctx, clientHookParams{}) if err != nil { @@ -112,43 +160,44 @@ func NewCompletionClient(ctx context.Context, opts ...option.ClientOption) (*Com if err != nil { return nil, err } - c := &CompletionClient{ + client := CompletionClient{CallOptions: defaultCompletionCallOptions()} + + c := &completionGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCompletionCallOptions(), - completionClient: talentpb.NewCompletionClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CompletionClient) Connection() *grpc.ClientConn { +func (c *completionGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CompletionClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CompletionClient) setGoogleClientInfo(keyval ...string) { +func (c *completionGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CompleteQuery completes the specified prefix with keyword suggestions. -// Intended for use by a job search auto-complete search box. -func (c *CompletionClient) CompleteQuery(ctx context.Context, req *talentpb.CompleteQueryRequest, opts ...gax.CallOption) (*talentpb.CompleteQueryResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *completionGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *completionGRPCClient) CompleteQuery(ctx context.Context, req *talentpb.CompleteQueryRequest, opts ...gax.CallOption) (*talentpb.CompleteQueryResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -156,7 +205,7 @@ func (c *CompletionClient) CompleteQuery(ctx context.Context, req *talentpb.Comp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "tenant", url.QueryEscape(req.GetTenant()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CompleteQuery[0:len(c.CallOptions.CompleteQuery):len(c.CallOptions.CompleteQuery)], opts...) + opts = append((*c.CallOptions).CompleteQuery[0:len((*c.CallOptions).CompleteQuery):len((*c.CallOptions).CompleteQuery)], opts...) var resp *talentpb.CompleteQueryResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/talent/apiv4/completion_client_example_test.go b/talent/apiv4/completion_client_example_test.go index fab9cd64e8b3..94f58d70833d 100644 --- a/talent/apiv4/completion_client_example_test.go +++ b/talent/apiv4/completion_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewCompletionClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCompletionClient_CompleteQuery() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewCompletionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CompleteQueryRequest{ // TODO: Fill request struct fields. diff --git a/talent/apiv4/doc.go b/talent/apiv4/doc.go index b65c34a79509..51dbc23b4a5b 100644 --- a/talent/apiv4/doc.go +++ b/talent/apiv4/doc.go @@ -20,6 +20,8 @@ // Cloud Talent Solution provides the capability to create, read, update, and // delete job postings, as well as search jobs based on keywords and filters. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package talent // import "cloud.google.com/go/talent/apiv4" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/talent/apiv4/event_client.go b/talent/apiv4/event_client.go index 35eab5fa75eb..a13ee458dfe5 100644 --- a/talent/apiv4/event_client.go +++ b/talent/apiv4/event_client.go @@ -39,7 +39,7 @@ type EventCallOptions struct { CreateClientEvent []gax.CallOption } -func defaultEventClientOptions() []option.ClientOption { +func defaultEventGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("jobs.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("jobs.mtls.googleapis.com:443"), @@ -57,32 +57,85 @@ func defaultEventCallOptions() *EventCallOptions { } } +// internalEventClient is an interface that defines the methods availaible from Cloud Talent Solution API. +type internalEventClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateClientEvent(context.Context, *talentpb.CreateClientEventRequest, ...gax.CallOption) (*talentpb.ClientEvent, error) +} + // EventClient is a client for interacting with Cloud Talent Solution API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A service handles client event report. type EventClient struct { + // The internal transport-dependent client. + internalClient internalEventClient + + // The call options for this service. + CallOptions *EventCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *EventClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *EventClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *EventClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateClientEvent report events issued when end user interacts with customer’s application +// that uses Cloud Talent Solution. You may inspect the created events in +// self service +// tools (at https://console.cloud.google.com/talent-solution/overview). +// Learn +// more (at https://cloud.google.com/talent-solution/docs/management-tools) +// about self service tools. +func (c *EventClient) CreateClientEvent(ctx context.Context, req *talentpb.CreateClientEventRequest, opts ...gax.CallOption) (*talentpb.ClientEvent, error) { + return c.internalClient.CreateClientEvent(ctx, req, opts...) +} + +// eventGRPCClient is a client for interacting with Cloud Talent Solution API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type eventGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing EventClient + CallOptions **EventCallOptions + // The gRPC API client. eventClient talentpb.EventServiceClient - // The call options for this service. - CallOptions *EventCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewEventClient creates a new event service client. +// NewEventClient creates a new event service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A service handles client event report. func NewEventClient(ctx context.Context, opts ...option.ClientOption) (*EventClient, error) { - clientOpts := defaultEventClientOptions() - + clientOpts := defaultEventGRPCClientOptions() if newEventClientHook != nil { hookOpts, err := newEventClientHook(ctx, clientHookParams{}) if err != nil { @@ -100,48 +153,44 @@ func NewEventClient(ctx context.Context, opts ...option.ClientOption) (*EventCli if err != nil { return nil, err } - c := &EventClient{ + client := EventClient{CallOptions: defaultEventCallOptions()} + + c := &eventGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultEventCallOptions(), - - eventClient: talentpb.NewEventServiceClient(connPool), + eventClient: talentpb.NewEventServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *EventClient) Connection() *grpc.ClientConn { +func (c *eventGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *EventClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *EventClient) setGoogleClientInfo(keyval ...string) { +func (c *eventGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateClientEvent report events issued when end user interacts with customer’s application -// that uses Cloud Talent Solution. You may inspect the created events in -// self service -// tools (at https://console.cloud.google.com/talent-solution/overview). -// Learn -// more (at https://cloud.google.com/talent-solution/docs/management-tools) -// about self service tools. -func (c *EventClient) CreateClientEvent(ctx context.Context, req *talentpb.CreateClientEventRequest, opts ...gax.CallOption) (*talentpb.ClientEvent, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *eventGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *eventGRPCClient) CreateClientEvent(ctx context.Context, req *talentpb.CreateClientEventRequest, opts ...gax.CallOption) (*talentpb.ClientEvent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -149,7 +198,7 @@ func (c *EventClient) CreateClientEvent(ctx context.Context, req *talentpb.Creat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateClientEvent[0:len(c.CallOptions.CreateClientEvent):len(c.CallOptions.CreateClientEvent)], opts...) + opts = append((*c.CallOptions).CreateClientEvent[0:len((*c.CallOptions).CreateClientEvent):len((*c.CallOptions).CreateClientEvent)], opts...) var resp *talentpb.ClientEvent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/talent/apiv4/event_client_example_test.go b/talent/apiv4/event_client_example_test.go index ce20e6663fbc..ce61f8bcc3ab 100644 --- a/talent/apiv4/event_client_example_test.go +++ b/talent/apiv4/event_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewEventClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleEventClient_CreateClientEvent() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateClientEventRequest{ // TODO: Fill request struct fields. diff --git a/talent/apiv4/job_client.go b/talent/apiv4/job_client.go index 1f0aecbda3a1..3504b278988e 100644 --- a/talent/apiv4/job_client.go +++ b/talent/apiv4/job_client.go @@ -54,7 +54,7 @@ type JobCallOptions struct { SearchJobsForAlert []gax.CallOption } -func defaultJobClientOptions() []option.ClientOption { +func defaultJobGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("jobs.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("jobs.mtls.googleapis.com:443"), @@ -114,37 +114,187 @@ func defaultJobCallOptions() *JobCallOptions { } } +// internalJobClient is an interface that defines the methods availaible from Cloud Talent Solution API. +type internalJobClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateJob(context.Context, *talentpb.CreateJobRequest, ...gax.CallOption) (*talentpb.Job, error) + BatchCreateJobs(context.Context, *talentpb.BatchCreateJobsRequest, ...gax.CallOption) (*BatchCreateJobsOperation, error) + BatchCreateJobsOperation(name string) *BatchCreateJobsOperation + GetJob(context.Context, *talentpb.GetJobRequest, ...gax.CallOption) (*talentpb.Job, error) + UpdateJob(context.Context, *talentpb.UpdateJobRequest, ...gax.CallOption) (*talentpb.Job, error) + BatchUpdateJobs(context.Context, *talentpb.BatchUpdateJobsRequest, ...gax.CallOption) (*BatchUpdateJobsOperation, error) + BatchUpdateJobsOperation(name string) *BatchUpdateJobsOperation + DeleteJob(context.Context, *talentpb.DeleteJobRequest, ...gax.CallOption) error + BatchDeleteJobs(context.Context, *talentpb.BatchDeleteJobsRequest, ...gax.CallOption) (*BatchDeleteJobsOperation, error) + BatchDeleteJobsOperation(name string) *BatchDeleteJobsOperation + ListJobs(context.Context, *talentpb.ListJobsRequest, ...gax.CallOption) *JobIterator + SearchJobs(context.Context, *talentpb.SearchJobsRequest, ...gax.CallOption) (*talentpb.SearchJobsResponse, error) + SearchJobsForAlert(context.Context, *talentpb.SearchJobsRequest, ...gax.CallOption) (*talentpb.SearchJobsResponse, error) +} + // JobClient is a client for interacting with Cloud Talent Solution API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A service handles job management, including job CRUD, enumeration and search. type JobClient struct { + // The internal transport-dependent client. + internalClient internalJobClient + + // The call options for this service. + CallOptions *JobCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *JobClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *JobClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *JobClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateJob creates a new job. +// +// Typically, the job becomes searchable within 10 seconds, but it may take +// up to 5 minutes. +func (c *JobClient) CreateJob(ctx context.Context, req *talentpb.CreateJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { + return c.internalClient.CreateJob(ctx, req, opts...) +} + +// BatchCreateJobs begins executing a batch create jobs operation. +func (c *JobClient) BatchCreateJobs(ctx context.Context, req *talentpb.BatchCreateJobsRequest, opts ...gax.CallOption) (*BatchCreateJobsOperation, error) { + return c.internalClient.BatchCreateJobs(ctx, req, opts...) +} + +// BatchCreateJobsOperation returns a new BatchCreateJobsOperation from a given name. +// The name must be that of a previously created BatchCreateJobsOperation, possibly from a different process. +func (c *JobClient) BatchCreateJobsOperation(name string) *BatchCreateJobsOperation { + return c.internalClient.BatchCreateJobsOperation(name) +} + +// GetJob retrieves the specified job, whose status is OPEN or recently EXPIRED +// within the last 90 days. +func (c *JobClient) GetJob(ctx context.Context, req *talentpb.GetJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { + return c.internalClient.GetJob(ctx, req, opts...) +} + +// UpdateJob updates specified job. +// +// Typically, updated contents become visible in search results within 10 +// seconds, but it may take up to 5 minutes. +func (c *JobClient) UpdateJob(ctx context.Context, req *talentpb.UpdateJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { + return c.internalClient.UpdateJob(ctx, req, opts...) +} + +// BatchUpdateJobs begins executing a batch update jobs operation. +func (c *JobClient) BatchUpdateJobs(ctx context.Context, req *talentpb.BatchUpdateJobsRequest, opts ...gax.CallOption) (*BatchUpdateJobsOperation, error) { + return c.internalClient.BatchUpdateJobs(ctx, req, opts...) +} + +// BatchUpdateJobsOperation returns a new BatchUpdateJobsOperation from a given name. +// The name must be that of a previously created BatchUpdateJobsOperation, possibly from a different process. +func (c *JobClient) BatchUpdateJobsOperation(name string) *BatchUpdateJobsOperation { + return c.internalClient.BatchUpdateJobsOperation(name) +} + +// DeleteJob deletes the specified job. +// +// Typically, the job becomes unsearchable within 10 seconds, but it may take +// up to 5 minutes. +func (c *JobClient) DeleteJob(ctx context.Context, req *talentpb.DeleteJobRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteJob(ctx, req, opts...) +} + +// BatchDeleteJobs begins executing a batch delete jobs operation. +func (c *JobClient) BatchDeleteJobs(ctx context.Context, req *talentpb.BatchDeleteJobsRequest, opts ...gax.CallOption) (*BatchDeleteJobsOperation, error) { + return c.internalClient.BatchDeleteJobs(ctx, req, opts...) +} + +// BatchDeleteJobsOperation returns a new BatchDeleteJobsOperation from a given name. +// The name must be that of a previously created BatchDeleteJobsOperation, possibly from a different process. +func (c *JobClient) BatchDeleteJobsOperation(name string) *BatchDeleteJobsOperation { + return c.internalClient.BatchDeleteJobsOperation(name) +} + +// ListJobs lists jobs by filter. +func (c *JobClient) ListJobs(ctx context.Context, req *talentpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { + return c.internalClient.ListJobs(ctx, req, opts...) +} + +// SearchJobs searches for jobs using the provided SearchJobsRequest. +// +// This call constrains the visibility of jobs +// present in the database, and only returns jobs that the caller has +// permission to search against. +func (c *JobClient) SearchJobs(ctx context.Context, req *talentpb.SearchJobsRequest, opts ...gax.CallOption) (*talentpb.SearchJobsResponse, error) { + return c.internalClient.SearchJobs(ctx, req, opts...) +} + +// SearchJobsForAlert searches for jobs using the provided SearchJobsRequest. +// +// This API call is intended for the use case of targeting passive job +// seekers (for example, job seekers who have signed up to receive email +// alerts about potential job opportunities), it has different algorithmic +// adjustments that are designed to specifically target passive job seekers. +// +// This call constrains the visibility of jobs +// present in the database, and only returns jobs the caller has +// permission to search against. +func (c *JobClient) SearchJobsForAlert(ctx context.Context, req *talentpb.SearchJobsRequest, opts ...gax.CallOption) (*talentpb.SearchJobsResponse, error) { + return c.internalClient.SearchJobsForAlert(ctx, req, opts...) +} + +// jobGRPCClient is a client for interacting with Cloud Talent Solution API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type jobGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing JobClient + CallOptions **JobCallOptions + // The gRPC API client. jobClient talentpb.JobServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *JobCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewJobClient creates a new job service client. +// NewJobClient creates a new job service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A service handles job management, including job CRUD, enumeration and search. func NewJobClient(ctx context.Context, opts ...option.ClientOption) (*JobClient, error) { - clientOpts := defaultJobClientOptions() - + clientOpts := defaultJobGRPCClientOptions() if newJobClientHook != nil { hookOpts, err := newJobClientHook(ctx, clientHookParams{}) if err != nil { @@ -162,16 +312,19 @@ func NewJobClient(ctx context.Context, opts ...option.ClientOption) (*JobClient, if err != nil { return nil, err } - c := &JobClient{ + client := JobClient{CallOptions: defaultJobCallOptions()} + + c := &jobGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultJobCallOptions(), - - jobClient: talentpb.NewJobServiceClient(connPool), + jobClient: talentpb.NewJobServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -181,36 +334,33 @@ func NewJobClient(ctx context.Context, opts ...option.ClientOption) (*JobClient, // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *JobClient) Connection() *grpc.ClientConn { +func (c *jobGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *JobClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *JobClient) setGoogleClientInfo(keyval ...string) { +func (c *jobGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateJob creates a new job. -// -// Typically, the job becomes searchable within 10 seconds, but it may take -// up to 5 minutes. -func (c *JobClient) CreateJob(ctx context.Context, req *talentpb.CreateJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *jobGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *jobGRPCClient) CreateJob(ctx context.Context, req *talentpb.CreateJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -218,7 +368,7 @@ func (c *JobClient) CreateJob(ctx context.Context, req *talentpb.CreateJobReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateJob[0:len(c.CallOptions.CreateJob):len(c.CallOptions.CreateJob)], opts...) + opts = append((*c.CallOptions).CreateJob[0:len((*c.CallOptions).CreateJob):len((*c.CallOptions).CreateJob)], opts...) var resp *talentpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -231,8 +381,7 @@ func (c *JobClient) CreateJob(ctx context.Context, req *talentpb.CreateJobReques return resp, nil } -// BatchCreateJobs begins executing a batch create jobs operation. -func (c *JobClient) BatchCreateJobs(ctx context.Context, req *talentpb.BatchCreateJobsRequest, opts ...gax.CallOption) (*BatchCreateJobsOperation, error) { +func (c *jobGRPCClient) BatchCreateJobs(ctx context.Context, req *talentpb.BatchCreateJobsRequest, opts ...gax.CallOption) (*BatchCreateJobsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -240,7 +389,7 @@ func (c *JobClient) BatchCreateJobs(ctx context.Context, req *talentpb.BatchCrea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchCreateJobs[0:len(c.CallOptions.BatchCreateJobs):len(c.CallOptions.BatchCreateJobs)], opts...) + opts = append((*c.CallOptions).BatchCreateJobs[0:len((*c.CallOptions).BatchCreateJobs):len((*c.CallOptions).BatchCreateJobs)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -251,13 +400,11 @@ func (c *JobClient) BatchCreateJobs(ctx context.Context, req *talentpb.BatchCrea return nil, err } return &BatchCreateJobsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetJob retrieves the specified job, whose status is OPEN or recently EXPIRED -// within the last 90 days. -func (c *JobClient) GetJob(ctx context.Context, req *talentpb.GetJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { +func (c *jobGRPCClient) GetJob(ctx context.Context, req *talentpb.GetJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -265,7 +412,7 @@ func (c *JobClient) GetJob(ctx context.Context, req *talentpb.GetJobRequest, opt } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetJob[0:len(c.CallOptions.GetJob):len(c.CallOptions.GetJob)], opts...) + opts = append((*c.CallOptions).GetJob[0:len((*c.CallOptions).GetJob):len((*c.CallOptions).GetJob)], opts...) var resp *talentpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -278,11 +425,7 @@ func (c *JobClient) GetJob(ctx context.Context, req *talentpb.GetJobRequest, opt return resp, nil } -// UpdateJob updates specified job. -// -// Typically, updated contents become visible in search results within 10 -// seconds, but it may take up to 5 minutes. -func (c *JobClient) UpdateJob(ctx context.Context, req *talentpb.UpdateJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { +func (c *jobGRPCClient) UpdateJob(ctx context.Context, req *talentpb.UpdateJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -290,7 +433,7 @@ func (c *JobClient) UpdateJob(ctx context.Context, req *talentpb.UpdateJobReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "job.name", url.QueryEscape(req.GetJob().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateJob[0:len(c.CallOptions.UpdateJob):len(c.CallOptions.UpdateJob)], opts...) + opts = append((*c.CallOptions).UpdateJob[0:len((*c.CallOptions).UpdateJob):len((*c.CallOptions).UpdateJob)], opts...) var resp *talentpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -303,8 +446,7 @@ func (c *JobClient) UpdateJob(ctx context.Context, req *talentpb.UpdateJobReques return resp, nil } -// BatchUpdateJobs begins executing a batch update jobs operation. -func (c *JobClient) BatchUpdateJobs(ctx context.Context, req *talentpb.BatchUpdateJobsRequest, opts ...gax.CallOption) (*BatchUpdateJobsOperation, error) { +func (c *jobGRPCClient) BatchUpdateJobs(ctx context.Context, req *talentpb.BatchUpdateJobsRequest, opts ...gax.CallOption) (*BatchUpdateJobsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -312,7 +454,7 @@ func (c *JobClient) BatchUpdateJobs(ctx context.Context, req *talentpb.BatchUpda } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchUpdateJobs[0:len(c.CallOptions.BatchUpdateJobs):len(c.CallOptions.BatchUpdateJobs)], opts...) + opts = append((*c.CallOptions).BatchUpdateJobs[0:len((*c.CallOptions).BatchUpdateJobs):len((*c.CallOptions).BatchUpdateJobs)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -323,15 +465,11 @@ func (c *JobClient) BatchUpdateJobs(ctx context.Context, req *talentpb.BatchUpda return nil, err } return &BatchUpdateJobsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteJob deletes the specified job. -// -// Typically, the job becomes unsearchable within 10 seconds, but it may take -// up to 5 minutes. -func (c *JobClient) DeleteJob(ctx context.Context, req *talentpb.DeleteJobRequest, opts ...gax.CallOption) error { +func (c *jobGRPCClient) DeleteJob(ctx context.Context, req *talentpb.DeleteJobRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -339,7 +477,7 @@ func (c *JobClient) DeleteJob(ctx context.Context, req *talentpb.DeleteJobReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteJob[0:len(c.CallOptions.DeleteJob):len(c.CallOptions.DeleteJob)], opts...) + opts = append((*c.CallOptions).DeleteJob[0:len((*c.CallOptions).DeleteJob):len((*c.CallOptions).DeleteJob)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.jobClient.DeleteJob(ctx, req, settings.GRPC...) @@ -348,8 +486,7 @@ func (c *JobClient) DeleteJob(ctx context.Context, req *talentpb.DeleteJobReques return err } -// BatchDeleteJobs begins executing a batch delete jobs operation. -func (c *JobClient) BatchDeleteJobs(ctx context.Context, req *talentpb.BatchDeleteJobsRequest, opts ...gax.CallOption) (*BatchDeleteJobsOperation, error) { +func (c *jobGRPCClient) BatchDeleteJobs(ctx context.Context, req *talentpb.BatchDeleteJobsRequest, opts ...gax.CallOption) (*BatchDeleteJobsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -357,7 +494,7 @@ func (c *JobClient) BatchDeleteJobs(ctx context.Context, req *talentpb.BatchDele } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchDeleteJobs[0:len(c.CallOptions.BatchDeleteJobs):len(c.CallOptions.BatchDeleteJobs)], opts...) + opts = append((*c.CallOptions).BatchDeleteJobs[0:len((*c.CallOptions).BatchDeleteJobs):len((*c.CallOptions).BatchDeleteJobs)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -368,15 +505,14 @@ func (c *JobClient) BatchDeleteJobs(ctx context.Context, req *talentpb.BatchDele return nil, err } return &BatchDeleteJobsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListJobs lists jobs by filter. -func (c *JobClient) ListJobs(ctx context.Context, req *talentpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { +func (c *jobGRPCClient) ListJobs(ctx context.Context, req *talentpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListJobs[0:len(c.CallOptions.ListJobs):len(c.CallOptions.ListJobs)], opts...) + opts = append((*c.CallOptions).ListJobs[0:len((*c.CallOptions).ListJobs):len((*c.CallOptions).ListJobs)], opts...) it := &JobIterator{} req = proto.Clone(req).(*talentpb.ListJobsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*talentpb.Job, string, error) { @@ -413,12 +549,7 @@ func (c *JobClient) ListJobs(ctx context.Context, req *talentpb.ListJobsRequest, return it } -// SearchJobs searches for jobs using the provided SearchJobsRequest. -// -// This call constrains the visibility of jobs -// present in the database, and only returns jobs that the caller has -// permission to search against. -func (c *JobClient) SearchJobs(ctx context.Context, req *talentpb.SearchJobsRequest, opts ...gax.CallOption) (*talentpb.SearchJobsResponse, error) { +func (c *jobGRPCClient) SearchJobs(ctx context.Context, req *talentpb.SearchJobsRequest, opts ...gax.CallOption) (*talentpb.SearchJobsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -426,7 +557,7 @@ func (c *JobClient) SearchJobs(ctx context.Context, req *talentpb.SearchJobsRequ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SearchJobs[0:len(c.CallOptions.SearchJobs):len(c.CallOptions.SearchJobs)], opts...) + opts = append((*c.CallOptions).SearchJobs[0:len((*c.CallOptions).SearchJobs):len((*c.CallOptions).SearchJobs)], opts...) var resp *talentpb.SearchJobsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -439,17 +570,7 @@ func (c *JobClient) SearchJobs(ctx context.Context, req *talentpb.SearchJobsRequ return resp, nil } -// SearchJobsForAlert searches for jobs using the provided SearchJobsRequest. -// -// This API call is intended for the use case of targeting passive job -// seekers (for example, job seekers who have signed up to receive email -// alerts about potential job opportunities), it has different algorithmic -// adjustments that are designed to specifically target passive job seekers. -// -// This call constrains the visibility of jobs -// present in the database, and only returns jobs the caller has -// permission to search against. -func (c *JobClient) SearchJobsForAlert(ctx context.Context, req *talentpb.SearchJobsRequest, opts ...gax.CallOption) (*talentpb.SearchJobsResponse, error) { +func (c *jobGRPCClient) SearchJobsForAlert(ctx context.Context, req *talentpb.SearchJobsRequest, opts ...gax.CallOption) (*talentpb.SearchJobsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -457,7 +578,7 @@ func (c *JobClient) SearchJobsForAlert(ctx context.Context, req *talentpb.Search } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SearchJobsForAlert[0:len(c.CallOptions.SearchJobsForAlert):len(c.CallOptions.SearchJobsForAlert)], opts...) + opts = append((*c.CallOptions).SearchJobsForAlert[0:len((*c.CallOptions).SearchJobsForAlert):len((*c.CallOptions).SearchJobsForAlert)], opts...) var resp *talentpb.SearchJobsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -477,9 +598,9 @@ type BatchCreateJobsOperation struct { // BatchCreateJobsOperation returns a new BatchCreateJobsOperation from a given name. // The name must be that of a previously created BatchCreateJobsOperation, possibly from a different process. -func (c *JobClient) BatchCreateJobsOperation(name string) *BatchCreateJobsOperation { +func (c *jobGRPCClient) BatchCreateJobsOperation(name string) *BatchCreateJobsOperation { return &BatchCreateJobsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -546,9 +667,9 @@ type BatchDeleteJobsOperation struct { // BatchDeleteJobsOperation returns a new BatchDeleteJobsOperation from a given name. // The name must be that of a previously created BatchDeleteJobsOperation, possibly from a different process. -func (c *JobClient) BatchDeleteJobsOperation(name string) *BatchDeleteJobsOperation { +func (c *jobGRPCClient) BatchDeleteJobsOperation(name string) *BatchDeleteJobsOperation { return &BatchDeleteJobsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -615,9 +736,9 @@ type BatchUpdateJobsOperation struct { // BatchUpdateJobsOperation returns a new BatchUpdateJobsOperation from a given name. // The name must be that of a previously created BatchUpdateJobsOperation, possibly from a different process. -func (c *JobClient) BatchUpdateJobsOperation(name string) *BatchUpdateJobsOperation { +func (c *jobGRPCClient) BatchUpdateJobsOperation(name string) *BatchUpdateJobsOperation { return &BatchUpdateJobsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/talent/apiv4/job_client_example_test.go b/talent/apiv4/job_client_example_test.go index 460b0c6c9e5f..3824c08accdd 100644 --- a/talent/apiv4/job_client_example_test.go +++ b/talent/apiv4/job_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewJobClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleJobClient_CreateJob() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateJobRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleJobClient_CreateJob() { } func ExampleJobClient_BatchCreateJobs() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.BatchCreateJobsRequest{ // TODO: Fill request struct fields. @@ -80,13 +80,12 @@ func ExampleJobClient_BatchCreateJobs() { } func ExampleJobClient_GetJob() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.GetJobRequest{ // TODO: Fill request struct fields. @@ -100,13 +99,12 @@ func ExampleJobClient_GetJob() { } func ExampleJobClient_UpdateJob() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.UpdateJobRequest{ // TODO: Fill request struct fields. @@ -120,13 +118,12 @@ func ExampleJobClient_UpdateJob() { } func ExampleJobClient_BatchUpdateJobs() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.BatchUpdateJobsRequest{ // TODO: Fill request struct fields. @@ -150,6 +147,7 @@ func ExampleJobClient_DeleteJob() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.DeleteJobRequest{ // TODO: Fill request struct fields. @@ -161,13 +159,12 @@ func ExampleJobClient_DeleteJob() { } func ExampleJobClient_BatchDeleteJobs() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.BatchDeleteJobsRequest{ // TODO: Fill request struct fields. @@ -186,14 +183,12 @@ func ExampleJobClient_BatchDeleteJobs() { } func ExampleJobClient_ListJobs() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.ListJobsRequest{ // TODO: Fill request struct fields. @@ -213,13 +208,12 @@ func ExampleJobClient_ListJobs() { } func ExampleJobClient_SearchJobs() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.SearchJobsRequest{ // TODO: Fill request struct fields. @@ -233,13 +227,12 @@ func ExampleJobClient_SearchJobs() { } func ExampleJobClient_SearchJobsForAlert() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.SearchJobsRequest{ // TODO: Fill request struct fields. diff --git a/talent/apiv4/tenant_client.go b/talent/apiv4/tenant_client.go index 30fed0e3441a..62bb857c11f5 100644 --- a/talent/apiv4/tenant_client.go +++ b/talent/apiv4/tenant_client.go @@ -46,7 +46,7 @@ type TenantCallOptions struct { ListTenants []gax.CallOption } -func defaultTenantClientOptions() []option.ClientOption { +func defaultTenantGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("jobs.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("jobs.mtls.googleapis.com:443"), @@ -101,32 +101,103 @@ func defaultTenantCallOptions() *TenantCallOptions { } } +// internalTenantClient is an interface that defines the methods availaible from Cloud Talent Solution API. +type internalTenantClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateTenant(context.Context, *talentpb.CreateTenantRequest, ...gax.CallOption) (*talentpb.Tenant, error) + GetTenant(context.Context, *talentpb.GetTenantRequest, ...gax.CallOption) (*talentpb.Tenant, error) + UpdateTenant(context.Context, *talentpb.UpdateTenantRequest, ...gax.CallOption) (*talentpb.Tenant, error) + DeleteTenant(context.Context, *talentpb.DeleteTenantRequest, ...gax.CallOption) error + ListTenants(context.Context, *talentpb.ListTenantsRequest, ...gax.CallOption) *TenantIterator +} + // TenantClient is a client for interacting with Cloud Talent Solution API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A service that handles tenant management, including CRUD and enumeration. type TenantClient struct { + // The internal transport-dependent client. + internalClient internalTenantClient + + // The call options for this service. + CallOptions *TenantCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *TenantClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *TenantClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *TenantClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateTenant creates a new tenant entity. +func (c *TenantClient) CreateTenant(ctx context.Context, req *talentpb.CreateTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { + return c.internalClient.CreateTenant(ctx, req, opts...) +} + +// GetTenant retrieves specified tenant. +func (c *TenantClient) GetTenant(ctx context.Context, req *talentpb.GetTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { + return c.internalClient.GetTenant(ctx, req, opts...) +} + +// UpdateTenant updates specified tenant. +func (c *TenantClient) UpdateTenant(ctx context.Context, req *talentpb.UpdateTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { + return c.internalClient.UpdateTenant(ctx, req, opts...) +} + +// DeleteTenant deletes specified tenant. +func (c *TenantClient) DeleteTenant(ctx context.Context, req *talentpb.DeleteTenantRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTenant(ctx, req, opts...) +} + +// ListTenants lists all tenants associated with the project. +func (c *TenantClient) ListTenants(ctx context.Context, req *talentpb.ListTenantsRequest, opts ...gax.CallOption) *TenantIterator { + return c.internalClient.ListTenants(ctx, req, opts...) +} + +// tenantGRPCClient is a client for interacting with Cloud Talent Solution API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type tenantGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing TenantClient + CallOptions **TenantCallOptions + // The gRPC API client. tenantClient talentpb.TenantServiceClient - // The call options for this service. - CallOptions *TenantCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewTenantClient creates a new tenant service client. +// NewTenantClient creates a new tenant service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A service that handles tenant management, including CRUD and enumeration. func NewTenantClient(ctx context.Context, opts ...option.ClientOption) (*TenantClient, error) { - clientOpts := defaultTenantClientOptions() - + clientOpts := defaultTenantGRPCClientOptions() if newTenantClientHook != nil { hookOpts, err := newTenantClientHook(ctx, clientHookParams{}) if err != nil { @@ -144,42 +215,44 @@ func NewTenantClient(ctx context.Context, opts ...option.ClientOption) (*TenantC if err != nil { return nil, err } - c := &TenantClient{ + client := TenantClient{CallOptions: defaultTenantCallOptions()} + + c := &tenantGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultTenantCallOptions(), - - tenantClient: talentpb.NewTenantServiceClient(connPool), + tenantClient: talentpb.NewTenantServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *TenantClient) Connection() *grpc.ClientConn { +func (c *tenantGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *TenantClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *TenantClient) setGoogleClientInfo(keyval ...string) { +func (c *tenantGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateTenant creates a new tenant entity. -func (c *TenantClient) CreateTenant(ctx context.Context, req *talentpb.CreateTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *tenantGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *tenantGRPCClient) CreateTenant(ctx context.Context, req *talentpb.CreateTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -187,7 +260,7 @@ func (c *TenantClient) CreateTenant(ctx context.Context, req *talentpb.CreateTen } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTenant[0:len(c.CallOptions.CreateTenant):len(c.CallOptions.CreateTenant)], opts...) + opts = append((*c.CallOptions).CreateTenant[0:len((*c.CallOptions).CreateTenant):len((*c.CallOptions).CreateTenant)], opts...) var resp *talentpb.Tenant err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -200,8 +273,7 @@ func (c *TenantClient) CreateTenant(ctx context.Context, req *talentpb.CreateTen return resp, nil } -// GetTenant retrieves specified tenant. -func (c *TenantClient) GetTenant(ctx context.Context, req *talentpb.GetTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { +func (c *tenantGRPCClient) GetTenant(ctx context.Context, req *talentpb.GetTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -209,7 +281,7 @@ func (c *TenantClient) GetTenant(ctx context.Context, req *talentpb.GetTenantReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTenant[0:len(c.CallOptions.GetTenant):len(c.CallOptions.GetTenant)], opts...) + opts = append((*c.CallOptions).GetTenant[0:len((*c.CallOptions).GetTenant):len((*c.CallOptions).GetTenant)], opts...) var resp *talentpb.Tenant err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -222,8 +294,7 @@ func (c *TenantClient) GetTenant(ctx context.Context, req *talentpb.GetTenantReq return resp, nil } -// UpdateTenant updates specified tenant. -func (c *TenantClient) UpdateTenant(ctx context.Context, req *talentpb.UpdateTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { +func (c *tenantGRPCClient) UpdateTenant(ctx context.Context, req *talentpb.UpdateTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -231,7 +302,7 @@ func (c *TenantClient) UpdateTenant(ctx context.Context, req *talentpb.UpdateTen } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "tenant.name", url.QueryEscape(req.GetTenant().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTenant[0:len(c.CallOptions.UpdateTenant):len(c.CallOptions.UpdateTenant)], opts...) + opts = append((*c.CallOptions).UpdateTenant[0:len((*c.CallOptions).UpdateTenant):len((*c.CallOptions).UpdateTenant)], opts...) var resp *talentpb.Tenant err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -244,8 +315,7 @@ func (c *TenantClient) UpdateTenant(ctx context.Context, req *talentpb.UpdateTen return resp, nil } -// DeleteTenant deletes specified tenant. -func (c *TenantClient) DeleteTenant(ctx context.Context, req *talentpb.DeleteTenantRequest, opts ...gax.CallOption) error { +func (c *tenantGRPCClient) DeleteTenant(ctx context.Context, req *talentpb.DeleteTenantRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -253,7 +323,7 @@ func (c *TenantClient) DeleteTenant(ctx context.Context, req *talentpb.DeleteTen } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTenant[0:len(c.CallOptions.DeleteTenant):len(c.CallOptions.DeleteTenant)], opts...) + opts = append((*c.CallOptions).DeleteTenant[0:len((*c.CallOptions).DeleteTenant):len((*c.CallOptions).DeleteTenant)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.tenantClient.DeleteTenant(ctx, req, settings.GRPC...) @@ -262,11 +332,10 @@ func (c *TenantClient) DeleteTenant(ctx context.Context, req *talentpb.DeleteTen return err } -// ListTenants lists all tenants associated with the project. -func (c *TenantClient) ListTenants(ctx context.Context, req *talentpb.ListTenantsRequest, opts ...gax.CallOption) *TenantIterator { +func (c *tenantGRPCClient) ListTenants(ctx context.Context, req *talentpb.ListTenantsRequest, opts ...gax.CallOption) *TenantIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTenants[0:len(c.CallOptions.ListTenants):len(c.CallOptions.ListTenants)], opts...) + opts = append((*c.CallOptions).ListTenants[0:len((*c.CallOptions).ListTenants):len((*c.CallOptions).ListTenants)], opts...) it := &TenantIterator{} req = proto.Clone(req).(*talentpb.ListTenantsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*talentpb.Tenant, string, error) { diff --git a/talent/apiv4/tenant_client_example_test.go b/talent/apiv4/tenant_client_example_test.go index 859318c00da6..56d1ec8f2f88 100644 --- a/talent/apiv4/tenant_client_example_test.go +++ b/talent/apiv4/tenant_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewTenantClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleTenantClient_CreateTenant() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewTenantClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateTenantRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleTenantClient_CreateTenant() { } func ExampleTenantClient_GetTenant() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewTenantClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.GetTenantRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleTenantClient_GetTenant() { } func ExampleTenantClient_UpdateTenant() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - ctx := context.Background() c, err := talent.NewTenantClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.UpdateTenantRequest{ // TODO: Fill request struct fields. @@ -100,6 +99,7 @@ func ExampleTenantClient_DeleteTenant() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.DeleteTenantRequest{ // TODO: Fill request struct fields. @@ -111,14 +111,12 @@ func ExampleTenantClient_DeleteTenant() { } func ExampleTenantClient_ListTenants() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewTenantClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.ListTenantsRequest{ // TODO: Fill request struct fields. diff --git a/talent/apiv4beta1/application_client.go b/talent/apiv4beta1/application_client.go index d795388bbc22..c8f9c8e26840 100644 --- a/talent/apiv4beta1/application_client.go +++ b/talent/apiv4beta1/application_client.go @@ -46,7 +46,7 @@ type ApplicationCallOptions struct { ListApplications []gax.CallOption } -func defaultApplicationClientOptions() []option.ClientOption { +func defaultApplicationGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("jobs.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("jobs.mtls.googleapis.com:443"), @@ -101,33 +101,105 @@ func defaultApplicationCallOptions() *ApplicationCallOptions { } } +// internalApplicationClient is an interface that defines the methods availaible from Cloud Talent Solution API. +type internalApplicationClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateApplication(context.Context, *talentpb.CreateApplicationRequest, ...gax.CallOption) (*talentpb.Application, error) + GetApplication(context.Context, *talentpb.GetApplicationRequest, ...gax.CallOption) (*talentpb.Application, error) + UpdateApplication(context.Context, *talentpb.UpdateApplicationRequest, ...gax.CallOption) (*talentpb.Application, error) + DeleteApplication(context.Context, *talentpb.DeleteApplicationRequest, ...gax.CallOption) error + ListApplications(context.Context, *talentpb.ListApplicationsRequest, ...gax.CallOption) *ApplicationIterator +} + // ApplicationClient is a client for interacting with Cloud Talent Solution API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A service that handles application management, including CRUD and +// enumeration. type ApplicationClient struct { + // The internal transport-dependent client. + internalClient internalApplicationClient + + // The call options for this service. + CallOptions *ApplicationCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ApplicationClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ApplicationClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ApplicationClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateApplication creates a new application entity. +func (c *ApplicationClient) CreateApplication(ctx context.Context, req *talentpb.CreateApplicationRequest, opts ...gax.CallOption) (*talentpb.Application, error) { + return c.internalClient.CreateApplication(ctx, req, opts...) +} + +// GetApplication retrieves specified application. +func (c *ApplicationClient) GetApplication(ctx context.Context, req *talentpb.GetApplicationRequest, opts ...gax.CallOption) (*talentpb.Application, error) { + return c.internalClient.GetApplication(ctx, req, opts...) +} + +// UpdateApplication updates specified application. +func (c *ApplicationClient) UpdateApplication(ctx context.Context, req *talentpb.UpdateApplicationRequest, opts ...gax.CallOption) (*talentpb.Application, error) { + return c.internalClient.UpdateApplication(ctx, req, opts...) +} + +// DeleteApplication deletes specified application. +func (c *ApplicationClient) DeleteApplication(ctx context.Context, req *talentpb.DeleteApplicationRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteApplication(ctx, req, opts...) +} + +// ListApplications lists all applications associated with the profile. +func (c *ApplicationClient) ListApplications(ctx context.Context, req *talentpb.ListApplicationsRequest, opts ...gax.CallOption) *ApplicationIterator { + return c.internalClient.ListApplications(ctx, req, opts...) +} + +// applicationGRPCClient is a client for interacting with Cloud Talent Solution API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type applicationGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ApplicationClient + CallOptions **ApplicationCallOptions + // The gRPC API client. applicationClient talentpb.ApplicationServiceClient - // The call options for this service. - CallOptions *ApplicationCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewApplicationClient creates a new application service client. +// NewApplicationClient creates a new application service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A service that handles application management, including CRUD and // enumeration. func NewApplicationClient(ctx context.Context, opts ...option.ClientOption) (*ApplicationClient, error) { - clientOpts := defaultApplicationClientOptions() - + clientOpts := defaultApplicationGRPCClientOptions() if newApplicationClientHook != nil { hookOpts, err := newApplicationClientHook(ctx, clientHookParams{}) if err != nil { @@ -145,42 +217,44 @@ func NewApplicationClient(ctx context.Context, opts ...option.ClientOption) (*Ap if err != nil { return nil, err } - c := &ApplicationClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultApplicationCallOptions(), + client := ApplicationClient{CallOptions: defaultApplicationCallOptions()} + c := &applicationGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, applicationClient: talentpb.NewApplicationServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ApplicationClient) Connection() *grpc.ClientConn { +func (c *applicationGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ApplicationClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ApplicationClient) setGoogleClientInfo(keyval ...string) { +func (c *applicationGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateApplication creates a new application entity. -func (c *ApplicationClient) CreateApplication(ctx context.Context, req *talentpb.CreateApplicationRequest, opts ...gax.CallOption) (*talentpb.Application, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *applicationGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *applicationGRPCClient) CreateApplication(ctx context.Context, req *talentpb.CreateApplicationRequest, opts ...gax.CallOption) (*talentpb.Application, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -188,7 +262,7 @@ func (c *ApplicationClient) CreateApplication(ctx context.Context, req *talentpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateApplication[0:len(c.CallOptions.CreateApplication):len(c.CallOptions.CreateApplication)], opts...) + opts = append((*c.CallOptions).CreateApplication[0:len((*c.CallOptions).CreateApplication):len((*c.CallOptions).CreateApplication)], opts...) var resp *talentpb.Application err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -201,8 +275,7 @@ func (c *ApplicationClient) CreateApplication(ctx context.Context, req *talentpb return resp, nil } -// GetApplication retrieves specified application. -func (c *ApplicationClient) GetApplication(ctx context.Context, req *talentpb.GetApplicationRequest, opts ...gax.CallOption) (*talentpb.Application, error) { +func (c *applicationGRPCClient) GetApplication(ctx context.Context, req *talentpb.GetApplicationRequest, opts ...gax.CallOption) (*talentpb.Application, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -210,7 +283,7 @@ func (c *ApplicationClient) GetApplication(ctx context.Context, req *talentpb.Ge } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetApplication[0:len(c.CallOptions.GetApplication):len(c.CallOptions.GetApplication)], opts...) + opts = append((*c.CallOptions).GetApplication[0:len((*c.CallOptions).GetApplication):len((*c.CallOptions).GetApplication)], opts...) var resp *talentpb.Application err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -223,8 +296,7 @@ func (c *ApplicationClient) GetApplication(ctx context.Context, req *talentpb.Ge return resp, nil } -// UpdateApplication updates specified application. -func (c *ApplicationClient) UpdateApplication(ctx context.Context, req *talentpb.UpdateApplicationRequest, opts ...gax.CallOption) (*talentpb.Application, error) { +func (c *applicationGRPCClient) UpdateApplication(ctx context.Context, req *talentpb.UpdateApplicationRequest, opts ...gax.CallOption) (*talentpb.Application, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -232,7 +304,7 @@ func (c *ApplicationClient) UpdateApplication(ctx context.Context, req *talentpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "application.name", url.QueryEscape(req.GetApplication().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateApplication[0:len(c.CallOptions.UpdateApplication):len(c.CallOptions.UpdateApplication)], opts...) + opts = append((*c.CallOptions).UpdateApplication[0:len((*c.CallOptions).UpdateApplication):len((*c.CallOptions).UpdateApplication)], opts...) var resp *talentpb.Application err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -245,8 +317,7 @@ func (c *ApplicationClient) UpdateApplication(ctx context.Context, req *talentpb return resp, nil } -// DeleteApplication deletes specified application. -func (c *ApplicationClient) DeleteApplication(ctx context.Context, req *talentpb.DeleteApplicationRequest, opts ...gax.CallOption) error { +func (c *applicationGRPCClient) DeleteApplication(ctx context.Context, req *talentpb.DeleteApplicationRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -254,7 +325,7 @@ func (c *ApplicationClient) DeleteApplication(ctx context.Context, req *talentpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteApplication[0:len(c.CallOptions.DeleteApplication):len(c.CallOptions.DeleteApplication)], opts...) + opts = append((*c.CallOptions).DeleteApplication[0:len((*c.CallOptions).DeleteApplication):len((*c.CallOptions).DeleteApplication)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.applicationClient.DeleteApplication(ctx, req, settings.GRPC...) @@ -263,11 +334,10 @@ func (c *ApplicationClient) DeleteApplication(ctx context.Context, req *talentpb return err } -// ListApplications lists all applications associated with the profile. -func (c *ApplicationClient) ListApplications(ctx context.Context, req *talentpb.ListApplicationsRequest, opts ...gax.CallOption) *ApplicationIterator { +func (c *applicationGRPCClient) ListApplications(ctx context.Context, req *talentpb.ListApplicationsRequest, opts ...gax.CallOption) *ApplicationIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListApplications[0:len(c.CallOptions.ListApplications):len(c.CallOptions.ListApplications)], opts...) + opts = append((*c.CallOptions).ListApplications[0:len((*c.CallOptions).ListApplications):len((*c.CallOptions).ListApplications)], opts...) it := &ApplicationIterator{} req = proto.Clone(req).(*talentpb.ListApplicationsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*talentpb.Application, string, error) { diff --git a/talent/apiv4beta1/application_client_example_test.go b/talent/apiv4beta1/application_client_example_test.go index ac8100d74488..c6ad0b37eafd 100644 --- a/talent/apiv4beta1/application_client_example_test.go +++ b/talent/apiv4beta1/application_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewApplicationClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleApplicationClient_CreateApplication() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewApplicationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateApplicationRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleApplicationClient_CreateApplication() { } func ExampleApplicationClient_GetApplication() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewApplicationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.GetApplicationRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleApplicationClient_GetApplication() { } func ExampleApplicationClient_UpdateApplication() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewApplicationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.UpdateApplicationRequest{ // TODO: Fill request struct fields. @@ -100,6 +99,7 @@ func ExampleApplicationClient_DeleteApplication() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.DeleteApplicationRequest{ // TODO: Fill request struct fields. @@ -111,14 +111,12 @@ func ExampleApplicationClient_DeleteApplication() { } func ExampleApplicationClient_ListApplications() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewApplicationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.ListApplicationsRequest{ // TODO: Fill request struct fields. diff --git a/talent/apiv4beta1/company_client.go b/talent/apiv4beta1/company_client.go index 2b0b8f1f5f7e..58fce6023e33 100644 --- a/talent/apiv4beta1/company_client.go +++ b/talent/apiv4beta1/company_client.go @@ -46,7 +46,7 @@ type CompanyCallOptions struct { ListCompanies []gax.CallOption } -func defaultCompanyClientOptions() []option.ClientOption { +func defaultCompanyGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("jobs.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("jobs.mtls.googleapis.com:443"), @@ -101,32 +101,104 @@ func defaultCompanyCallOptions() *CompanyCallOptions { } } +// internalCompanyClient is an interface that defines the methods availaible from Cloud Talent Solution API. +type internalCompanyClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateCompany(context.Context, *talentpb.CreateCompanyRequest, ...gax.CallOption) (*talentpb.Company, error) + GetCompany(context.Context, *talentpb.GetCompanyRequest, ...gax.CallOption) (*talentpb.Company, error) + UpdateCompany(context.Context, *talentpb.UpdateCompanyRequest, ...gax.CallOption) (*talentpb.Company, error) + DeleteCompany(context.Context, *talentpb.DeleteCompanyRequest, ...gax.CallOption) error + ListCompanies(context.Context, *talentpb.ListCompaniesRequest, ...gax.CallOption) *CompanyIterator +} + // CompanyClient is a client for interacting with Cloud Talent Solution API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A service that handles company management, including CRUD and enumeration. type CompanyClient struct { + // The internal transport-dependent client. + internalClient internalCompanyClient + + // The call options for this service. + CallOptions *CompanyCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CompanyClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CompanyClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CompanyClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateCompany creates a new company entity. +func (c *CompanyClient) CreateCompany(ctx context.Context, req *talentpb.CreateCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { + return c.internalClient.CreateCompany(ctx, req, opts...) +} + +// GetCompany retrieves specified company. +func (c *CompanyClient) GetCompany(ctx context.Context, req *talentpb.GetCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { + return c.internalClient.GetCompany(ctx, req, opts...) +} + +// UpdateCompany updates specified company. +func (c *CompanyClient) UpdateCompany(ctx context.Context, req *talentpb.UpdateCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { + return c.internalClient.UpdateCompany(ctx, req, opts...) +} + +// DeleteCompany deletes specified company. +// Prerequisite: The company has no jobs associated with it. +func (c *CompanyClient) DeleteCompany(ctx context.Context, req *talentpb.DeleteCompanyRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteCompany(ctx, req, opts...) +} + +// ListCompanies lists all companies associated with the project. +func (c *CompanyClient) ListCompanies(ctx context.Context, req *talentpb.ListCompaniesRequest, opts ...gax.CallOption) *CompanyIterator { + return c.internalClient.ListCompanies(ctx, req, opts...) +} + +// companyGRPCClient is a client for interacting with Cloud Talent Solution API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type companyGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CompanyClient + CallOptions **CompanyCallOptions + // The gRPC API client. companyClient talentpb.CompanyServiceClient - // The call options for this service. - CallOptions *CompanyCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCompanyClient creates a new company service client. +// NewCompanyClient creates a new company service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A service that handles company management, including CRUD and enumeration. func NewCompanyClient(ctx context.Context, opts ...option.ClientOption) (*CompanyClient, error) { - clientOpts := defaultCompanyClientOptions() - + clientOpts := defaultCompanyGRPCClientOptions() if newCompanyClientHook != nil { hookOpts, err := newCompanyClientHook(ctx, clientHookParams{}) if err != nil { @@ -144,42 +216,44 @@ func NewCompanyClient(ctx context.Context, opts ...option.ClientOption) (*Compan if err != nil { return nil, err } - c := &CompanyClient{ + client := CompanyClient{CallOptions: defaultCompanyCallOptions()} + + c := &companyGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCompanyCallOptions(), - - companyClient: talentpb.NewCompanyServiceClient(connPool), + companyClient: talentpb.NewCompanyServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CompanyClient) Connection() *grpc.ClientConn { +func (c *companyGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CompanyClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CompanyClient) setGoogleClientInfo(keyval ...string) { +func (c *companyGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateCompany creates a new company entity. -func (c *CompanyClient) CreateCompany(ctx context.Context, req *talentpb.CreateCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *companyGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *companyGRPCClient) CreateCompany(ctx context.Context, req *talentpb.CreateCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -187,7 +261,7 @@ func (c *CompanyClient) CreateCompany(ctx context.Context, req *talentpb.CreateC } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateCompany[0:len(c.CallOptions.CreateCompany):len(c.CallOptions.CreateCompany)], opts...) + opts = append((*c.CallOptions).CreateCompany[0:len((*c.CallOptions).CreateCompany):len((*c.CallOptions).CreateCompany)], opts...) var resp *talentpb.Company err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -200,8 +274,7 @@ func (c *CompanyClient) CreateCompany(ctx context.Context, req *talentpb.CreateC return resp, nil } -// GetCompany retrieves specified company. -func (c *CompanyClient) GetCompany(ctx context.Context, req *talentpb.GetCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { +func (c *companyGRPCClient) GetCompany(ctx context.Context, req *talentpb.GetCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -209,7 +282,7 @@ func (c *CompanyClient) GetCompany(ctx context.Context, req *talentpb.GetCompany } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetCompany[0:len(c.CallOptions.GetCompany):len(c.CallOptions.GetCompany)], opts...) + opts = append((*c.CallOptions).GetCompany[0:len((*c.CallOptions).GetCompany):len((*c.CallOptions).GetCompany)], opts...) var resp *talentpb.Company err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -222,8 +295,7 @@ func (c *CompanyClient) GetCompany(ctx context.Context, req *talentpb.GetCompany return resp, nil } -// UpdateCompany updates specified company. -func (c *CompanyClient) UpdateCompany(ctx context.Context, req *talentpb.UpdateCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { +func (c *companyGRPCClient) UpdateCompany(ctx context.Context, req *talentpb.UpdateCompanyRequest, opts ...gax.CallOption) (*talentpb.Company, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -231,7 +303,7 @@ func (c *CompanyClient) UpdateCompany(ctx context.Context, req *talentpb.UpdateC } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "company.name", url.QueryEscape(req.GetCompany().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateCompany[0:len(c.CallOptions.UpdateCompany):len(c.CallOptions.UpdateCompany)], opts...) + opts = append((*c.CallOptions).UpdateCompany[0:len((*c.CallOptions).UpdateCompany):len((*c.CallOptions).UpdateCompany)], opts...) var resp *talentpb.Company err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -244,9 +316,7 @@ func (c *CompanyClient) UpdateCompany(ctx context.Context, req *talentpb.UpdateC return resp, nil } -// DeleteCompany deletes specified company. -// Prerequisite: The company has no jobs associated with it. -func (c *CompanyClient) DeleteCompany(ctx context.Context, req *talentpb.DeleteCompanyRequest, opts ...gax.CallOption) error { +func (c *companyGRPCClient) DeleteCompany(ctx context.Context, req *talentpb.DeleteCompanyRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -254,7 +324,7 @@ func (c *CompanyClient) DeleteCompany(ctx context.Context, req *talentpb.DeleteC } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteCompany[0:len(c.CallOptions.DeleteCompany):len(c.CallOptions.DeleteCompany)], opts...) + opts = append((*c.CallOptions).DeleteCompany[0:len((*c.CallOptions).DeleteCompany):len((*c.CallOptions).DeleteCompany)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.companyClient.DeleteCompany(ctx, req, settings.GRPC...) @@ -263,11 +333,10 @@ func (c *CompanyClient) DeleteCompany(ctx context.Context, req *talentpb.DeleteC return err } -// ListCompanies lists all companies associated with the project. -func (c *CompanyClient) ListCompanies(ctx context.Context, req *talentpb.ListCompaniesRequest, opts ...gax.CallOption) *CompanyIterator { +func (c *companyGRPCClient) ListCompanies(ctx context.Context, req *talentpb.ListCompaniesRequest, opts ...gax.CallOption) *CompanyIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCompanies[0:len(c.CallOptions.ListCompanies):len(c.CallOptions.ListCompanies)], opts...) + opts = append((*c.CallOptions).ListCompanies[0:len((*c.CallOptions).ListCompanies):len((*c.CallOptions).ListCompanies)], opts...) it := &CompanyIterator{} req = proto.Clone(req).(*talentpb.ListCompaniesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*talentpb.Company, string, error) { diff --git a/talent/apiv4beta1/company_client_example_test.go b/talent/apiv4beta1/company_client_example_test.go index 3cdc790844e8..6da6d1965634 100644 --- a/talent/apiv4beta1/company_client_example_test.go +++ b/talent/apiv4beta1/company_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewCompanyClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCompanyClient_CreateCompany() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewCompanyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateCompanyRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleCompanyClient_CreateCompany() { } func ExampleCompanyClient_GetCompany() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewCompanyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.GetCompanyRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleCompanyClient_GetCompany() { } func ExampleCompanyClient_UpdateCompany() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewCompanyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.UpdateCompanyRequest{ // TODO: Fill request struct fields. @@ -100,6 +99,7 @@ func ExampleCompanyClient_DeleteCompany() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.DeleteCompanyRequest{ // TODO: Fill request struct fields. @@ -111,14 +111,12 @@ func ExampleCompanyClient_DeleteCompany() { } func ExampleCompanyClient_ListCompanies() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewCompanyClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.ListCompaniesRequest{ // TODO: Fill request struct fields. diff --git a/talent/apiv4beta1/completion_client.go b/talent/apiv4beta1/completion_client.go index bcddf380ff25..a2959ed4b38e 100644 --- a/talent/apiv4beta1/completion_client.go +++ b/talent/apiv4beta1/completion_client.go @@ -40,7 +40,7 @@ type CompletionCallOptions struct { CompleteQuery []gax.CallOption } -func defaultCompletionClientOptions() []option.ClientOption { +func defaultCompletionGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("jobs.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("jobs.mtls.googleapis.com:443"), @@ -69,32 +69,80 @@ func defaultCompletionCallOptions() *CompletionCallOptions { } } +// internalCompletionClient is an interface that defines the methods availaible from Cloud Talent Solution API. +type internalCompletionClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CompleteQuery(context.Context, *talentpb.CompleteQueryRequest, ...gax.CallOption) (*talentpb.CompleteQueryResponse, error) +} + // CompletionClient is a client for interacting with Cloud Talent Solution API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A service handles auto completion. type CompletionClient struct { + // The internal transport-dependent client. + internalClient internalCompletionClient + + // The call options for this service. + CallOptions *CompletionCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *CompletionClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *CompletionClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *CompletionClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CompleteQuery completes the specified prefix with keyword suggestions. +// Intended for use by a job search auto-complete search box. +func (c *CompletionClient) CompleteQuery(ctx context.Context, req *talentpb.CompleteQueryRequest, opts ...gax.CallOption) (*talentpb.CompleteQueryResponse, error) { + return c.internalClient.CompleteQuery(ctx, req, opts...) +} + +// completionGRPCClient is a client for interacting with Cloud Talent Solution API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type completionGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing CompletionClient + CallOptions **CompletionCallOptions + // The gRPC API client. completionClient talentpb.CompletionClient - // The call options for this service. - CallOptions *CompletionCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewCompletionClient creates a new completion client. +// NewCompletionClient creates a new completion client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A service handles auto completion. func NewCompletionClient(ctx context.Context, opts ...option.ClientOption) (*CompletionClient, error) { - clientOpts := defaultCompletionClientOptions() - + clientOpts := defaultCompletionGRPCClientOptions() if newCompletionClientHook != nil { hookOpts, err := newCompletionClientHook(ctx, clientHookParams{}) if err != nil { @@ -112,43 +160,44 @@ func NewCompletionClient(ctx context.Context, opts ...option.ClientOption) (*Com if err != nil { return nil, err } - c := &CompletionClient{ + client := CompletionClient{CallOptions: defaultCompletionCallOptions()} + + c := &completionGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCompletionCallOptions(), - completionClient: talentpb.NewCompletionClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *CompletionClient) Connection() *grpc.ClientConn { +func (c *completionGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *CompletionClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *CompletionClient) setGoogleClientInfo(keyval ...string) { +func (c *completionGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CompleteQuery completes the specified prefix with keyword suggestions. -// Intended for use by a job search auto-complete search box. -func (c *CompletionClient) CompleteQuery(ctx context.Context, req *talentpb.CompleteQueryRequest, opts ...gax.CallOption) (*talentpb.CompleteQueryResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *completionGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *completionGRPCClient) CompleteQuery(ctx context.Context, req *talentpb.CompleteQueryRequest, opts ...gax.CallOption) (*talentpb.CompleteQueryResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -156,7 +205,7 @@ func (c *CompletionClient) CompleteQuery(ctx context.Context, req *talentpb.Comp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CompleteQuery[0:len(c.CallOptions.CompleteQuery):len(c.CallOptions.CompleteQuery)], opts...) + opts = append((*c.CallOptions).CompleteQuery[0:len((*c.CallOptions).CompleteQuery):len((*c.CallOptions).CompleteQuery)], opts...) var resp *talentpb.CompleteQueryResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/talent/apiv4beta1/completion_client_example_test.go b/talent/apiv4beta1/completion_client_example_test.go index da31f1947243..728a4b31f906 100644 --- a/talent/apiv4beta1/completion_client_example_test.go +++ b/talent/apiv4beta1/completion_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewCompletionClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleCompletionClient_CompleteQuery() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewCompletionClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CompleteQueryRequest{ // TODO: Fill request struct fields. diff --git a/talent/apiv4beta1/doc.go b/talent/apiv4beta1/doc.go index 3449867e375d..42acffdec06d 100644 --- a/talent/apiv4beta1/doc.go +++ b/talent/apiv4beta1/doc.go @@ -20,6 +20,8 @@ // Cloud Talent Solution provides the capability to create, read, update, and // delete job postings, as well as search jobs based on keywords and filters. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package talent // import "cloud.google.com/go/talent/apiv4beta1" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/talent/apiv4beta1/event_client.go b/talent/apiv4beta1/event_client.go index 6905c76af3ae..f82ede603735 100644 --- a/talent/apiv4beta1/event_client.go +++ b/talent/apiv4beta1/event_client.go @@ -39,7 +39,7 @@ type EventCallOptions struct { CreateClientEvent []gax.CallOption } -func defaultEventClientOptions() []option.ClientOption { +func defaultEventGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("jobs.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("jobs.mtls.googleapis.com:443"), @@ -57,32 +57,85 @@ func defaultEventCallOptions() *EventCallOptions { } } +// internalEventClient is an interface that defines the methods availaible from Cloud Talent Solution API. +type internalEventClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateClientEvent(context.Context, *talentpb.CreateClientEventRequest, ...gax.CallOption) (*talentpb.ClientEvent, error) +} + // EventClient is a client for interacting with Cloud Talent Solution API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A service handles client event report. type EventClient struct { + // The internal transport-dependent client. + internalClient internalEventClient + + // The call options for this service. + CallOptions *EventCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *EventClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *EventClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *EventClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateClientEvent report events issued when end user interacts with customer’s application +// that uses Cloud Talent Solution. You may inspect the created events in +// self service +// tools (at https://console.cloud.google.com/talent-solution/overview). +// Learn +// more (at https://cloud.google.com/talent-solution/docs/management-tools) +// about self service tools. +func (c *EventClient) CreateClientEvent(ctx context.Context, req *talentpb.CreateClientEventRequest, opts ...gax.CallOption) (*talentpb.ClientEvent, error) { + return c.internalClient.CreateClientEvent(ctx, req, opts...) +} + +// eventGRPCClient is a client for interacting with Cloud Talent Solution API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type eventGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing EventClient + CallOptions **EventCallOptions + // The gRPC API client. eventClient talentpb.EventServiceClient - // The call options for this service. - CallOptions *EventCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewEventClient creates a new event service client. +// NewEventClient creates a new event service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A service handles client event report. func NewEventClient(ctx context.Context, opts ...option.ClientOption) (*EventClient, error) { - clientOpts := defaultEventClientOptions() - + clientOpts := defaultEventGRPCClientOptions() if newEventClientHook != nil { hookOpts, err := newEventClientHook(ctx, clientHookParams{}) if err != nil { @@ -100,48 +153,44 @@ func NewEventClient(ctx context.Context, opts ...option.ClientOption) (*EventCli if err != nil { return nil, err } - c := &EventClient{ + client := EventClient{CallOptions: defaultEventCallOptions()} + + c := &eventGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultEventCallOptions(), - - eventClient: talentpb.NewEventServiceClient(connPool), + eventClient: talentpb.NewEventServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *EventClient) Connection() *grpc.ClientConn { +func (c *eventGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *EventClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *EventClient) setGoogleClientInfo(keyval ...string) { +func (c *eventGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateClientEvent report events issued when end user interacts with customer’s application -// that uses Cloud Talent Solution. You may inspect the created events in -// self service -// tools (at https://console.cloud.google.com/talent-solution/overview). -// Learn -// more (at https://cloud.google.com/talent-solution/docs/management-tools) -// about self service tools. -func (c *EventClient) CreateClientEvent(ctx context.Context, req *talentpb.CreateClientEventRequest, opts ...gax.CallOption) (*talentpb.ClientEvent, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *eventGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *eventGRPCClient) CreateClientEvent(ctx context.Context, req *talentpb.CreateClientEventRequest, opts ...gax.CallOption) (*talentpb.ClientEvent, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -149,7 +198,7 @@ func (c *EventClient) CreateClientEvent(ctx context.Context, req *talentpb.Creat } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateClientEvent[0:len(c.CallOptions.CreateClientEvent):len(c.CallOptions.CreateClientEvent)], opts...) + opts = append((*c.CallOptions).CreateClientEvent[0:len((*c.CallOptions).CreateClientEvent):len((*c.CallOptions).CreateClientEvent)], opts...) var resp *talentpb.ClientEvent err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/talent/apiv4beta1/event_client_example_test.go b/talent/apiv4beta1/event_client_example_test.go index 6cb35e06e5cc..637f41f04d91 100644 --- a/talent/apiv4beta1/event_client_example_test.go +++ b/talent/apiv4beta1/event_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewEventClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleEventClient_CreateClientEvent() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewEventClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateClientEventRequest{ // TODO: Fill request struct fields. diff --git a/talent/apiv4beta1/job_client.go b/talent/apiv4beta1/job_client.go index 05c55f841999..b75b3cf5f85d 100644 --- a/talent/apiv4beta1/job_client.go +++ b/talent/apiv4beta1/job_client.go @@ -54,7 +54,7 @@ type JobCallOptions struct { SearchJobsForAlert []gax.CallOption } -func defaultJobClientOptions() []option.ClientOption { +func defaultJobGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("jobs.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("jobs.mtls.googleapis.com:443"), @@ -114,37 +114,180 @@ func defaultJobCallOptions() *JobCallOptions { } } +// internalJobClient is an interface that defines the methods availaible from Cloud Talent Solution API. +type internalJobClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateJob(context.Context, *talentpb.CreateJobRequest, ...gax.CallOption) (*talentpb.Job, error) + BatchCreateJobs(context.Context, *talentpb.BatchCreateJobsRequest, ...gax.CallOption) (*BatchCreateJobsOperation, error) + BatchCreateJobsOperation(name string) *BatchCreateJobsOperation + GetJob(context.Context, *talentpb.GetJobRequest, ...gax.CallOption) (*talentpb.Job, error) + UpdateJob(context.Context, *talentpb.UpdateJobRequest, ...gax.CallOption) (*talentpb.Job, error) + BatchUpdateJobs(context.Context, *talentpb.BatchUpdateJobsRequest, ...gax.CallOption) (*BatchUpdateJobsOperation, error) + BatchUpdateJobsOperation(name string) *BatchUpdateJobsOperation + DeleteJob(context.Context, *talentpb.DeleteJobRequest, ...gax.CallOption) error + BatchDeleteJobs(context.Context, *talentpb.BatchDeleteJobsRequest, ...gax.CallOption) error + ListJobs(context.Context, *talentpb.ListJobsRequest, ...gax.CallOption) *JobIterator + SearchJobs(context.Context, *talentpb.SearchJobsRequest, ...gax.CallOption) (*talentpb.SearchJobsResponse, error) + SearchJobsForAlert(context.Context, *talentpb.SearchJobsRequest, ...gax.CallOption) *SearchJobsResponse_MatchingJobIterator +} + // JobClient is a client for interacting with Cloud Talent Solution API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A service handles job management, including job CRUD, enumeration and search. type JobClient struct { + // The internal transport-dependent client. + internalClient internalJobClient + + // The call options for this service. + CallOptions *JobCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *JobClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *JobClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *JobClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateJob creates a new job. +// +// Typically, the job becomes searchable within 10 seconds, but it may take +// up to 5 minutes. +func (c *JobClient) CreateJob(ctx context.Context, req *talentpb.CreateJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { + return c.internalClient.CreateJob(ctx, req, opts...) +} + +// BatchCreateJobs begins executing a batch create jobs operation. +func (c *JobClient) BatchCreateJobs(ctx context.Context, req *talentpb.BatchCreateJobsRequest, opts ...gax.CallOption) (*BatchCreateJobsOperation, error) { + return c.internalClient.BatchCreateJobs(ctx, req, opts...) +} + +// BatchCreateJobsOperation returns a new BatchCreateJobsOperation from a given name. +// The name must be that of a previously created BatchCreateJobsOperation, possibly from a different process. +func (c *JobClient) BatchCreateJobsOperation(name string) *BatchCreateJobsOperation { + return c.internalClient.BatchCreateJobsOperation(name) +} + +// GetJob retrieves the specified job, whose status is OPEN or recently EXPIRED +// within the last 90 days. +func (c *JobClient) GetJob(ctx context.Context, req *talentpb.GetJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { + return c.internalClient.GetJob(ctx, req, opts...) +} + +// UpdateJob updates specified job. +// +// Typically, updated contents become visible in search results within 10 +// seconds, but it may take up to 5 minutes. +func (c *JobClient) UpdateJob(ctx context.Context, req *talentpb.UpdateJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { + return c.internalClient.UpdateJob(ctx, req, opts...) +} + +// BatchUpdateJobs begins executing a batch update jobs operation. +func (c *JobClient) BatchUpdateJobs(ctx context.Context, req *talentpb.BatchUpdateJobsRequest, opts ...gax.CallOption) (*BatchUpdateJobsOperation, error) { + return c.internalClient.BatchUpdateJobs(ctx, req, opts...) +} + +// BatchUpdateJobsOperation returns a new BatchUpdateJobsOperation from a given name. +// The name must be that of a previously created BatchUpdateJobsOperation, possibly from a different process. +func (c *JobClient) BatchUpdateJobsOperation(name string) *BatchUpdateJobsOperation { + return c.internalClient.BatchUpdateJobsOperation(name) +} + +// DeleteJob deletes the specified job. +// +// Typically, the job becomes unsearchable within 10 seconds, but it may take +// up to 5 minutes. +func (c *JobClient) DeleteJob(ctx context.Context, req *talentpb.DeleteJobRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteJob(ctx, req, opts...) +} + +// BatchDeleteJobs deletes a list of Jobs by filter. +func (c *JobClient) BatchDeleteJobs(ctx context.Context, req *talentpb.BatchDeleteJobsRequest, opts ...gax.CallOption) error { + return c.internalClient.BatchDeleteJobs(ctx, req, opts...) +} + +// ListJobs lists jobs by filter. +func (c *JobClient) ListJobs(ctx context.Context, req *talentpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { + return c.internalClient.ListJobs(ctx, req, opts...) +} + +// SearchJobs searches for jobs using the provided SearchJobsRequest. +// +// This call constrains the visibility of jobs +// present in the database, and only returns jobs that the caller has +// permission to search against. +func (c *JobClient) SearchJobs(ctx context.Context, req *talentpb.SearchJobsRequest, opts ...gax.CallOption) (*talentpb.SearchJobsResponse, error) { + return c.internalClient.SearchJobs(ctx, req, opts...) +} + +// SearchJobsForAlert searches for jobs using the provided SearchJobsRequest. +// +// This API call is intended for the use case of targeting passive job +// seekers (for example, job seekers who have signed up to receive email +// alerts about potential job opportunities), and has different algorithmic +// adjustments that are targeted to passive job seekers. +// +// This call constrains the visibility of jobs +// present in the database, and only returns jobs the caller has +// permission to search against. +func (c *JobClient) SearchJobsForAlert(ctx context.Context, req *talentpb.SearchJobsRequest, opts ...gax.CallOption) *SearchJobsResponse_MatchingJobIterator { + return c.internalClient.SearchJobsForAlert(ctx, req, opts...) +} + +// jobGRPCClient is a client for interacting with Cloud Talent Solution API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type jobGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing JobClient + CallOptions **JobCallOptions + // The gRPC API client. jobClient talentpb.JobServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *JobCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewJobClient creates a new job service client. +// NewJobClient creates a new job service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A service handles job management, including job CRUD, enumeration and search. func NewJobClient(ctx context.Context, opts ...option.ClientOption) (*JobClient, error) { - clientOpts := defaultJobClientOptions() - + clientOpts := defaultJobGRPCClientOptions() if newJobClientHook != nil { hookOpts, err := newJobClientHook(ctx, clientHookParams{}) if err != nil { @@ -162,16 +305,19 @@ func NewJobClient(ctx context.Context, opts ...option.ClientOption) (*JobClient, if err != nil { return nil, err } - c := &JobClient{ + client := JobClient{CallOptions: defaultJobCallOptions()} + + c := &jobGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultJobCallOptions(), - - jobClient: talentpb.NewJobServiceClient(connPool), + jobClient: talentpb.NewJobServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -181,36 +327,33 @@ func NewJobClient(ctx context.Context, opts ...option.ClientOption) (*JobClient, // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *JobClient) Connection() *grpc.ClientConn { +func (c *jobGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *JobClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *JobClient) setGoogleClientInfo(keyval ...string) { +func (c *jobGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateJob creates a new job. -// -// Typically, the job becomes searchable within 10 seconds, but it may take -// up to 5 minutes. -func (c *JobClient) CreateJob(ctx context.Context, req *talentpb.CreateJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *jobGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *jobGRPCClient) CreateJob(ctx context.Context, req *talentpb.CreateJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -218,7 +361,7 @@ func (c *JobClient) CreateJob(ctx context.Context, req *talentpb.CreateJobReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateJob[0:len(c.CallOptions.CreateJob):len(c.CallOptions.CreateJob)], opts...) + opts = append((*c.CallOptions).CreateJob[0:len((*c.CallOptions).CreateJob):len((*c.CallOptions).CreateJob)], opts...) var resp *talentpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -231,8 +374,7 @@ func (c *JobClient) CreateJob(ctx context.Context, req *talentpb.CreateJobReques return resp, nil } -// BatchCreateJobs begins executing a batch create jobs operation. -func (c *JobClient) BatchCreateJobs(ctx context.Context, req *talentpb.BatchCreateJobsRequest, opts ...gax.CallOption) (*BatchCreateJobsOperation, error) { +func (c *jobGRPCClient) BatchCreateJobs(ctx context.Context, req *talentpb.BatchCreateJobsRequest, opts ...gax.CallOption) (*BatchCreateJobsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -240,7 +382,7 @@ func (c *JobClient) BatchCreateJobs(ctx context.Context, req *talentpb.BatchCrea } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchCreateJobs[0:len(c.CallOptions.BatchCreateJobs):len(c.CallOptions.BatchCreateJobs)], opts...) + opts = append((*c.CallOptions).BatchCreateJobs[0:len((*c.CallOptions).BatchCreateJobs):len((*c.CallOptions).BatchCreateJobs)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -251,13 +393,11 @@ func (c *JobClient) BatchCreateJobs(ctx context.Context, req *talentpb.BatchCrea return nil, err } return &BatchCreateJobsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// GetJob retrieves the specified job, whose status is OPEN or recently EXPIRED -// within the last 90 days. -func (c *JobClient) GetJob(ctx context.Context, req *talentpb.GetJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { +func (c *jobGRPCClient) GetJob(ctx context.Context, req *talentpb.GetJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -265,7 +405,7 @@ func (c *JobClient) GetJob(ctx context.Context, req *talentpb.GetJobRequest, opt } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetJob[0:len(c.CallOptions.GetJob):len(c.CallOptions.GetJob)], opts...) + opts = append((*c.CallOptions).GetJob[0:len((*c.CallOptions).GetJob):len((*c.CallOptions).GetJob)], opts...) var resp *talentpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -278,11 +418,7 @@ func (c *JobClient) GetJob(ctx context.Context, req *talentpb.GetJobRequest, opt return resp, nil } -// UpdateJob updates specified job. -// -// Typically, updated contents become visible in search results within 10 -// seconds, but it may take up to 5 minutes. -func (c *JobClient) UpdateJob(ctx context.Context, req *talentpb.UpdateJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { +func (c *jobGRPCClient) UpdateJob(ctx context.Context, req *talentpb.UpdateJobRequest, opts ...gax.CallOption) (*talentpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -290,7 +426,7 @@ func (c *JobClient) UpdateJob(ctx context.Context, req *talentpb.UpdateJobReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "job.name", url.QueryEscape(req.GetJob().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateJob[0:len(c.CallOptions.UpdateJob):len(c.CallOptions.UpdateJob)], opts...) + opts = append((*c.CallOptions).UpdateJob[0:len((*c.CallOptions).UpdateJob):len((*c.CallOptions).UpdateJob)], opts...) var resp *talentpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -303,8 +439,7 @@ func (c *JobClient) UpdateJob(ctx context.Context, req *talentpb.UpdateJobReques return resp, nil } -// BatchUpdateJobs begins executing a batch update jobs operation. -func (c *JobClient) BatchUpdateJobs(ctx context.Context, req *talentpb.BatchUpdateJobsRequest, opts ...gax.CallOption) (*BatchUpdateJobsOperation, error) { +func (c *jobGRPCClient) BatchUpdateJobs(ctx context.Context, req *talentpb.BatchUpdateJobsRequest, opts ...gax.CallOption) (*BatchUpdateJobsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -312,7 +447,7 @@ func (c *JobClient) BatchUpdateJobs(ctx context.Context, req *talentpb.BatchUpda } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchUpdateJobs[0:len(c.CallOptions.BatchUpdateJobs):len(c.CallOptions.BatchUpdateJobs)], opts...) + opts = append((*c.CallOptions).BatchUpdateJobs[0:len((*c.CallOptions).BatchUpdateJobs):len((*c.CallOptions).BatchUpdateJobs)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -323,15 +458,11 @@ func (c *JobClient) BatchUpdateJobs(ctx context.Context, req *talentpb.BatchUpda return nil, err } return &BatchUpdateJobsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteJob deletes the specified job. -// -// Typically, the job becomes unsearchable within 10 seconds, but it may take -// up to 5 minutes. -func (c *JobClient) DeleteJob(ctx context.Context, req *talentpb.DeleteJobRequest, opts ...gax.CallOption) error { +func (c *jobGRPCClient) DeleteJob(ctx context.Context, req *talentpb.DeleteJobRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -339,7 +470,7 @@ func (c *JobClient) DeleteJob(ctx context.Context, req *talentpb.DeleteJobReques } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteJob[0:len(c.CallOptions.DeleteJob):len(c.CallOptions.DeleteJob)], opts...) + opts = append((*c.CallOptions).DeleteJob[0:len((*c.CallOptions).DeleteJob):len((*c.CallOptions).DeleteJob)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.jobClient.DeleteJob(ctx, req, settings.GRPC...) @@ -348,8 +479,7 @@ func (c *JobClient) DeleteJob(ctx context.Context, req *talentpb.DeleteJobReques return err } -// BatchDeleteJobs deletes a list of Jobs by filter. -func (c *JobClient) BatchDeleteJobs(ctx context.Context, req *talentpb.BatchDeleteJobsRequest, opts ...gax.CallOption) error { +func (c *jobGRPCClient) BatchDeleteJobs(ctx context.Context, req *talentpb.BatchDeleteJobsRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -357,7 +487,7 @@ func (c *JobClient) BatchDeleteJobs(ctx context.Context, req *talentpb.BatchDele } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchDeleteJobs[0:len(c.CallOptions.BatchDeleteJobs):len(c.CallOptions.BatchDeleteJobs)], opts...) + opts = append((*c.CallOptions).BatchDeleteJobs[0:len((*c.CallOptions).BatchDeleteJobs):len((*c.CallOptions).BatchDeleteJobs)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.jobClient.BatchDeleteJobs(ctx, req, settings.GRPC...) @@ -366,11 +496,10 @@ func (c *JobClient) BatchDeleteJobs(ctx context.Context, req *talentpb.BatchDele return err } -// ListJobs lists jobs by filter. -func (c *JobClient) ListJobs(ctx context.Context, req *talentpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { +func (c *jobGRPCClient) ListJobs(ctx context.Context, req *talentpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListJobs[0:len(c.CallOptions.ListJobs):len(c.CallOptions.ListJobs)], opts...) + opts = append((*c.CallOptions).ListJobs[0:len((*c.CallOptions).ListJobs):len((*c.CallOptions).ListJobs)], opts...) it := &JobIterator{} req = proto.Clone(req).(*talentpb.ListJobsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*talentpb.Job, string, error) { @@ -407,12 +536,7 @@ func (c *JobClient) ListJobs(ctx context.Context, req *talentpb.ListJobsRequest, return it } -// SearchJobs searches for jobs using the provided SearchJobsRequest. -// -// This call constrains the visibility of jobs -// present in the database, and only returns jobs that the caller has -// permission to search against. -func (c *JobClient) SearchJobs(ctx context.Context, req *talentpb.SearchJobsRequest, opts ...gax.CallOption) (*talentpb.SearchJobsResponse, error) { +func (c *jobGRPCClient) SearchJobs(ctx context.Context, req *talentpb.SearchJobsRequest, opts ...gax.CallOption) (*talentpb.SearchJobsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -420,7 +544,7 @@ func (c *JobClient) SearchJobs(ctx context.Context, req *talentpb.SearchJobsRequ } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SearchJobs[0:len(c.CallOptions.SearchJobs):len(c.CallOptions.SearchJobs)], opts...) + opts = append((*c.CallOptions).SearchJobs[0:len((*c.CallOptions).SearchJobs):len((*c.CallOptions).SearchJobs)], opts...) var resp *talentpb.SearchJobsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -433,20 +557,10 @@ func (c *JobClient) SearchJobs(ctx context.Context, req *talentpb.SearchJobsRequ return resp, nil } -// SearchJobsForAlert searches for jobs using the provided SearchJobsRequest. -// -// This API call is intended for the use case of targeting passive job -// seekers (for example, job seekers who have signed up to receive email -// alerts about potential job opportunities), and has different algorithmic -// adjustments that are targeted to passive job seekers. -// -// This call constrains the visibility of jobs -// present in the database, and only returns jobs the caller has -// permission to search against. -func (c *JobClient) SearchJobsForAlert(ctx context.Context, req *talentpb.SearchJobsRequest, opts ...gax.CallOption) *SearchJobsResponse_MatchingJobIterator { +func (c *jobGRPCClient) SearchJobsForAlert(ctx context.Context, req *talentpb.SearchJobsRequest, opts ...gax.CallOption) *SearchJobsResponse_MatchingJobIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SearchJobsForAlert[0:len(c.CallOptions.SearchJobsForAlert):len(c.CallOptions.SearchJobsForAlert)], opts...) + opts = append((*c.CallOptions).SearchJobsForAlert[0:len((*c.CallOptions).SearchJobsForAlert):len((*c.CallOptions).SearchJobsForAlert)], opts...) it := &SearchJobsResponse_MatchingJobIterator{} req = proto.Clone(req).(*talentpb.SearchJobsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*talentpb.SearchJobsResponse_MatchingJob, string, error) { @@ -490,9 +604,9 @@ type BatchCreateJobsOperation struct { // BatchCreateJobsOperation returns a new BatchCreateJobsOperation from a given name. // The name must be that of a previously created BatchCreateJobsOperation, possibly from a different process. -func (c *JobClient) BatchCreateJobsOperation(name string) *BatchCreateJobsOperation { +func (c *jobGRPCClient) BatchCreateJobsOperation(name string) *BatchCreateJobsOperation { return &BatchCreateJobsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -559,9 +673,9 @@ type BatchUpdateJobsOperation struct { // BatchUpdateJobsOperation returns a new BatchUpdateJobsOperation from a given name. // The name must be that of a previously created BatchUpdateJobsOperation, possibly from a different process. -func (c *JobClient) BatchUpdateJobsOperation(name string) *BatchUpdateJobsOperation { +func (c *jobGRPCClient) BatchUpdateJobsOperation(name string) *BatchUpdateJobsOperation { return &BatchUpdateJobsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/talent/apiv4beta1/job_client_example_test.go b/talent/apiv4beta1/job_client_example_test.go index c6b4fcb680b7..204a808cc98a 100644 --- a/talent/apiv4beta1/job_client_example_test.go +++ b/talent/apiv4beta1/job_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewJobClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleJobClient_CreateJob() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateJobRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleJobClient_CreateJob() { } func ExampleJobClient_BatchCreateJobs() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.BatchCreateJobsRequest{ // TODO: Fill request struct fields. @@ -80,13 +80,12 @@ func ExampleJobClient_BatchCreateJobs() { } func ExampleJobClient_GetJob() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.GetJobRequest{ // TODO: Fill request struct fields. @@ -100,13 +99,12 @@ func ExampleJobClient_GetJob() { } func ExampleJobClient_UpdateJob() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.UpdateJobRequest{ // TODO: Fill request struct fields. @@ -120,13 +118,12 @@ func ExampleJobClient_UpdateJob() { } func ExampleJobClient_BatchUpdateJobs() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.BatchUpdateJobsRequest{ // TODO: Fill request struct fields. @@ -150,6 +147,7 @@ func ExampleJobClient_DeleteJob() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.DeleteJobRequest{ // TODO: Fill request struct fields. @@ -166,6 +164,7 @@ func ExampleJobClient_BatchDeleteJobs() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.BatchDeleteJobsRequest{ // TODO: Fill request struct fields. @@ -177,14 +176,12 @@ func ExampleJobClient_BatchDeleteJobs() { } func ExampleJobClient_ListJobs() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.ListJobsRequest{ // TODO: Fill request struct fields. @@ -204,13 +201,12 @@ func ExampleJobClient_ListJobs() { } func ExampleJobClient_SearchJobs() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.SearchJobsRequest{ // TODO: Fill request struct fields. @@ -224,14 +220,12 @@ func ExampleJobClient_SearchJobs() { } func ExampleJobClient_SearchJobsForAlert() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewJobClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.SearchJobsRequest{ // TODO: Fill request struct fields. diff --git a/talent/apiv4beta1/profile_client.go b/talent/apiv4beta1/profile_client.go index d9074aa1b27c..4556dd687409 100644 --- a/talent/apiv4beta1/profile_client.go +++ b/talent/apiv4beta1/profile_client.go @@ -47,7 +47,7 @@ type ProfileCallOptions struct { SearchProfiles []gax.CallOption } -func defaultProfileClientOptions() []option.ClientOption { +func defaultProfileGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("jobs.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("jobs.mtls.googleapis.com:443"), @@ -103,33 +103,118 @@ func defaultProfileCallOptions() *ProfileCallOptions { } } +// internalProfileClient is an interface that defines the methods availaible from Cloud Talent Solution API. +type internalProfileClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListProfiles(context.Context, *talentpb.ListProfilesRequest, ...gax.CallOption) *ProfileIterator + CreateProfile(context.Context, *talentpb.CreateProfileRequest, ...gax.CallOption) (*talentpb.Profile, error) + GetProfile(context.Context, *talentpb.GetProfileRequest, ...gax.CallOption) (*talentpb.Profile, error) + UpdateProfile(context.Context, *talentpb.UpdateProfileRequest, ...gax.CallOption) (*talentpb.Profile, error) + DeleteProfile(context.Context, *talentpb.DeleteProfileRequest, ...gax.CallOption) error + SearchProfiles(context.Context, *talentpb.SearchProfilesRequest, ...gax.CallOption) (*talentpb.SearchProfilesResponse, error) +} + // ProfileClient is a client for interacting with Cloud Talent Solution API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A service that handles profile management, including profile CRUD, +// enumeration and search. type ProfileClient struct { + // The internal transport-dependent client. + internalClient internalProfileClient + + // The call options for this service. + CallOptions *ProfileCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ProfileClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ProfileClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ProfileClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListProfiles lists profiles by filter. The order is unspecified. +func (c *ProfileClient) ListProfiles(ctx context.Context, req *talentpb.ListProfilesRequest, opts ...gax.CallOption) *ProfileIterator { + return c.internalClient.ListProfiles(ctx, req, opts...) +} + +// CreateProfile creates and returns a new profile. +func (c *ProfileClient) CreateProfile(ctx context.Context, req *talentpb.CreateProfileRequest, opts ...gax.CallOption) (*talentpb.Profile, error) { + return c.internalClient.CreateProfile(ctx, req, opts...) +} + +// GetProfile gets the specified profile. +func (c *ProfileClient) GetProfile(ctx context.Context, req *talentpb.GetProfileRequest, opts ...gax.CallOption) (*talentpb.Profile, error) { + return c.internalClient.GetProfile(ctx, req, opts...) +} + +// UpdateProfile updates the specified profile and returns the updated result. +func (c *ProfileClient) UpdateProfile(ctx context.Context, req *talentpb.UpdateProfileRequest, opts ...gax.CallOption) (*talentpb.Profile, error) { + return c.internalClient.UpdateProfile(ctx, req, opts...) +} + +// DeleteProfile deletes the specified profile. +// Prerequisite: The profile has no associated applications or assignments +// associated. +func (c *ProfileClient) DeleteProfile(ctx context.Context, req *talentpb.DeleteProfileRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteProfile(ctx, req, opts...) +} + +// SearchProfiles searches for profiles within a tenant. +// +// For example, search by raw queries “software engineer in Mountain View” or +// search by structured filters (location filter, education filter, etc.). +// +// See SearchProfilesRequest for more information. +func (c *ProfileClient) SearchProfiles(ctx context.Context, req *talentpb.SearchProfilesRequest, opts ...gax.CallOption) (*talentpb.SearchProfilesResponse, error) { + return c.internalClient.SearchProfiles(ctx, req, opts...) +} + +// profileGRPCClient is a client for interacting with Cloud Talent Solution API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type profileGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ProfileClient + CallOptions **ProfileCallOptions + // The gRPC API client. profileClient talentpb.ProfileServiceClient - // The call options for this service. - CallOptions *ProfileCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewProfileClient creates a new profile service client. +// NewProfileClient creates a new profile service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A service that handles profile management, including profile CRUD, // enumeration and search. func NewProfileClient(ctx context.Context, opts ...option.ClientOption) (*ProfileClient, error) { - clientOpts := defaultProfileClientOptions() - + clientOpts := defaultProfileGRPCClientOptions() if newProfileClientHook != nil { hookOpts, err := newProfileClientHook(ctx, clientHookParams{}) if err != nil { @@ -147,45 +232,47 @@ func NewProfileClient(ctx context.Context, opts ...option.ClientOption) (*Profil if err != nil { return nil, err } - c := &ProfileClient{ + client := ProfileClient{CallOptions: defaultProfileCallOptions()} + + c := &profileGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultProfileCallOptions(), - - profileClient: talentpb.NewProfileServiceClient(connPool), + profileClient: talentpb.NewProfileServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ProfileClient) Connection() *grpc.ClientConn { +func (c *profileGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ProfileClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ProfileClient) setGoogleClientInfo(keyval ...string) { +func (c *profileGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListProfiles lists profiles by filter. The order is unspecified. -func (c *ProfileClient) ListProfiles(ctx context.Context, req *talentpb.ListProfilesRequest, opts ...gax.CallOption) *ProfileIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *profileGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *profileGRPCClient) ListProfiles(ctx context.Context, req *talentpb.ListProfilesRequest, opts ...gax.CallOption) *ProfileIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListProfiles[0:len(c.CallOptions.ListProfiles):len(c.CallOptions.ListProfiles)], opts...) + opts = append((*c.CallOptions).ListProfiles[0:len((*c.CallOptions).ListProfiles):len((*c.CallOptions).ListProfiles)], opts...) it := &ProfileIterator{} req = proto.Clone(req).(*talentpb.ListProfilesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*talentpb.Profile, string, error) { @@ -222,8 +309,7 @@ func (c *ProfileClient) ListProfiles(ctx context.Context, req *talentpb.ListProf return it } -// CreateProfile creates and returns a new profile. -func (c *ProfileClient) CreateProfile(ctx context.Context, req *talentpb.CreateProfileRequest, opts ...gax.CallOption) (*talentpb.Profile, error) { +func (c *profileGRPCClient) CreateProfile(ctx context.Context, req *talentpb.CreateProfileRequest, opts ...gax.CallOption) (*talentpb.Profile, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -231,7 +317,7 @@ func (c *ProfileClient) CreateProfile(ctx context.Context, req *talentpb.CreateP } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateProfile[0:len(c.CallOptions.CreateProfile):len(c.CallOptions.CreateProfile)], opts...) + opts = append((*c.CallOptions).CreateProfile[0:len((*c.CallOptions).CreateProfile):len((*c.CallOptions).CreateProfile)], opts...) var resp *talentpb.Profile err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -244,8 +330,7 @@ func (c *ProfileClient) CreateProfile(ctx context.Context, req *talentpb.CreateP return resp, nil } -// GetProfile gets the specified profile. -func (c *ProfileClient) GetProfile(ctx context.Context, req *talentpb.GetProfileRequest, opts ...gax.CallOption) (*talentpb.Profile, error) { +func (c *profileGRPCClient) GetProfile(ctx context.Context, req *talentpb.GetProfileRequest, opts ...gax.CallOption) (*talentpb.Profile, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -253,7 +338,7 @@ func (c *ProfileClient) GetProfile(ctx context.Context, req *talentpb.GetProfile } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetProfile[0:len(c.CallOptions.GetProfile):len(c.CallOptions.GetProfile)], opts...) + opts = append((*c.CallOptions).GetProfile[0:len((*c.CallOptions).GetProfile):len((*c.CallOptions).GetProfile)], opts...) var resp *talentpb.Profile err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -266,8 +351,7 @@ func (c *ProfileClient) GetProfile(ctx context.Context, req *talentpb.GetProfile return resp, nil } -// UpdateProfile updates the specified profile and returns the updated result. -func (c *ProfileClient) UpdateProfile(ctx context.Context, req *talentpb.UpdateProfileRequest, opts ...gax.CallOption) (*talentpb.Profile, error) { +func (c *profileGRPCClient) UpdateProfile(ctx context.Context, req *talentpb.UpdateProfileRequest, opts ...gax.CallOption) (*talentpb.Profile, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -275,7 +359,7 @@ func (c *ProfileClient) UpdateProfile(ctx context.Context, req *talentpb.UpdateP } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "profile.name", url.QueryEscape(req.GetProfile().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateProfile[0:len(c.CallOptions.UpdateProfile):len(c.CallOptions.UpdateProfile)], opts...) + opts = append((*c.CallOptions).UpdateProfile[0:len((*c.CallOptions).UpdateProfile):len((*c.CallOptions).UpdateProfile)], opts...) var resp *talentpb.Profile err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -288,10 +372,7 @@ func (c *ProfileClient) UpdateProfile(ctx context.Context, req *talentpb.UpdateP return resp, nil } -// DeleteProfile deletes the specified profile. -// Prerequisite: The profile has no associated applications or assignments -// associated. -func (c *ProfileClient) DeleteProfile(ctx context.Context, req *talentpb.DeleteProfileRequest, opts ...gax.CallOption) error { +func (c *profileGRPCClient) DeleteProfile(ctx context.Context, req *talentpb.DeleteProfileRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -299,7 +380,7 @@ func (c *ProfileClient) DeleteProfile(ctx context.Context, req *talentpb.DeleteP } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteProfile[0:len(c.CallOptions.DeleteProfile):len(c.CallOptions.DeleteProfile)], opts...) + opts = append((*c.CallOptions).DeleteProfile[0:len((*c.CallOptions).DeleteProfile):len((*c.CallOptions).DeleteProfile)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.profileClient.DeleteProfile(ctx, req, settings.GRPC...) @@ -308,13 +389,7 @@ func (c *ProfileClient) DeleteProfile(ctx context.Context, req *talentpb.DeleteP return err } -// SearchProfiles searches for profiles within a tenant. -// -// For example, search by raw queries “software engineer in Mountain View” or -// search by structured filters (location filter, education filter, etc.). -// -// See SearchProfilesRequest for more information. -func (c *ProfileClient) SearchProfiles(ctx context.Context, req *talentpb.SearchProfilesRequest, opts ...gax.CallOption) (*talentpb.SearchProfilesResponse, error) { +func (c *profileGRPCClient) SearchProfiles(ctx context.Context, req *talentpb.SearchProfilesRequest, opts ...gax.CallOption) (*talentpb.SearchProfilesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -322,7 +397,7 @@ func (c *ProfileClient) SearchProfiles(ctx context.Context, req *talentpb.Search } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SearchProfiles[0:len(c.CallOptions.SearchProfiles):len(c.CallOptions.SearchProfiles)], opts...) + opts = append((*c.CallOptions).SearchProfiles[0:len((*c.CallOptions).SearchProfiles):len((*c.CallOptions).SearchProfiles)], opts...) var resp *talentpb.SearchProfilesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/talent/apiv4beta1/profile_client_example_test.go b/talent/apiv4beta1/profile_client_example_test.go index f12a59058458..99a3d7a74e4d 100644 --- a/talent/apiv4beta1/profile_client_example_test.go +++ b/talent/apiv4beta1/profile_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewProfileClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleProfileClient_ListProfiles() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewProfileClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.ListProfilesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleProfileClient_ListProfiles() { } func ExampleProfileClient_CreateProfile() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewProfileClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateProfileRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleProfileClient_CreateProfile() { } func ExampleProfileClient_GetProfile() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewProfileClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.GetProfileRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleProfileClient_GetProfile() { } func ExampleProfileClient_UpdateProfile() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewProfileClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.UpdateProfileRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleProfileClient_DeleteProfile() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.DeleteProfileRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleProfileClient_DeleteProfile() { } func ExampleProfileClient_SearchProfiles() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewProfileClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.SearchProfilesRequest{ // TODO: Fill request struct fields. diff --git a/talent/apiv4beta1/tenant_client.go b/talent/apiv4beta1/tenant_client.go index 9d56b9e099da..fea06f2d135b 100644 --- a/talent/apiv4beta1/tenant_client.go +++ b/talent/apiv4beta1/tenant_client.go @@ -46,7 +46,7 @@ type TenantCallOptions struct { ListTenants []gax.CallOption } -func defaultTenantClientOptions() []option.ClientOption { +func defaultTenantGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("jobs.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("jobs.mtls.googleapis.com:443"), @@ -101,32 +101,103 @@ func defaultTenantCallOptions() *TenantCallOptions { } } +// internalTenantClient is an interface that defines the methods availaible from Cloud Talent Solution API. +type internalTenantClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateTenant(context.Context, *talentpb.CreateTenantRequest, ...gax.CallOption) (*talentpb.Tenant, error) + GetTenant(context.Context, *talentpb.GetTenantRequest, ...gax.CallOption) (*talentpb.Tenant, error) + UpdateTenant(context.Context, *talentpb.UpdateTenantRequest, ...gax.CallOption) (*talentpb.Tenant, error) + DeleteTenant(context.Context, *talentpb.DeleteTenantRequest, ...gax.CallOption) error + ListTenants(context.Context, *talentpb.ListTenantsRequest, ...gax.CallOption) *TenantIterator +} + // TenantClient is a client for interacting with Cloud Talent Solution API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// A service that handles tenant management, including CRUD and enumeration. type TenantClient struct { + // The internal transport-dependent client. + internalClient internalTenantClient + + // The call options for this service. + CallOptions *TenantCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *TenantClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *TenantClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *TenantClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateTenant creates a new tenant entity. +func (c *TenantClient) CreateTenant(ctx context.Context, req *talentpb.CreateTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { + return c.internalClient.CreateTenant(ctx, req, opts...) +} + +// GetTenant retrieves specified tenant. +func (c *TenantClient) GetTenant(ctx context.Context, req *talentpb.GetTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { + return c.internalClient.GetTenant(ctx, req, opts...) +} + +// UpdateTenant updates specified tenant. +func (c *TenantClient) UpdateTenant(ctx context.Context, req *talentpb.UpdateTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { + return c.internalClient.UpdateTenant(ctx, req, opts...) +} + +// DeleteTenant deletes specified tenant. +func (c *TenantClient) DeleteTenant(ctx context.Context, req *talentpb.DeleteTenantRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteTenant(ctx, req, opts...) +} + +// ListTenants lists all tenants associated with the project. +func (c *TenantClient) ListTenants(ctx context.Context, req *talentpb.ListTenantsRequest, opts ...gax.CallOption) *TenantIterator { + return c.internalClient.ListTenants(ctx, req, opts...) +} + +// tenantGRPCClient is a client for interacting with Cloud Talent Solution API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type tenantGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing TenantClient + CallOptions **TenantCallOptions + // The gRPC API client. tenantClient talentpb.TenantServiceClient - // The call options for this service. - CallOptions *TenantCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewTenantClient creates a new tenant service client. +// NewTenantClient creates a new tenant service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // A service that handles tenant management, including CRUD and enumeration. func NewTenantClient(ctx context.Context, opts ...option.ClientOption) (*TenantClient, error) { - clientOpts := defaultTenantClientOptions() - + clientOpts := defaultTenantGRPCClientOptions() if newTenantClientHook != nil { hookOpts, err := newTenantClientHook(ctx, clientHookParams{}) if err != nil { @@ -144,42 +215,44 @@ func NewTenantClient(ctx context.Context, opts ...option.ClientOption) (*TenantC if err != nil { return nil, err } - c := &TenantClient{ + client := TenantClient{CallOptions: defaultTenantCallOptions()} + + c := &tenantGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultTenantCallOptions(), - - tenantClient: talentpb.NewTenantServiceClient(connPool), + tenantClient: talentpb.NewTenantServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *TenantClient) Connection() *grpc.ClientConn { +func (c *tenantGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *TenantClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *TenantClient) setGoogleClientInfo(keyval ...string) { +func (c *tenantGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateTenant creates a new tenant entity. -func (c *TenantClient) CreateTenant(ctx context.Context, req *talentpb.CreateTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *tenantGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *tenantGRPCClient) CreateTenant(ctx context.Context, req *talentpb.CreateTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -187,7 +260,7 @@ func (c *TenantClient) CreateTenant(ctx context.Context, req *talentpb.CreateTen } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateTenant[0:len(c.CallOptions.CreateTenant):len(c.CallOptions.CreateTenant)], opts...) + opts = append((*c.CallOptions).CreateTenant[0:len((*c.CallOptions).CreateTenant):len((*c.CallOptions).CreateTenant)], opts...) var resp *talentpb.Tenant err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -200,8 +273,7 @@ func (c *TenantClient) CreateTenant(ctx context.Context, req *talentpb.CreateTen return resp, nil } -// GetTenant retrieves specified tenant. -func (c *TenantClient) GetTenant(ctx context.Context, req *talentpb.GetTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { +func (c *tenantGRPCClient) GetTenant(ctx context.Context, req *talentpb.GetTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -209,7 +281,7 @@ func (c *TenantClient) GetTenant(ctx context.Context, req *talentpb.GetTenantReq } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTenant[0:len(c.CallOptions.GetTenant):len(c.CallOptions.GetTenant)], opts...) + opts = append((*c.CallOptions).GetTenant[0:len((*c.CallOptions).GetTenant):len((*c.CallOptions).GetTenant)], opts...) var resp *talentpb.Tenant err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -222,8 +294,7 @@ func (c *TenantClient) GetTenant(ctx context.Context, req *talentpb.GetTenantReq return resp, nil } -// UpdateTenant updates specified tenant. -func (c *TenantClient) UpdateTenant(ctx context.Context, req *talentpb.UpdateTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { +func (c *tenantGRPCClient) UpdateTenant(ctx context.Context, req *talentpb.UpdateTenantRequest, opts ...gax.CallOption) (*talentpb.Tenant, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -231,7 +302,7 @@ func (c *TenantClient) UpdateTenant(ctx context.Context, req *talentpb.UpdateTen } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "tenant.name", url.QueryEscape(req.GetTenant().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateTenant[0:len(c.CallOptions.UpdateTenant):len(c.CallOptions.UpdateTenant)], opts...) + opts = append((*c.CallOptions).UpdateTenant[0:len((*c.CallOptions).UpdateTenant):len((*c.CallOptions).UpdateTenant)], opts...) var resp *talentpb.Tenant err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -244,8 +315,7 @@ func (c *TenantClient) UpdateTenant(ctx context.Context, req *talentpb.UpdateTen return resp, nil } -// DeleteTenant deletes specified tenant. -func (c *TenantClient) DeleteTenant(ctx context.Context, req *talentpb.DeleteTenantRequest, opts ...gax.CallOption) error { +func (c *tenantGRPCClient) DeleteTenant(ctx context.Context, req *talentpb.DeleteTenantRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 30000*time.Millisecond) defer cancel() @@ -253,7 +323,7 @@ func (c *TenantClient) DeleteTenant(ctx context.Context, req *talentpb.DeleteTen } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteTenant[0:len(c.CallOptions.DeleteTenant):len(c.CallOptions.DeleteTenant)], opts...) + opts = append((*c.CallOptions).DeleteTenant[0:len((*c.CallOptions).DeleteTenant):len((*c.CallOptions).DeleteTenant)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.tenantClient.DeleteTenant(ctx, req, settings.GRPC...) @@ -262,11 +332,10 @@ func (c *TenantClient) DeleteTenant(ctx context.Context, req *talentpb.DeleteTen return err } -// ListTenants lists all tenants associated with the project. -func (c *TenantClient) ListTenants(ctx context.Context, req *talentpb.ListTenantsRequest, opts ...gax.CallOption) *TenantIterator { +func (c *tenantGRPCClient) ListTenants(ctx context.Context, req *talentpb.ListTenantsRequest, opts ...gax.CallOption) *TenantIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTenants[0:len(c.CallOptions.ListTenants):len(c.CallOptions.ListTenants)], opts...) + opts = append((*c.CallOptions).ListTenants[0:len((*c.CallOptions).ListTenants):len((*c.CallOptions).ListTenants)], opts...) it := &TenantIterator{} req = proto.Clone(req).(*talentpb.ListTenantsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*talentpb.Tenant, string, error) { diff --git a/talent/apiv4beta1/tenant_client_example_test.go b/talent/apiv4beta1/tenant_client_example_test.go index 6e156ceee65a..425d38f180af 100644 --- a/talent/apiv4beta1/tenant_client_example_test.go +++ b/talent/apiv4beta1/tenant_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewTenantClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleTenantClient_CreateTenant() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewTenantClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.CreateTenantRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleTenantClient_CreateTenant() { } func ExampleTenantClient_GetTenant() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewTenantClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.GetTenantRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleTenantClient_GetTenant() { } func ExampleTenantClient_UpdateTenant() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - ctx := context.Background() c, err := talent.NewTenantClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.UpdateTenantRequest{ // TODO: Fill request struct fields. @@ -100,6 +99,7 @@ func ExampleTenantClient_DeleteTenant() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.DeleteTenantRequest{ // TODO: Fill request struct fields. @@ -111,14 +111,12 @@ func ExampleTenantClient_DeleteTenant() { } func ExampleTenantClient_ListTenants() { - // import talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := talent.NewTenantClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &talentpb.ListTenantsRequest{ // TODO: Fill request struct fields. diff --git a/texttospeech/apiv1/doc.go b/texttospeech/apiv1/doc.go index c81e2f543871..d2e52dc904d2 100644 --- a/texttospeech/apiv1/doc.go +++ b/texttospeech/apiv1/doc.go @@ -29,7 +29,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package texttospeech // import "cloud.google.com/go/texttospeech/apiv1" import ( @@ -49,7 +49,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/texttospeech/apiv1/text_to_speech_client.go b/texttospeech/apiv1/text_to_speech_client.go index 06f9d6d2681b..d2ee99081d64 100644 --- a/texttospeech/apiv1/text_to_speech_client.go +++ b/texttospeech/apiv1/text_to_speech_client.go @@ -39,7 +39,7 @@ type CallOptions struct { SynthesizeSpeech []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("texttospeech.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("texttospeech.mtls.googleapis.com:443"), @@ -80,32 +80,86 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Text-to-Speech API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListVoices(context.Context, *texttospeechpb.ListVoicesRequest, ...gax.CallOption) (*texttospeechpb.ListVoicesResponse, error) + SynthesizeSpeech(context.Context, *texttospeechpb.SynthesizeSpeechRequest, ...gax.CallOption) (*texttospeechpb.SynthesizeSpeechResponse, error) +} + // Client is a client for interacting with Cloud Text-to-Speech API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service that implements Google Cloud Text-to-Speech API. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListVoices returns a list of Voice supported for synthesis. +func (c *Client) ListVoices(ctx context.Context, req *texttospeechpb.ListVoicesRequest, opts ...gax.CallOption) (*texttospeechpb.ListVoicesResponse, error) { + return c.internalClient.ListVoices(ctx, req, opts...) +} + +// SynthesizeSpeech synthesizes speech synchronously: receive results after all text input +// has been processed. +func (c *Client) SynthesizeSpeech(ctx context.Context, req *texttospeechpb.SynthesizeSpeechRequest, opts ...gax.CallOption) (*texttospeechpb.SynthesizeSpeechResponse, error) { + return c.internalClient.SynthesizeSpeech(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Cloud Text-to-Speech API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client texttospeechpb.TextToSpeechClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new text to speech client. +// NewClient creates a new text to speech client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service that implements Google Cloud Text-to-Speech API. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -123,49 +177,51 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: texttospeechpb.NewTextToSpeechClient(connPool), + client: texttospeechpb.NewTextToSpeechClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListVoices returns a list of Voice supported for synthesis. -func (c *Client) ListVoices(ctx context.Context, req *texttospeechpb.ListVoicesRequest, opts ...gax.CallOption) (*texttospeechpb.ListVoicesResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ListVoices(ctx context.Context, req *texttospeechpb.ListVoicesRequest, opts ...gax.CallOption) (*texttospeechpb.ListVoicesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ListVoices[0:len(c.CallOptions.ListVoices):len(c.CallOptions.ListVoices)], opts...) + opts = append((*c.CallOptions).ListVoices[0:len((*c.CallOptions).ListVoices):len((*c.CallOptions).ListVoices)], opts...) var resp *texttospeechpb.ListVoicesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -178,16 +234,14 @@ func (c *Client) ListVoices(ctx context.Context, req *texttospeechpb.ListVoicesR return resp, nil } -// SynthesizeSpeech synthesizes speech synchronously: receive results after all text input -// has been processed. -func (c *Client) SynthesizeSpeech(ctx context.Context, req *texttospeechpb.SynthesizeSpeechRequest, opts ...gax.CallOption) (*texttospeechpb.SynthesizeSpeechResponse, error) { +func (c *gRPCClient) SynthesizeSpeech(ctx context.Context, req *texttospeechpb.SynthesizeSpeechRequest, opts ...gax.CallOption) (*texttospeechpb.SynthesizeSpeechResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.SynthesizeSpeech[0:len(c.CallOptions.SynthesizeSpeech):len(c.CallOptions.SynthesizeSpeech)], opts...) + opts = append((*c.CallOptions).SynthesizeSpeech[0:len((*c.CallOptions).SynthesizeSpeech):len((*c.CallOptions).SynthesizeSpeech)], opts...) var resp *texttospeechpb.SynthesizeSpeechResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/texttospeech/apiv1/text_to_speech_client_example_test.go b/texttospeech/apiv1/text_to_speech_client_example_test.go index 2b8a33499aa2..645bdea4c38d 100644 --- a/texttospeech/apiv1/text_to_speech_client_example_test.go +++ b/texttospeech/apiv1/text_to_speech_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ListVoices() { - // import texttospeechpb "google.golang.org/genproto/googleapis/cloud/texttospeech/v1" - ctx := context.Background() c, err := texttospeech.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &texttospeechpb.ListVoicesRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleClient_ListVoices() { } func ExampleClient_SynthesizeSpeech() { - // import texttospeechpb "google.golang.org/genproto/googleapis/cloud/texttospeech/v1" - ctx := context.Background() c, err := texttospeech.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &texttospeechpb.SynthesizeSpeechRequest{ // TODO: Fill request struct fields. diff --git a/trace/apiv1/doc.go b/trace/apiv1/doc.go index d565cdc982f0..4ac19f54c08f 100644 --- a/trace/apiv1/doc.go +++ b/trace/apiv1/doc.go @@ -32,7 +32,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package trace // import "cloud.google.com/go/trace/apiv1" import ( @@ -52,7 +52,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/trace/apiv1/trace_client.go b/trace/apiv1/trace_client.go index 761098514904..d97e1e2cb24e 100644 --- a/trace/apiv1/trace_client.go +++ b/trace/apiv1/trace_client.go @@ -44,7 +44,7 @@ type CallOptions struct { PatchTraces []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudtrace.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudtrace.mtls.googleapis.com:443"), @@ -97,27 +97,95 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Stackdriver Trace API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListTraces(context.Context, *cloudtracepb.ListTracesRequest, ...gax.CallOption) *TraceIterator + GetTrace(context.Context, *cloudtracepb.GetTraceRequest, ...gax.CallOption) (*cloudtracepb.Trace, error) + PatchTraces(context.Context, *cloudtracepb.PatchTracesRequest, ...gax.CallOption) error +} + // Client is a client for interacting with Stackdriver Trace API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// This file describes an API for collecting and viewing traces and spans +// within a trace. A Trace is a collection of spans corresponding to a single +// operation or set of operations for an application. A span is an individual +// timed event which forms a node of the trace tree. Spans for a single trace +// may span multiple services. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListTraces returns of a list of traces that match the specified filter conditions. +func (c *Client) ListTraces(ctx context.Context, req *cloudtracepb.ListTracesRequest, opts ...gax.CallOption) *TraceIterator { + return c.internalClient.ListTraces(ctx, req, opts...) +} + +// GetTrace gets a single trace by its ID. +func (c *Client) GetTrace(ctx context.Context, req *cloudtracepb.GetTraceRequest, opts ...gax.CallOption) (*cloudtracepb.Trace, error) { + return c.internalClient.GetTrace(ctx, req, opts...) +} + +// PatchTraces sends new traces to Stackdriver Trace or updates existing traces. If the ID +// of a trace that you send matches that of an existing trace, any fields +// in the existing trace and its spans are overwritten by the provided values, +// and any new fields provided are merged with the existing trace data. If the +// ID does not match, a new trace is created. +func (c *Client) PatchTraces(ctx context.Context, req *cloudtracepb.PatchTracesRequest, opts ...gax.CallOption) error { + return c.internalClient.PatchTraces(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Stackdriver Trace API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client cloudtracepb.TraceServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new trace service client. +// NewClient creates a new trace service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // This file describes an API for collecting and viewing traces and spans // within a trace. A Trace is a collection of spans corresponding to a single @@ -125,8 +193,7 @@ type Client struct { // timed event which forms a node of the trace tree. Spans for a single trace // may span multiple services. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -144,45 +211,47 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: cloudtracepb.NewTraceServiceClient(connPool), + client: cloudtracepb.NewTraceServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListTraces returns of a list of traces that match the specified filter conditions. -func (c *Client) ListTraces(ctx context.Context, req *cloudtracepb.ListTracesRequest, opts ...gax.CallOption) *TraceIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ListTraces(ctx context.Context, req *cloudtracepb.ListTracesRequest, opts ...gax.CallOption) *TraceIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListTraces[0:len(c.CallOptions.ListTraces):len(c.CallOptions.ListTraces)], opts...) + opts = append((*c.CallOptions).ListTraces[0:len((*c.CallOptions).ListTraces):len((*c.CallOptions).ListTraces)], opts...) it := &TraceIterator{} req = proto.Clone(req).(*cloudtracepb.ListTracesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*cloudtracepb.Trace, string, error) { @@ -219,8 +288,7 @@ func (c *Client) ListTraces(ctx context.Context, req *cloudtracepb.ListTracesReq return it } -// GetTrace gets a single trace by its ID. -func (c *Client) GetTrace(ctx context.Context, req *cloudtracepb.GetTraceRequest, opts ...gax.CallOption) (*cloudtracepb.Trace, error) { +func (c *gRPCClient) GetTrace(ctx context.Context, req *cloudtracepb.GetTraceRequest, opts ...gax.CallOption) (*cloudtracepb.Trace, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -228,7 +296,7 @@ func (c *Client) GetTrace(ctx context.Context, req *cloudtracepb.GetTraceRequest } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v&%s=%v", "project_id", url.QueryEscape(req.GetProjectId()), "trace_id", url.QueryEscape(req.GetTraceId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetTrace[0:len(c.CallOptions.GetTrace):len(c.CallOptions.GetTrace)], opts...) + opts = append((*c.CallOptions).GetTrace[0:len((*c.CallOptions).GetTrace):len((*c.CallOptions).GetTrace)], opts...) var resp *cloudtracepb.Trace err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -241,12 +309,7 @@ func (c *Client) GetTrace(ctx context.Context, req *cloudtracepb.GetTraceRequest return resp, nil } -// PatchTraces sends new traces to Stackdriver Trace or updates existing traces. If the ID -// of a trace that you send matches that of an existing trace, any fields -// in the existing trace and its spans are overwritten by the provided values, -// and any new fields provided are merged with the existing trace data. If the -// ID does not match, a new trace is created. -func (c *Client) PatchTraces(ctx context.Context, req *cloudtracepb.PatchTracesRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) PatchTraces(ctx context.Context, req *cloudtracepb.PatchTracesRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 45000*time.Millisecond) defer cancel() @@ -254,7 +317,7 @@ func (c *Client) PatchTraces(ctx context.Context, req *cloudtracepb.PatchTracesR } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "project_id", url.QueryEscape(req.GetProjectId()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PatchTraces[0:len(c.CallOptions.PatchTraces):len(c.CallOptions.PatchTraces)], opts...) + opts = append((*c.CallOptions).PatchTraces[0:len((*c.CallOptions).PatchTraces):len((*c.CallOptions).PatchTraces)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.PatchTraces(ctx, req, settings.GRPC...) diff --git a/trace/apiv1/trace_client_example_test.go b/trace/apiv1/trace_client_example_test.go index f8906d34ac50..2b090f24e46e 100644 --- a/trace/apiv1/trace_client_example_test.go +++ b/trace/apiv1/trace_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ListTraces() { - // import cloudtracepb "google.golang.org/genproto/googleapis/devtools/cloudtrace/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := trace.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudtracepb.ListTracesRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleClient_ListTraces() { } func ExampleClient_GetTrace() { - // import cloudtracepb "google.golang.org/genproto/googleapis/devtools/cloudtrace/v1" - ctx := context.Background() c, err := trace.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudtracepb.GetTraceRequest{ // TODO: Fill request struct fields. @@ -87,6 +86,7 @@ func ExampleClient_PatchTraces() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudtracepb.PatchTracesRequest{ // TODO: Fill request struct fields. diff --git a/trace/apiv2/doc.go b/trace/apiv2/doc.go index d2b628147c37..1f8f0e47075c 100644 --- a/trace/apiv2/doc.go +++ b/trace/apiv2/doc.go @@ -32,7 +32,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package trace // import "cloud.google.com/go/trace/apiv2" import ( @@ -52,7 +52,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/trace/apiv2/trace_client.go b/trace/apiv2/trace_client.go index 0f1d78a39575..2fb6a3e1a1b7 100644 --- a/trace/apiv2/trace_client.go +++ b/trace/apiv2/trace_client.go @@ -41,7 +41,7 @@ type CallOptions struct { CreateSpan []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("cloudtrace.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("cloudtrace.mtls.googleapis.com:443"), @@ -71,27 +71,86 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Stackdriver Trace API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + BatchWriteSpans(context.Context, *cloudtracepb.BatchWriteSpansRequest, ...gax.CallOption) error + CreateSpan(context.Context, *cloudtracepb.Span, ...gax.CallOption) (*cloudtracepb.Span, error) +} + // Client is a client for interacting with Stackdriver Trace API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// This file describes an API for collecting and viewing traces and spans +// within a trace. A Trace is a collection of spans corresponding to a single +// operation or set of operations for an application. A span is an individual +// timed event which forms a node of the trace tree. A single trace may +// contain span(s) from multiple services. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// BatchWriteSpans sends new spans to new or existing traces. You cannot update +// existing spans. +func (c *Client) BatchWriteSpans(ctx context.Context, req *cloudtracepb.BatchWriteSpansRequest, opts ...gax.CallOption) error { + return c.internalClient.BatchWriteSpans(ctx, req, opts...) +} + +// CreateSpan creates a new span. +func (c *Client) CreateSpan(ctx context.Context, req *cloudtracepb.Span, opts ...gax.CallOption) (*cloudtracepb.Span, error) { + return c.internalClient.CreateSpan(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Stackdriver Trace API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client cloudtracepb.TraceServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new trace service client. +// NewClient creates a new trace service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // This file describes an API for collecting and viewing traces and spans // within a trace. A Trace is a collection of spans corresponding to a single @@ -99,8 +158,7 @@ type Client struct { // timed event which forms a node of the trace tree. A single trace may // contain span(s) from multiple services. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -118,43 +176,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: cloudtracepb.NewTraceServiceClient(connPool), + client: cloudtracepb.NewTraceServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// BatchWriteSpans sends new spans to new or existing traces. You cannot update -// existing spans. -func (c *Client) BatchWriteSpans(ctx context.Context, req *cloudtracepb.BatchWriteSpansRequest, opts ...gax.CallOption) error { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) BatchWriteSpans(ctx context.Context, req *cloudtracepb.BatchWriteSpansRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -162,7 +221,7 @@ func (c *Client) BatchWriteSpans(ctx context.Context, req *cloudtracepb.BatchWri } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchWriteSpans[0:len(c.CallOptions.BatchWriteSpans):len(c.CallOptions.BatchWriteSpans)], opts...) + opts = append((*c.CallOptions).BatchWriteSpans[0:len((*c.CallOptions).BatchWriteSpans):len((*c.CallOptions).BatchWriteSpans)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.BatchWriteSpans(ctx, req, settings.GRPC...) @@ -171,8 +230,7 @@ func (c *Client) BatchWriteSpans(ctx context.Context, req *cloudtracepb.BatchWri return err } -// CreateSpan creates a new span. -func (c *Client) CreateSpan(ctx context.Context, req *cloudtracepb.Span, opts ...gax.CallOption) (*cloudtracepb.Span, error) { +func (c *gRPCClient) CreateSpan(ctx context.Context, req *cloudtracepb.Span, opts ...gax.CallOption) (*cloudtracepb.Span, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 120000*time.Millisecond) defer cancel() @@ -180,7 +238,7 @@ func (c *Client) CreateSpan(ctx context.Context, req *cloudtracepb.Span, opts .. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSpan[0:len(c.CallOptions.CreateSpan):len(c.CallOptions.CreateSpan)], opts...) + opts = append((*c.CallOptions).CreateSpan[0:len((*c.CallOptions).CreateSpan):len((*c.CallOptions).CreateSpan)], opts...) var resp *cloudtracepb.Span err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/trace/apiv2/trace_client_example_test.go b/trace/apiv2/trace_client_example_test.go index e42c5eb56118..d8cb80bef184 100644 --- a/trace/apiv2/trace_client_example_test.go +++ b/trace/apiv2/trace_client_example_test.go @@ -29,6 +29,8 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } @@ -39,6 +41,7 @@ func ExampleClient_BatchWriteSpans() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudtracepb.BatchWriteSpansRequest{ // TODO: Fill request struct fields. @@ -50,13 +53,12 @@ func ExampleClient_BatchWriteSpans() { } func ExampleClient_CreateSpan() { - // import cloudtracepb "google.golang.org/genproto/googleapis/devtools/cloudtrace/v2" - ctx := context.Background() c, err := trace.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &cloudtracepb.Span{ // TODO: Fill request struct fields. diff --git a/translate/apiv3/doc.go b/translate/apiv3/doc.go index 411b7946f166..a85aeeb50965 100644 --- a/translate/apiv3/doc.go +++ b/translate/apiv3/doc.go @@ -28,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package translate // import "cloud.google.com/go/translate/apiv3" import ( @@ -48,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/translate/apiv3/translation_client.go b/translate/apiv3/translation_client.go index 8e6424dbca7b..6b2a919ba060 100644 --- a/translate/apiv3/translation_client.go +++ b/translate/apiv3/translation_client.go @@ -52,7 +52,7 @@ type TranslationCallOptions struct { DeleteGlossary []gax.CallOption } -func defaultTranslationClientOptions() []option.ClientOption { +func defaultTranslationGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("translate.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("translate.mtls.googleapis.com:443"), @@ -121,37 +121,163 @@ func defaultTranslationCallOptions() *TranslationCallOptions { } } +// internalTranslationClient is an interface that defines the methods availaible from Cloud Translation API. +type internalTranslationClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + TranslateText(context.Context, *translatepb.TranslateTextRequest, ...gax.CallOption) (*translatepb.TranslateTextResponse, error) + DetectLanguage(context.Context, *translatepb.DetectLanguageRequest, ...gax.CallOption) (*translatepb.DetectLanguageResponse, error) + GetSupportedLanguages(context.Context, *translatepb.GetSupportedLanguagesRequest, ...gax.CallOption) (*translatepb.SupportedLanguages, error) + BatchTranslateText(context.Context, *translatepb.BatchTranslateTextRequest, ...gax.CallOption) (*BatchTranslateTextOperation, error) + BatchTranslateTextOperation(name string) *BatchTranslateTextOperation + CreateGlossary(context.Context, *translatepb.CreateGlossaryRequest, ...gax.CallOption) (*CreateGlossaryOperation, error) + CreateGlossaryOperation(name string) *CreateGlossaryOperation + ListGlossaries(context.Context, *translatepb.ListGlossariesRequest, ...gax.CallOption) *GlossaryIterator + GetGlossary(context.Context, *translatepb.GetGlossaryRequest, ...gax.CallOption) (*translatepb.Glossary, error) + DeleteGlossary(context.Context, *translatepb.DeleteGlossaryRequest, ...gax.CallOption) (*DeleteGlossaryOperation, error) + DeleteGlossaryOperation(name string) *DeleteGlossaryOperation +} + // TranslationClient is a client for interacting with Cloud Translation API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Provides natural language translation operations. type TranslationClient struct { + // The internal transport-dependent client. + internalClient internalTranslationClient + + // The call options for this service. + CallOptions *TranslationCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *TranslationClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *TranslationClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *TranslationClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// TranslateText translates input text and returns translated text. +func (c *TranslationClient) TranslateText(ctx context.Context, req *translatepb.TranslateTextRequest, opts ...gax.CallOption) (*translatepb.TranslateTextResponse, error) { + return c.internalClient.TranslateText(ctx, req, opts...) +} + +// DetectLanguage detects the language of text within a request. +func (c *TranslationClient) DetectLanguage(ctx context.Context, req *translatepb.DetectLanguageRequest, opts ...gax.CallOption) (*translatepb.DetectLanguageResponse, error) { + return c.internalClient.DetectLanguage(ctx, req, opts...) +} + +// GetSupportedLanguages returns a list of supported languages for translation. +func (c *TranslationClient) GetSupportedLanguages(ctx context.Context, req *translatepb.GetSupportedLanguagesRequest, opts ...gax.CallOption) (*translatepb.SupportedLanguages, error) { + return c.internalClient.GetSupportedLanguages(ctx, req, opts...) +} + +// BatchTranslateText translates a large volume of text in asynchronous batch mode. +// This function provides real-time output as the inputs are being processed. +// If caller cancels a request, the partial results (for an input file, it’s +// all or nothing) may still be available on the specified output location. +// +// This call returns immediately and you can +// use google.longrunning.Operation.name (at http://google.longrunning.Operation.name) to poll the status of the call. +func (c *TranslationClient) BatchTranslateText(ctx context.Context, req *translatepb.BatchTranslateTextRequest, opts ...gax.CallOption) (*BatchTranslateTextOperation, error) { + return c.internalClient.BatchTranslateText(ctx, req, opts...) +} + +// BatchTranslateTextOperation returns a new BatchTranslateTextOperation from a given name. +// The name must be that of a previously created BatchTranslateTextOperation, possibly from a different process. +func (c *TranslationClient) BatchTranslateTextOperation(name string) *BatchTranslateTextOperation { + return c.internalClient.BatchTranslateTextOperation(name) +} + +// CreateGlossary creates a glossary and returns the long-running operation. Returns +// NOT_FOUND, if the project doesn’t exist. +func (c *TranslationClient) CreateGlossary(ctx context.Context, req *translatepb.CreateGlossaryRequest, opts ...gax.CallOption) (*CreateGlossaryOperation, error) { + return c.internalClient.CreateGlossary(ctx, req, opts...) +} + +// CreateGlossaryOperation returns a new CreateGlossaryOperation from a given name. +// The name must be that of a previously created CreateGlossaryOperation, possibly from a different process. +func (c *TranslationClient) CreateGlossaryOperation(name string) *CreateGlossaryOperation { + return c.internalClient.CreateGlossaryOperation(name) +} + +// ListGlossaries lists glossaries in a project. Returns NOT_FOUND, if the project doesn’t +// exist. +func (c *TranslationClient) ListGlossaries(ctx context.Context, req *translatepb.ListGlossariesRequest, opts ...gax.CallOption) *GlossaryIterator { + return c.internalClient.ListGlossaries(ctx, req, opts...) +} + +// GetGlossary gets a glossary. Returns NOT_FOUND, if the glossary doesn’t +// exist. +func (c *TranslationClient) GetGlossary(ctx context.Context, req *translatepb.GetGlossaryRequest, opts ...gax.CallOption) (*translatepb.Glossary, error) { + return c.internalClient.GetGlossary(ctx, req, opts...) +} + +// DeleteGlossary deletes a glossary, or cancels glossary construction +// if the glossary isn’t created yet. +// Returns NOT_FOUND, if the glossary doesn’t exist. +func (c *TranslationClient) DeleteGlossary(ctx context.Context, req *translatepb.DeleteGlossaryRequest, opts ...gax.CallOption) (*DeleteGlossaryOperation, error) { + return c.internalClient.DeleteGlossary(ctx, req, opts...) +} + +// DeleteGlossaryOperation returns a new DeleteGlossaryOperation from a given name. +// The name must be that of a previously created DeleteGlossaryOperation, possibly from a different process. +func (c *TranslationClient) DeleteGlossaryOperation(name string) *DeleteGlossaryOperation { + return c.internalClient.DeleteGlossaryOperation(name) +} + +// translationGRPCClient is a client for interacting with Cloud Translation API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type translationGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing TranslationClient + CallOptions **TranslationCallOptions + // The gRPC API client. translationClient translatepb.TranslationServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *TranslationCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewTranslationClient creates a new translation service client. +// NewTranslationClient creates a new translation service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Provides natural language translation operations. func NewTranslationClient(ctx context.Context, opts ...option.ClientOption) (*TranslationClient, error) { - clientOpts := defaultTranslationClientOptions() - + clientOpts := defaultTranslationGRPCClientOptions() if newTranslationClientHook != nil { hookOpts, err := newTranslationClientHook(ctx, clientHookParams{}) if err != nil { @@ -169,16 +295,19 @@ func NewTranslationClient(ctx context.Context, opts ...option.ClientOption) (*Tr if err != nil { return nil, err } - c := &TranslationClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultTranslationCallOptions(), + client := TranslationClient{CallOptions: defaultTranslationCallOptions()} + c := &translationGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, translationClient: translatepb.NewTranslationServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -188,33 +317,33 @@ func NewTranslationClient(ctx context.Context, opts ...option.ClientOption) (*Tr // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *TranslationClient) Connection() *grpc.ClientConn { +func (c *translationGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *TranslationClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *TranslationClient) setGoogleClientInfo(keyval ...string) { +func (c *translationGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// TranslateText translates input text and returns translated text. -func (c *TranslationClient) TranslateText(ctx context.Context, req *translatepb.TranslateTextRequest, opts ...gax.CallOption) (*translatepb.TranslateTextResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *translationGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *translationGRPCClient) TranslateText(ctx context.Context, req *translatepb.TranslateTextRequest, opts ...gax.CallOption) (*translatepb.TranslateTextResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -222,7 +351,7 @@ func (c *TranslationClient) TranslateText(ctx context.Context, req *translatepb. } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TranslateText[0:len(c.CallOptions.TranslateText):len(c.CallOptions.TranslateText)], opts...) + opts = append((*c.CallOptions).TranslateText[0:len((*c.CallOptions).TranslateText):len((*c.CallOptions).TranslateText)], opts...) var resp *translatepb.TranslateTextResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -235,8 +364,7 @@ func (c *TranslationClient) TranslateText(ctx context.Context, req *translatepb. return resp, nil } -// DetectLanguage detects the language of text within a request. -func (c *TranslationClient) DetectLanguage(ctx context.Context, req *translatepb.DetectLanguageRequest, opts ...gax.CallOption) (*translatepb.DetectLanguageResponse, error) { +func (c *translationGRPCClient) DetectLanguage(ctx context.Context, req *translatepb.DetectLanguageRequest, opts ...gax.CallOption) (*translatepb.DetectLanguageResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -244,7 +372,7 @@ func (c *TranslationClient) DetectLanguage(ctx context.Context, req *translatepb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DetectLanguage[0:len(c.CallOptions.DetectLanguage):len(c.CallOptions.DetectLanguage)], opts...) + opts = append((*c.CallOptions).DetectLanguage[0:len((*c.CallOptions).DetectLanguage):len((*c.CallOptions).DetectLanguage)], opts...) var resp *translatepb.DetectLanguageResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -257,8 +385,7 @@ func (c *TranslationClient) DetectLanguage(ctx context.Context, req *translatepb return resp, nil } -// GetSupportedLanguages returns a list of supported languages for translation. -func (c *TranslationClient) GetSupportedLanguages(ctx context.Context, req *translatepb.GetSupportedLanguagesRequest, opts ...gax.CallOption) (*translatepb.SupportedLanguages, error) { +func (c *translationGRPCClient) GetSupportedLanguages(ctx context.Context, req *translatepb.GetSupportedLanguagesRequest, opts ...gax.CallOption) (*translatepb.SupportedLanguages, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -266,7 +393,7 @@ func (c *TranslationClient) GetSupportedLanguages(ctx context.Context, req *tran } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSupportedLanguages[0:len(c.CallOptions.GetSupportedLanguages):len(c.CallOptions.GetSupportedLanguages)], opts...) + opts = append((*c.CallOptions).GetSupportedLanguages[0:len((*c.CallOptions).GetSupportedLanguages):len((*c.CallOptions).GetSupportedLanguages)], opts...) var resp *translatepb.SupportedLanguages err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -279,14 +406,7 @@ func (c *TranslationClient) GetSupportedLanguages(ctx context.Context, req *tran return resp, nil } -// BatchTranslateText translates a large volume of text in asynchronous batch mode. -// This function provides real-time output as the inputs are being processed. -// If caller cancels a request, the partial results (for an input file, it’s -// all or nothing) may still be available on the specified output location. -// -// This call returns immediately and you can -// use google.longrunning.Operation.name (at http://google.longrunning.Operation.name) to poll the status of the call. -func (c *TranslationClient) BatchTranslateText(ctx context.Context, req *translatepb.BatchTranslateTextRequest, opts ...gax.CallOption) (*BatchTranslateTextOperation, error) { +func (c *translationGRPCClient) BatchTranslateText(ctx context.Context, req *translatepb.BatchTranslateTextRequest, opts ...gax.CallOption) (*BatchTranslateTextOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -294,7 +414,7 @@ func (c *TranslationClient) BatchTranslateText(ctx context.Context, req *transla } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchTranslateText[0:len(c.CallOptions.BatchTranslateText):len(c.CallOptions.BatchTranslateText)], opts...) + opts = append((*c.CallOptions).BatchTranslateText[0:len((*c.CallOptions).BatchTranslateText):len((*c.CallOptions).BatchTranslateText)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -305,13 +425,11 @@ func (c *TranslationClient) BatchTranslateText(ctx context.Context, req *transla return nil, err } return &BatchTranslateTextOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// CreateGlossary creates a glossary and returns the long-running operation. Returns -// NOT_FOUND, if the project doesn’t exist. -func (c *TranslationClient) CreateGlossary(ctx context.Context, req *translatepb.CreateGlossaryRequest, opts ...gax.CallOption) (*CreateGlossaryOperation, error) { +func (c *translationGRPCClient) CreateGlossary(ctx context.Context, req *translatepb.CreateGlossaryRequest, opts ...gax.CallOption) (*CreateGlossaryOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -319,7 +437,7 @@ func (c *TranslationClient) CreateGlossary(ctx context.Context, req *translatepb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateGlossary[0:len(c.CallOptions.CreateGlossary):len(c.CallOptions.CreateGlossary)], opts...) + opts = append((*c.CallOptions).CreateGlossary[0:len((*c.CallOptions).CreateGlossary):len((*c.CallOptions).CreateGlossary)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -330,16 +448,14 @@ func (c *TranslationClient) CreateGlossary(ctx context.Context, req *translatepb return nil, err } return &CreateGlossaryOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// ListGlossaries lists glossaries in a project. Returns NOT_FOUND, if the project doesn’t -// exist. -func (c *TranslationClient) ListGlossaries(ctx context.Context, req *translatepb.ListGlossariesRequest, opts ...gax.CallOption) *GlossaryIterator { +func (c *translationGRPCClient) ListGlossaries(ctx context.Context, req *translatepb.ListGlossariesRequest, opts ...gax.CallOption) *GlossaryIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListGlossaries[0:len(c.CallOptions.ListGlossaries):len(c.CallOptions.ListGlossaries)], opts...) + opts = append((*c.CallOptions).ListGlossaries[0:len((*c.CallOptions).ListGlossaries):len((*c.CallOptions).ListGlossaries)], opts...) it := &GlossaryIterator{} req = proto.Clone(req).(*translatepb.ListGlossariesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*translatepb.Glossary, string, error) { @@ -376,9 +492,7 @@ func (c *TranslationClient) ListGlossaries(ctx context.Context, req *translatepb return it } -// GetGlossary gets a glossary. Returns NOT_FOUND, if the glossary doesn’t -// exist. -func (c *TranslationClient) GetGlossary(ctx context.Context, req *translatepb.GetGlossaryRequest, opts ...gax.CallOption) (*translatepb.Glossary, error) { +func (c *translationGRPCClient) GetGlossary(ctx context.Context, req *translatepb.GetGlossaryRequest, opts ...gax.CallOption) (*translatepb.Glossary, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -386,7 +500,7 @@ func (c *TranslationClient) GetGlossary(ctx context.Context, req *translatepb.Ge } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetGlossary[0:len(c.CallOptions.GetGlossary):len(c.CallOptions.GetGlossary)], opts...) + opts = append((*c.CallOptions).GetGlossary[0:len((*c.CallOptions).GetGlossary):len((*c.CallOptions).GetGlossary)], opts...) var resp *translatepb.Glossary err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -399,10 +513,7 @@ func (c *TranslationClient) GetGlossary(ctx context.Context, req *translatepb.Ge return resp, nil } -// DeleteGlossary deletes a glossary, or cancels glossary construction -// if the glossary isn’t created yet. -// Returns NOT_FOUND, if the glossary doesn’t exist. -func (c *TranslationClient) DeleteGlossary(ctx context.Context, req *translatepb.DeleteGlossaryRequest, opts ...gax.CallOption) (*DeleteGlossaryOperation, error) { +func (c *translationGRPCClient) DeleteGlossary(ctx context.Context, req *translatepb.DeleteGlossaryRequest, opts ...gax.CallOption) (*DeleteGlossaryOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -410,7 +521,7 @@ func (c *TranslationClient) DeleteGlossary(ctx context.Context, req *translatepb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteGlossary[0:len(c.CallOptions.DeleteGlossary):len(c.CallOptions.DeleteGlossary)], opts...) + opts = append((*c.CallOptions).DeleteGlossary[0:len((*c.CallOptions).DeleteGlossary):len((*c.CallOptions).DeleteGlossary)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -421,7 +532,7 @@ func (c *TranslationClient) DeleteGlossary(ctx context.Context, req *translatepb return nil, err } return &DeleteGlossaryOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -432,9 +543,9 @@ type BatchTranslateTextOperation struct { // BatchTranslateTextOperation returns a new BatchTranslateTextOperation from a given name. // The name must be that of a previously created BatchTranslateTextOperation, possibly from a different process. -func (c *TranslationClient) BatchTranslateTextOperation(name string) *BatchTranslateTextOperation { +func (c *translationGRPCClient) BatchTranslateTextOperation(name string) *BatchTranslateTextOperation { return &BatchTranslateTextOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -501,9 +612,9 @@ type CreateGlossaryOperation struct { // CreateGlossaryOperation returns a new CreateGlossaryOperation from a given name. // The name must be that of a previously created CreateGlossaryOperation, possibly from a different process. -func (c *TranslationClient) CreateGlossaryOperation(name string) *CreateGlossaryOperation { +func (c *translationGRPCClient) CreateGlossaryOperation(name string) *CreateGlossaryOperation { return &CreateGlossaryOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -570,9 +681,9 @@ type DeleteGlossaryOperation struct { // DeleteGlossaryOperation returns a new DeleteGlossaryOperation from a given name. // The name must be that of a previously created DeleteGlossaryOperation, possibly from a different process. -func (c *TranslationClient) DeleteGlossaryOperation(name string) *DeleteGlossaryOperation { +func (c *translationGRPCClient) DeleteGlossaryOperation(name string) *DeleteGlossaryOperation { return &DeleteGlossaryOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/translate/apiv3/translation_client_example_test.go b/translate/apiv3/translation_client_example_test.go index 66ba70645b97..693ac440811c 100644 --- a/translate/apiv3/translation_client_example_test.go +++ b/translate/apiv3/translation_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewTranslationClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleTranslationClient_TranslateText() { - // import translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" - ctx := context.Background() c, err := translate.NewTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &translatepb.TranslateTextRequest{ // TODO: Fill request struct fields. @@ -55,13 +56,12 @@ func ExampleTranslationClient_TranslateText() { } func ExampleTranslationClient_DetectLanguage() { - // import translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" - ctx := context.Background() c, err := translate.NewTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &translatepb.DetectLanguageRequest{ // TODO: Fill request struct fields. @@ -75,13 +75,12 @@ func ExampleTranslationClient_DetectLanguage() { } func ExampleTranslationClient_GetSupportedLanguages() { - // import translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" - ctx := context.Background() c, err := translate.NewTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &translatepb.GetSupportedLanguagesRequest{ // TODO: Fill request struct fields. @@ -95,13 +94,12 @@ func ExampleTranslationClient_GetSupportedLanguages() { } func ExampleTranslationClient_BatchTranslateText() { - // import translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" - ctx := context.Background() c, err := translate.NewTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &translatepb.BatchTranslateTextRequest{ // TODO: Fill request struct fields. @@ -120,13 +118,12 @@ func ExampleTranslationClient_BatchTranslateText() { } func ExampleTranslationClient_CreateGlossary() { - // import translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" - ctx := context.Background() c, err := translate.NewTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &translatepb.CreateGlossaryRequest{ // TODO: Fill request struct fields. @@ -145,14 +142,12 @@ func ExampleTranslationClient_CreateGlossary() { } func ExampleTranslationClient_ListGlossaries() { - // import translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := translate.NewTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &translatepb.ListGlossariesRequest{ // TODO: Fill request struct fields. @@ -172,13 +167,12 @@ func ExampleTranslationClient_ListGlossaries() { } func ExampleTranslationClient_GetGlossary() { - // import translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" - ctx := context.Background() c, err := translate.NewTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &translatepb.GetGlossaryRequest{ // TODO: Fill request struct fields. @@ -192,13 +186,12 @@ func ExampleTranslationClient_GetGlossary() { } func ExampleTranslationClient_DeleteGlossary() { - // import translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3" - ctx := context.Background() c, err := translate.NewTranslationClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &translatepb.DeleteGlossaryRequest{ // TODO: Fill request struct fields. diff --git a/video/transcoder/apiv1beta1/doc.go b/video/transcoder/apiv1beta1/doc.go index 52b51510947f..b2d815e4d039 100644 --- a/video/transcoder/apiv1beta1/doc.go +++ b/video/transcoder/apiv1beta1/doc.go @@ -20,6 +20,8 @@ // This API converts video files into formats suitable for consumer // distribution. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -29,7 +31,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package transcoder // import "cloud.google.com/go/video/transcoder/apiv1beta1" import ( @@ -49,7 +51,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/video/transcoder/apiv1beta1/transcoder_client.go b/video/transcoder/apiv1beta1/transcoder_client.go index 0012d1b49e45..46747d371da3 100644 --- a/video/transcoder/apiv1beta1/transcoder_client.go +++ b/video/transcoder/apiv1beta1/transcoder_client.go @@ -48,7 +48,7 @@ type CallOptions struct { DeleteJobTemplate []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("transcoder.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("transcoder.mtls.googleapis.com:443"), @@ -73,27 +73,122 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Transcoder API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateJob(context.Context, *transcoderpb.CreateJobRequest, ...gax.CallOption) (*transcoderpb.Job, error) + ListJobs(context.Context, *transcoderpb.ListJobsRequest, ...gax.CallOption) *JobIterator + GetJob(context.Context, *transcoderpb.GetJobRequest, ...gax.CallOption) (*transcoderpb.Job, error) + DeleteJob(context.Context, *transcoderpb.DeleteJobRequest, ...gax.CallOption) error + CreateJobTemplate(context.Context, *transcoderpb.CreateJobTemplateRequest, ...gax.CallOption) (*transcoderpb.JobTemplate, error) + ListJobTemplates(context.Context, *transcoderpb.ListJobTemplatesRequest, ...gax.CallOption) *JobTemplateIterator + GetJobTemplate(context.Context, *transcoderpb.GetJobTemplateRequest, ...gax.CallOption) (*transcoderpb.JobTemplate, error) + DeleteJobTemplate(context.Context, *transcoderpb.DeleteJobTemplateRequest, ...gax.CallOption) error +} + // Client is a client for interacting with Transcoder API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Using the Transcoder API, you can queue asynchronous jobs for transcoding +// media into various output formats. Output formats may include different +// streaming standards such as HTTP Live Streaming (HLS) and Dynamic Adaptive +// Streaming over HTTP (DASH). You can also customize jobs using advanced +// features such as Digital Rights Management (DRM), audio equalization, content +// concatenation, and digital ad-stitch ready content generation. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateJob creates a job in the specified region. +func (c *Client) CreateJob(ctx context.Context, req *transcoderpb.CreateJobRequest, opts ...gax.CallOption) (*transcoderpb.Job, error) { + return c.internalClient.CreateJob(ctx, req, opts...) +} + +// ListJobs lists jobs in the specified region. +func (c *Client) ListJobs(ctx context.Context, req *transcoderpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { + return c.internalClient.ListJobs(ctx, req, opts...) +} + +// GetJob returns the job data. +func (c *Client) GetJob(ctx context.Context, req *transcoderpb.GetJobRequest, opts ...gax.CallOption) (*transcoderpb.Job, error) { + return c.internalClient.GetJob(ctx, req, opts...) +} + +// DeleteJob deletes a job. +func (c *Client) DeleteJob(ctx context.Context, req *transcoderpb.DeleteJobRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteJob(ctx, req, opts...) +} + +// CreateJobTemplate creates a job template in the specified region. +func (c *Client) CreateJobTemplate(ctx context.Context, req *transcoderpb.CreateJobTemplateRequest, opts ...gax.CallOption) (*transcoderpb.JobTemplate, error) { + return c.internalClient.CreateJobTemplate(ctx, req, opts...) +} + +// ListJobTemplates lists job templates in the specified region. +func (c *Client) ListJobTemplates(ctx context.Context, req *transcoderpb.ListJobTemplatesRequest, opts ...gax.CallOption) *JobTemplateIterator { + return c.internalClient.ListJobTemplates(ctx, req, opts...) +} + +// GetJobTemplate returns the job template data. +func (c *Client) GetJobTemplate(ctx context.Context, req *transcoderpb.GetJobTemplateRequest, opts ...gax.CallOption) (*transcoderpb.JobTemplate, error) { + return c.internalClient.GetJobTemplate(ctx, req, opts...) +} + +// DeleteJobTemplate deletes a job template. +func (c *Client) DeleteJobTemplate(ctx context.Context, req *transcoderpb.DeleteJobTemplateRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteJobTemplate(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Transcoder API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client transcoderpb.TranscoderServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new transcoder service client. +// NewClient creates a new transcoder service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Using the Transcoder API, you can queue asynchronous jobs for transcoding // media into various output formats. Output formats may include different @@ -102,8 +197,7 @@ type Client struct { // features such as Digital Rights Management (DRM), audio equalization, content // concatenation, and digital ad-stitch ready content generation. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -121,42 +215,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: transcoderpb.NewTranscoderServiceClient(connPool), + client: transcoderpb.NewTranscoderServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateJob creates a job in the specified region. -func (c *Client) CreateJob(ctx context.Context, req *transcoderpb.CreateJobRequest, opts ...gax.CallOption) (*transcoderpb.Job, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateJob(ctx context.Context, req *transcoderpb.CreateJobRequest, opts ...gax.CallOption) (*transcoderpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -164,7 +260,7 @@ func (c *Client) CreateJob(ctx context.Context, req *transcoderpb.CreateJobReque } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateJob[0:len(c.CallOptions.CreateJob):len(c.CallOptions.CreateJob)], opts...) + opts = append((*c.CallOptions).CreateJob[0:len((*c.CallOptions).CreateJob):len((*c.CallOptions).CreateJob)], opts...) var resp *transcoderpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -177,11 +273,10 @@ func (c *Client) CreateJob(ctx context.Context, req *transcoderpb.CreateJobReque return resp, nil } -// ListJobs lists jobs in the specified region. -func (c *Client) ListJobs(ctx context.Context, req *transcoderpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { +func (c *gRPCClient) ListJobs(ctx context.Context, req *transcoderpb.ListJobsRequest, opts ...gax.CallOption) *JobIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListJobs[0:len(c.CallOptions.ListJobs):len(c.CallOptions.ListJobs)], opts...) + opts = append((*c.CallOptions).ListJobs[0:len((*c.CallOptions).ListJobs):len((*c.CallOptions).ListJobs)], opts...) it := &JobIterator{} req = proto.Clone(req).(*transcoderpb.ListJobsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*transcoderpb.Job, string, error) { @@ -218,8 +313,7 @@ func (c *Client) ListJobs(ctx context.Context, req *transcoderpb.ListJobsRequest return it } -// GetJob returns the job data. -func (c *Client) GetJob(ctx context.Context, req *transcoderpb.GetJobRequest, opts ...gax.CallOption) (*transcoderpb.Job, error) { +func (c *gRPCClient) GetJob(ctx context.Context, req *transcoderpb.GetJobRequest, opts ...gax.CallOption) (*transcoderpb.Job, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -227,7 +321,7 @@ func (c *Client) GetJob(ctx context.Context, req *transcoderpb.GetJobRequest, op } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetJob[0:len(c.CallOptions.GetJob):len(c.CallOptions.GetJob)], opts...) + opts = append((*c.CallOptions).GetJob[0:len((*c.CallOptions).GetJob):len((*c.CallOptions).GetJob)], opts...) var resp *transcoderpb.Job err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -240,8 +334,7 @@ func (c *Client) GetJob(ctx context.Context, req *transcoderpb.GetJobRequest, op return resp, nil } -// DeleteJob deletes a job. -func (c *Client) DeleteJob(ctx context.Context, req *transcoderpb.DeleteJobRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteJob(ctx context.Context, req *transcoderpb.DeleteJobRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -249,7 +342,7 @@ func (c *Client) DeleteJob(ctx context.Context, req *transcoderpb.DeleteJobReque } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteJob[0:len(c.CallOptions.DeleteJob):len(c.CallOptions.DeleteJob)], opts...) + opts = append((*c.CallOptions).DeleteJob[0:len((*c.CallOptions).DeleteJob):len((*c.CallOptions).DeleteJob)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteJob(ctx, req, settings.GRPC...) @@ -258,8 +351,7 @@ func (c *Client) DeleteJob(ctx context.Context, req *transcoderpb.DeleteJobReque return err } -// CreateJobTemplate creates a job template in the specified region. -func (c *Client) CreateJobTemplate(ctx context.Context, req *transcoderpb.CreateJobTemplateRequest, opts ...gax.CallOption) (*transcoderpb.JobTemplate, error) { +func (c *gRPCClient) CreateJobTemplate(ctx context.Context, req *transcoderpb.CreateJobTemplateRequest, opts ...gax.CallOption) (*transcoderpb.JobTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -267,7 +359,7 @@ func (c *Client) CreateJobTemplate(ctx context.Context, req *transcoderpb.Create } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateJobTemplate[0:len(c.CallOptions.CreateJobTemplate):len(c.CallOptions.CreateJobTemplate)], opts...) + opts = append((*c.CallOptions).CreateJobTemplate[0:len((*c.CallOptions).CreateJobTemplate):len((*c.CallOptions).CreateJobTemplate)], opts...) var resp *transcoderpb.JobTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -280,11 +372,10 @@ func (c *Client) CreateJobTemplate(ctx context.Context, req *transcoderpb.Create return resp, nil } -// ListJobTemplates lists job templates in the specified region. -func (c *Client) ListJobTemplates(ctx context.Context, req *transcoderpb.ListJobTemplatesRequest, opts ...gax.CallOption) *JobTemplateIterator { +func (c *gRPCClient) ListJobTemplates(ctx context.Context, req *transcoderpb.ListJobTemplatesRequest, opts ...gax.CallOption) *JobTemplateIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListJobTemplates[0:len(c.CallOptions.ListJobTemplates):len(c.CallOptions.ListJobTemplates)], opts...) + opts = append((*c.CallOptions).ListJobTemplates[0:len((*c.CallOptions).ListJobTemplates):len((*c.CallOptions).ListJobTemplates)], opts...) it := &JobTemplateIterator{} req = proto.Clone(req).(*transcoderpb.ListJobTemplatesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*transcoderpb.JobTemplate, string, error) { @@ -321,8 +412,7 @@ func (c *Client) ListJobTemplates(ctx context.Context, req *transcoderpb.ListJob return it } -// GetJobTemplate returns the job template data. -func (c *Client) GetJobTemplate(ctx context.Context, req *transcoderpb.GetJobTemplateRequest, opts ...gax.CallOption) (*transcoderpb.JobTemplate, error) { +func (c *gRPCClient) GetJobTemplate(ctx context.Context, req *transcoderpb.GetJobTemplateRequest, opts ...gax.CallOption) (*transcoderpb.JobTemplate, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -330,7 +420,7 @@ func (c *Client) GetJobTemplate(ctx context.Context, req *transcoderpb.GetJobTem } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetJobTemplate[0:len(c.CallOptions.GetJobTemplate):len(c.CallOptions.GetJobTemplate)], opts...) + opts = append((*c.CallOptions).GetJobTemplate[0:len((*c.CallOptions).GetJobTemplate):len((*c.CallOptions).GetJobTemplate)], opts...) var resp *transcoderpb.JobTemplate err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -343,8 +433,7 @@ func (c *Client) GetJobTemplate(ctx context.Context, req *transcoderpb.GetJobTem return resp, nil } -// DeleteJobTemplate deletes a job template. -func (c *Client) DeleteJobTemplate(ctx context.Context, req *transcoderpb.DeleteJobTemplateRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteJobTemplate(ctx context.Context, req *transcoderpb.DeleteJobTemplateRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -352,7 +441,7 @@ func (c *Client) DeleteJobTemplate(ctx context.Context, req *transcoderpb.Delete } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteJobTemplate[0:len(c.CallOptions.DeleteJobTemplate):len(c.CallOptions.DeleteJobTemplate)], opts...) + opts = append((*c.CallOptions).DeleteJobTemplate[0:len((*c.CallOptions).DeleteJobTemplate):len((*c.CallOptions).DeleteJobTemplate)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteJobTemplate(ctx, req, settings.GRPC...) diff --git a/video/transcoder/apiv1beta1/transcoder_client_example_test.go b/video/transcoder/apiv1beta1/transcoder_client_example_test.go index fa53c1ced6a9..30e2c1315183 100644 --- a/video/transcoder/apiv1beta1/transcoder_client_example_test.go +++ b/video/transcoder/apiv1beta1/transcoder_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateJob() { - // import transcoderpb "google.golang.org/genproto/googleapis/cloud/video/transcoder/v1beta1" - ctx := context.Background() c, err := transcoder.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &transcoderpb.CreateJobRequest{ // TODO: Fill request struct fields. @@ -55,14 +56,12 @@ func ExampleClient_CreateJob() { } func ExampleClient_ListJobs() { - // import transcoderpb "google.golang.org/genproto/googleapis/cloud/video/transcoder/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := transcoder.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &transcoderpb.ListJobsRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleClient_ListJobs() { } func ExampleClient_GetJob() { - // import transcoderpb "google.golang.org/genproto/googleapis/cloud/video/transcoder/v1beta1" - ctx := context.Background() c, err := transcoder.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &transcoderpb.GetJobRequest{ // TODO: Fill request struct fields. @@ -107,6 +105,7 @@ func ExampleClient_DeleteJob() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &transcoderpb.DeleteJobRequest{ // TODO: Fill request struct fields. @@ -118,13 +117,12 @@ func ExampleClient_DeleteJob() { } func ExampleClient_CreateJobTemplate() { - // import transcoderpb "google.golang.org/genproto/googleapis/cloud/video/transcoder/v1beta1" - ctx := context.Background() c, err := transcoder.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &transcoderpb.CreateJobTemplateRequest{ // TODO: Fill request struct fields. @@ -138,14 +136,12 @@ func ExampleClient_CreateJobTemplate() { } func ExampleClient_ListJobTemplates() { - // import transcoderpb "google.golang.org/genproto/googleapis/cloud/video/transcoder/v1beta1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := transcoder.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &transcoderpb.ListJobTemplatesRequest{ // TODO: Fill request struct fields. @@ -165,13 +161,12 @@ func ExampleClient_ListJobTemplates() { } func ExampleClient_GetJobTemplate() { - // import transcoderpb "google.golang.org/genproto/googleapis/cloud/video/transcoder/v1beta1" - ctx := context.Background() c, err := transcoder.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &transcoderpb.GetJobTemplateRequest{ // TODO: Fill request struct fields. @@ -190,6 +185,7 @@ func ExampleClient_DeleteJobTemplate() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &transcoderpb.DeleteJobTemplateRequest{ // TODO: Fill request struct fields. diff --git a/videointelligence/apiv1/doc.go b/videointelligence/apiv1/doc.go index 2a56641fba13..1058139aa5d8 100644 --- a/videointelligence/apiv1/doc.go +++ b/videointelligence/apiv1/doc.go @@ -30,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package videointelligence // import "cloud.google.com/go/videointelligence/apiv1" import ( @@ -50,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/videointelligence/apiv1/video_intelligence_client.go b/videointelligence/apiv1/video_intelligence_client.go index 836ba15eb4a5..95f03044a287 100644 --- a/videointelligence/apiv1/video_intelligence_client.go +++ b/videointelligence/apiv1/video_intelligence_client.go @@ -41,7 +41,7 @@ type CallOptions struct { AnnotateVideo []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("videointelligence.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("videointelligence.mtls.googleapis.com:443"), @@ -70,37 +70,99 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Cloud Video Intelligence API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + AnnotateVideo(context.Context, *videointelligencepb.AnnotateVideoRequest, ...gax.CallOption) (*AnnotateVideoOperation, error) + AnnotateVideoOperation(name string) *AnnotateVideoOperation +} + // Client is a client for interacting with Cloud Video Intelligence API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service that implements the Video Intelligence API. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// AnnotateVideo performs asynchronous video annotation. Progress and results can be +// retrieved through the google.longrunning.Operations interface. +// Operation.metadata contains AnnotateVideoProgress (progress). +// Operation.response contains AnnotateVideoResponse (results). +func (c *Client) AnnotateVideo(ctx context.Context, req *videointelligencepb.AnnotateVideoRequest, opts ...gax.CallOption) (*AnnotateVideoOperation, error) { + return c.internalClient.AnnotateVideo(ctx, req, opts...) +} + +// AnnotateVideoOperation returns a new AnnotateVideoOperation from a given name. +// The name must be that of a previously created AnnotateVideoOperation, possibly from a different process. +func (c *Client) AnnotateVideoOperation(name string) *AnnotateVideoOperation { + return c.internalClient.AnnotateVideoOperation(name) +} + +// gRPCClient is a client for interacting with Cloud Video Intelligence API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client videointelligencepb.VideoIntelligenceServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new video intelligence service client. +// NewClient creates a new video intelligence service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service that implements the Video Intelligence API. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -118,16 +180,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: videointelligencepb.NewVideoIntelligenceServiceClient(connPool), + client: videointelligencepb.NewVideoIntelligenceServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -137,43 +202,40 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// AnnotateVideo performs asynchronous video annotation. Progress and results can be -// retrieved through the google.longrunning.Operations interface. -// Operation.metadata contains AnnotateVideoProgress (progress). -// Operation.response contains AnnotateVideoResponse (results). -func (c *Client) AnnotateVideo(ctx context.Context, req *videointelligencepb.AnnotateVideoRequest, opts ...gax.CallOption) (*AnnotateVideoOperation, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) AnnotateVideo(ctx context.Context, req *videointelligencepb.AnnotateVideoRequest, opts ...gax.CallOption) (*AnnotateVideoOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.AnnotateVideo[0:len(c.CallOptions.AnnotateVideo):len(c.CallOptions.AnnotateVideo)], opts...) + opts = append((*c.CallOptions).AnnotateVideo[0:len((*c.CallOptions).AnnotateVideo):len((*c.CallOptions).AnnotateVideo)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -184,7 +246,7 @@ func (c *Client) AnnotateVideo(ctx context.Context, req *videointelligencepb.Ann return nil, err } return &AnnotateVideoOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -195,9 +257,9 @@ type AnnotateVideoOperation struct { // AnnotateVideoOperation returns a new AnnotateVideoOperation from a given name. // The name must be that of a previously created AnnotateVideoOperation, possibly from a different process. -func (c *Client) AnnotateVideoOperation(name string) *AnnotateVideoOperation { +func (c *gRPCClient) AnnotateVideoOperation(name string) *AnnotateVideoOperation { return &AnnotateVideoOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/videointelligence/apiv1/video_intelligence_client_example_test.go b/videointelligence/apiv1/video_intelligence_client_example_test.go index e38f7f6b72fb..317f5f1c36a9 100644 --- a/videointelligence/apiv1/video_intelligence_client_example_test.go +++ b/videointelligence/apiv1/video_intelligence_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_AnnotateVideo() { - // import videointelligencepb "google.golang.org/genproto/googleapis/cloud/videointelligence/v1" - ctx := context.Background() c, err := videointelligence.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &videointelligencepb.AnnotateVideoRequest{ // TODO: Fill request struct fields. diff --git a/videointelligence/apiv1beta2/doc.go b/videointelligence/apiv1beta2/doc.go index a2e10a1ded1b..998e057b6174 100644 --- a/videointelligence/apiv1beta2/doc.go +++ b/videointelligence/apiv1beta2/doc.go @@ -21,6 +21,8 @@ // specifies the region for annotation and transcribes speech to text. // Supports both asynchronous API and streaming API. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -30,7 +32,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package videointelligence // import "cloud.google.com/go/videointelligence/apiv1beta2" import ( @@ -50,7 +52,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/videointelligence/apiv1beta2/video_intelligence_client.go b/videointelligence/apiv1beta2/video_intelligence_client.go index 24c691d9a489..757c1605755d 100644 --- a/videointelligence/apiv1beta2/video_intelligence_client.go +++ b/videointelligence/apiv1beta2/video_intelligence_client.go @@ -41,7 +41,7 @@ type CallOptions struct { AnnotateVideo []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("videointelligence.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("videointelligence.mtls.googleapis.com:443"), @@ -70,37 +70,99 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Google Cloud Video Intelligence API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + AnnotateVideo(context.Context, *videointelligencepb.AnnotateVideoRequest, ...gax.CallOption) (*AnnotateVideoOperation, error) + AnnotateVideoOperation(name string) *AnnotateVideoOperation +} + // Client is a client for interacting with Google Cloud Video Intelligence API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service that implements Google Cloud Video Intelligence API. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// AnnotateVideo performs asynchronous video annotation. Progress and results can be +// retrieved through the google.longrunning.Operations interface. +// Operation.metadata contains AnnotateVideoProgress (progress). +// Operation.response contains AnnotateVideoResponse (results). +func (c *Client) AnnotateVideo(ctx context.Context, req *videointelligencepb.AnnotateVideoRequest, opts ...gax.CallOption) (*AnnotateVideoOperation, error) { + return c.internalClient.AnnotateVideo(ctx, req, opts...) +} + +// AnnotateVideoOperation returns a new AnnotateVideoOperation from a given name. +// The name must be that of a previously created AnnotateVideoOperation, possibly from a different process. +func (c *Client) AnnotateVideoOperation(name string) *AnnotateVideoOperation { + return c.internalClient.AnnotateVideoOperation(name) +} + +// gRPCClient is a client for interacting with Google Cloud Video Intelligence API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client videointelligencepb.VideoIntelligenceServiceClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new video intelligence service client. +// NewClient creates a new video intelligence service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service that implements Google Cloud Video Intelligence API. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -118,16 +180,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: videointelligencepb.NewVideoIntelligenceServiceClient(connPool), + client: videointelligencepb.NewVideoIntelligenceServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -137,43 +202,40 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// AnnotateVideo performs asynchronous video annotation. Progress and results can be -// retrieved through the google.longrunning.Operations interface. -// Operation.metadata contains AnnotateVideoProgress (progress). -// Operation.response contains AnnotateVideoResponse (results). -func (c *Client) AnnotateVideo(ctx context.Context, req *videointelligencepb.AnnotateVideoRequest, opts ...gax.CallOption) (*AnnotateVideoOperation, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) AnnotateVideo(ctx context.Context, req *videointelligencepb.AnnotateVideoRequest, opts ...gax.CallOption) (*AnnotateVideoOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.AnnotateVideo[0:len(c.CallOptions.AnnotateVideo):len(c.CallOptions.AnnotateVideo)], opts...) + opts = append((*c.CallOptions).AnnotateVideo[0:len((*c.CallOptions).AnnotateVideo):len((*c.CallOptions).AnnotateVideo)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -184,7 +246,7 @@ func (c *Client) AnnotateVideo(ctx context.Context, req *videointelligencepb.Ann return nil, err } return &AnnotateVideoOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -195,9 +257,9 @@ type AnnotateVideoOperation struct { // AnnotateVideoOperation returns a new AnnotateVideoOperation from a given name. // The name must be that of a previously created AnnotateVideoOperation, possibly from a different process. -func (c *Client) AnnotateVideoOperation(name string) *AnnotateVideoOperation { +func (c *gRPCClient) AnnotateVideoOperation(name string) *AnnotateVideoOperation { return &AnnotateVideoOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/videointelligence/apiv1beta2/video_intelligence_client_example_test.go b/videointelligence/apiv1beta2/video_intelligence_client_example_test.go index 6906e7ce65d1..d9b4c0c4f32d 100644 --- a/videointelligence/apiv1beta2/video_intelligence_client_example_test.go +++ b/videointelligence/apiv1beta2/video_intelligence_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_AnnotateVideo() { - // import videointelligencepb "google.golang.org/genproto/googleapis/cloud/videointelligence/v1beta2" - ctx := context.Background() c, err := videointelligence.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &videointelligencepb.AnnotateVideoRequest{ // TODO: Fill request struct fields. diff --git a/vision/apiv1/doc.go b/vision/apiv1/doc.go index 053403010e51..0e368ad261c9 100644 --- a/vision/apiv1/doc.go +++ b/vision/apiv1/doc.go @@ -30,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package vision // import "cloud.google.com/go/vision/apiv1" import ( @@ -50,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/vision/apiv1/image_annotator_client.go b/vision/apiv1/image_annotator_client.go index 64c1115aae04..cb52bad2a2a5 100644 --- a/vision/apiv1/image_annotator_client.go +++ b/vision/apiv1/image_annotator_client.go @@ -46,7 +46,7 @@ type ImageAnnotatorCallOptions struct { AsyncBatchAnnotateFiles []gax.CallOption } -func defaultImageAnnotatorClientOptions() []option.ClientOption { +func defaultImageAnnotatorGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("vision.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("vision.mtls.googleapis.com:443"), @@ -111,39 +111,144 @@ func defaultImageAnnotatorCallOptions() *ImageAnnotatorCallOptions { } } +// internalImageAnnotatorClient is an interface that defines the methods availaible from Cloud Vision API. +type internalImageAnnotatorClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + BatchAnnotateImages(context.Context, *visionpb.BatchAnnotateImagesRequest, ...gax.CallOption) (*visionpb.BatchAnnotateImagesResponse, error) + BatchAnnotateFiles(context.Context, *visionpb.BatchAnnotateFilesRequest, ...gax.CallOption) (*visionpb.BatchAnnotateFilesResponse, error) + AsyncBatchAnnotateImages(context.Context, *visionpb.AsyncBatchAnnotateImagesRequest, ...gax.CallOption) (*AsyncBatchAnnotateImagesOperation, error) + AsyncBatchAnnotateImagesOperation(name string) *AsyncBatchAnnotateImagesOperation + AsyncBatchAnnotateFiles(context.Context, *visionpb.AsyncBatchAnnotateFilesRequest, ...gax.CallOption) (*AsyncBatchAnnotateFilesOperation, error) + AsyncBatchAnnotateFilesOperation(name string) *AsyncBatchAnnotateFilesOperation +} + // ImageAnnotatorClient is a client for interacting with Cloud Vision API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service that performs Google Cloud Vision API detection tasks over client +// images, such as face, landmark, logo, label, and text detection. The +// ImageAnnotator service returns detected entities from the images. type ImageAnnotatorClient struct { + // The internal transport-dependent client. + internalClient internalImageAnnotatorClient + + // The call options for this service. + CallOptions *ImageAnnotatorCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ImageAnnotatorClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ImageAnnotatorClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ImageAnnotatorClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// BatchAnnotateImages run image detection and annotation for a batch of images. +func (c *ImageAnnotatorClient) BatchAnnotateImages(ctx context.Context, req *visionpb.BatchAnnotateImagesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateImagesResponse, error) { + return c.internalClient.BatchAnnotateImages(ctx, req, opts...) +} + +// BatchAnnotateFiles service that performs image detection and annotation for a batch of files. +// Now only “application/pdf”, “image/tiff” and “image/gif” are supported. +// +// This service will extract at most 5 (customers can specify which 5 in +// AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each +// file provided and perform detection and annotation for each image +// extracted. +func (c *ImageAnnotatorClient) BatchAnnotateFiles(ctx context.Context, req *visionpb.BatchAnnotateFilesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateFilesResponse, error) { + return c.internalClient.BatchAnnotateFiles(ctx, req, opts...) +} + +// AsyncBatchAnnotateImages run asynchronous image detection and annotation for a list of images. +// +// Progress and results can be retrieved through the +// google.longrunning.Operations interface. +// Operation.metadata contains OperationMetadata (metadata). +// Operation.response contains AsyncBatchAnnotateImagesResponse (results). +// +// This service will write image annotation outputs to json files in customer +// GCS bucket, each json file containing BatchAnnotateImagesResponse proto. +func (c *ImageAnnotatorClient) AsyncBatchAnnotateImages(ctx context.Context, req *visionpb.AsyncBatchAnnotateImagesRequest, opts ...gax.CallOption) (*AsyncBatchAnnotateImagesOperation, error) { + return c.internalClient.AsyncBatchAnnotateImages(ctx, req, opts...) +} + +// AsyncBatchAnnotateImagesOperation returns a new AsyncBatchAnnotateImagesOperation from a given name. +// The name must be that of a previously created AsyncBatchAnnotateImagesOperation, possibly from a different process. +func (c *ImageAnnotatorClient) AsyncBatchAnnotateImagesOperation(name string) *AsyncBatchAnnotateImagesOperation { + return c.internalClient.AsyncBatchAnnotateImagesOperation(name) +} + +// AsyncBatchAnnotateFiles run asynchronous image detection and annotation for a list of generic +// files, such as PDF files, which may contain multiple pages and multiple +// images per page. Progress and results can be retrieved through the +// google.longrunning.Operations interface. +// Operation.metadata contains OperationMetadata (metadata). +// Operation.response contains AsyncBatchAnnotateFilesResponse (results). +func (c *ImageAnnotatorClient) AsyncBatchAnnotateFiles(ctx context.Context, req *visionpb.AsyncBatchAnnotateFilesRequest, opts ...gax.CallOption) (*AsyncBatchAnnotateFilesOperation, error) { + return c.internalClient.AsyncBatchAnnotateFiles(ctx, req, opts...) +} + +// AsyncBatchAnnotateFilesOperation returns a new AsyncBatchAnnotateFilesOperation from a given name. +// The name must be that of a previously created AsyncBatchAnnotateFilesOperation, possibly from a different process. +func (c *ImageAnnotatorClient) AsyncBatchAnnotateFilesOperation(name string) *AsyncBatchAnnotateFilesOperation { + return c.internalClient.AsyncBatchAnnotateFilesOperation(name) +} + +// imageAnnotatorGRPCClient is a client for interacting with Cloud Vision API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type imageAnnotatorGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ImageAnnotatorClient + CallOptions **ImageAnnotatorCallOptions + // The gRPC API client. imageAnnotatorClient visionpb.ImageAnnotatorClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *ImageAnnotatorCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewImageAnnotatorClient creates a new image annotator client. +// NewImageAnnotatorClient creates a new image annotator client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service that performs Google Cloud Vision API detection tasks over client // images, such as face, landmark, logo, label, and text detection. The // ImageAnnotator service returns detected entities from the images. func NewImageAnnotatorClient(ctx context.Context, opts ...option.ClientOption) (*ImageAnnotatorClient, error) { - clientOpts := defaultImageAnnotatorClientOptions() - + clientOpts := defaultImageAnnotatorGRPCClientOptions() if newImageAnnotatorClientHook != nil { hookOpts, err := newImageAnnotatorClientHook(ctx, clientHookParams{}) if err != nil { @@ -161,16 +266,19 @@ func NewImageAnnotatorClient(ctx context.Context, opts ...option.ClientOption) ( if err != nil { return nil, err } - c := &ImageAnnotatorClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultImageAnnotatorCallOptions(), + client := ImageAnnotatorClient{CallOptions: defaultImageAnnotatorCallOptions()} + c := &imageAnnotatorGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, imageAnnotatorClient: visionpb.NewImageAnnotatorClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -180,33 +288,33 @@ func NewImageAnnotatorClient(ctx context.Context, opts ...option.ClientOption) ( // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ImageAnnotatorClient) Connection() *grpc.ClientConn { +func (c *imageAnnotatorGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ImageAnnotatorClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ImageAnnotatorClient) setGoogleClientInfo(keyval ...string) { +func (c *imageAnnotatorGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// BatchAnnotateImages run image detection and annotation for a batch of images. -func (c *ImageAnnotatorClient) BatchAnnotateImages(ctx context.Context, req *visionpb.BatchAnnotateImagesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateImagesResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *imageAnnotatorGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *imageAnnotatorGRPCClient) BatchAnnotateImages(ctx context.Context, req *visionpb.BatchAnnotateImagesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateImagesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -214,7 +322,7 @@ func (c *ImageAnnotatorClient) BatchAnnotateImages(ctx context.Context, req *vis } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchAnnotateImages[0:len(c.CallOptions.BatchAnnotateImages):len(c.CallOptions.BatchAnnotateImages)], opts...) + opts = append((*c.CallOptions).BatchAnnotateImages[0:len((*c.CallOptions).BatchAnnotateImages):len((*c.CallOptions).BatchAnnotateImages)], opts...) var resp *visionpb.BatchAnnotateImagesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -227,14 +335,7 @@ func (c *ImageAnnotatorClient) BatchAnnotateImages(ctx context.Context, req *vis return resp, nil } -// BatchAnnotateFiles service that performs image detection and annotation for a batch of files. -// Now only “application/pdf”, “image/tiff” and “image/gif” are supported. -// -// This service will extract at most 5 (customers can specify which 5 in -// AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each -// file provided and perform detection and annotation for each image -// extracted. -func (c *ImageAnnotatorClient) BatchAnnotateFiles(ctx context.Context, req *visionpb.BatchAnnotateFilesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateFilesResponse, error) { +func (c *imageAnnotatorGRPCClient) BatchAnnotateFiles(ctx context.Context, req *visionpb.BatchAnnotateFilesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateFilesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -242,7 +343,7 @@ func (c *ImageAnnotatorClient) BatchAnnotateFiles(ctx context.Context, req *visi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.BatchAnnotateFiles[0:len(c.CallOptions.BatchAnnotateFiles):len(c.CallOptions.BatchAnnotateFiles)], opts...) + opts = append((*c.CallOptions).BatchAnnotateFiles[0:len((*c.CallOptions).BatchAnnotateFiles):len((*c.CallOptions).BatchAnnotateFiles)], opts...) var resp *visionpb.BatchAnnotateFilesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -255,16 +356,7 @@ func (c *ImageAnnotatorClient) BatchAnnotateFiles(ctx context.Context, req *visi return resp, nil } -// AsyncBatchAnnotateImages run asynchronous image detection and annotation for a list of images. -// -// Progress and results can be retrieved through the -// google.longrunning.Operations interface. -// Operation.metadata contains OperationMetadata (metadata). -// Operation.response contains AsyncBatchAnnotateImagesResponse (results). -// -// This service will write image annotation outputs to json files in customer -// GCS bucket, each json file containing BatchAnnotateImagesResponse proto. -func (c *ImageAnnotatorClient) AsyncBatchAnnotateImages(ctx context.Context, req *visionpb.AsyncBatchAnnotateImagesRequest, opts ...gax.CallOption) (*AsyncBatchAnnotateImagesOperation, error) { +func (c *imageAnnotatorGRPCClient) AsyncBatchAnnotateImages(ctx context.Context, req *visionpb.AsyncBatchAnnotateImagesRequest, opts ...gax.CallOption) (*AsyncBatchAnnotateImagesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -272,7 +364,7 @@ func (c *ImageAnnotatorClient) AsyncBatchAnnotateImages(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AsyncBatchAnnotateImages[0:len(c.CallOptions.AsyncBatchAnnotateImages):len(c.CallOptions.AsyncBatchAnnotateImages)], opts...) + opts = append((*c.CallOptions).AsyncBatchAnnotateImages[0:len((*c.CallOptions).AsyncBatchAnnotateImages):len((*c.CallOptions).AsyncBatchAnnotateImages)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -283,17 +375,11 @@ func (c *ImageAnnotatorClient) AsyncBatchAnnotateImages(ctx context.Context, req return nil, err } return &AsyncBatchAnnotateImagesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// AsyncBatchAnnotateFiles run asynchronous image detection and annotation for a list of generic -// files, such as PDF files, which may contain multiple pages and multiple -// images per page. Progress and results can be retrieved through the -// google.longrunning.Operations interface. -// Operation.metadata contains OperationMetadata (metadata). -// Operation.response contains AsyncBatchAnnotateFilesResponse (results). -func (c *ImageAnnotatorClient) AsyncBatchAnnotateFiles(ctx context.Context, req *visionpb.AsyncBatchAnnotateFilesRequest, opts ...gax.CallOption) (*AsyncBatchAnnotateFilesOperation, error) { +func (c *imageAnnotatorGRPCClient) AsyncBatchAnnotateFiles(ctx context.Context, req *visionpb.AsyncBatchAnnotateFilesRequest, opts ...gax.CallOption) (*AsyncBatchAnnotateFilesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -301,7 +387,7 @@ func (c *ImageAnnotatorClient) AsyncBatchAnnotateFiles(ctx context.Context, req } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AsyncBatchAnnotateFiles[0:len(c.CallOptions.AsyncBatchAnnotateFiles):len(c.CallOptions.AsyncBatchAnnotateFiles)], opts...) + opts = append((*c.CallOptions).AsyncBatchAnnotateFiles[0:len((*c.CallOptions).AsyncBatchAnnotateFiles):len((*c.CallOptions).AsyncBatchAnnotateFiles)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -312,7 +398,7 @@ func (c *ImageAnnotatorClient) AsyncBatchAnnotateFiles(ctx context.Context, req return nil, err } return &AsyncBatchAnnotateFilesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -323,9 +409,9 @@ type AsyncBatchAnnotateFilesOperation struct { // AsyncBatchAnnotateFilesOperation returns a new AsyncBatchAnnotateFilesOperation from a given name. // The name must be that of a previously created AsyncBatchAnnotateFilesOperation, possibly from a different process. -func (c *ImageAnnotatorClient) AsyncBatchAnnotateFilesOperation(name string) *AsyncBatchAnnotateFilesOperation { +func (c *imageAnnotatorGRPCClient) AsyncBatchAnnotateFilesOperation(name string) *AsyncBatchAnnotateFilesOperation { return &AsyncBatchAnnotateFilesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -392,9 +478,9 @@ type AsyncBatchAnnotateImagesOperation struct { // AsyncBatchAnnotateImagesOperation returns a new AsyncBatchAnnotateImagesOperation from a given name. // The name must be that of a previously created AsyncBatchAnnotateImagesOperation, possibly from a different process. -func (c *ImageAnnotatorClient) AsyncBatchAnnotateImagesOperation(name string) *AsyncBatchAnnotateImagesOperation { +func (c *imageAnnotatorGRPCClient) AsyncBatchAnnotateImagesOperation(name string) *AsyncBatchAnnotateImagesOperation { return &AsyncBatchAnnotateImagesOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/vision/apiv1/image_annotator_client_example_test.go b/vision/apiv1/image_annotator_client_example_test.go index b0e2794aabf4..f786dd1c9e23 100644 --- a/vision/apiv1/image_annotator_client_example_test.go +++ b/vision/apiv1/image_annotator_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewImageAnnotatorClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleImageAnnotatorClient_BatchAnnotateImages() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewImageAnnotatorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.BatchAnnotateImagesRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleImageAnnotatorClient_BatchAnnotateImages() { } func ExampleImageAnnotatorClient_BatchAnnotateFiles() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewImageAnnotatorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.BatchAnnotateFilesRequest{ // TODO: Fill request struct fields. @@ -74,13 +74,12 @@ func ExampleImageAnnotatorClient_BatchAnnotateFiles() { } func ExampleImageAnnotatorClient_AsyncBatchAnnotateImages() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewImageAnnotatorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.AsyncBatchAnnotateImagesRequest{ // TODO: Fill request struct fields. @@ -99,13 +98,12 @@ func ExampleImageAnnotatorClient_AsyncBatchAnnotateImages() { } func ExampleImageAnnotatorClient_AsyncBatchAnnotateFiles() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewImageAnnotatorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.AsyncBatchAnnotateFilesRequest{ // TODO: Fill request struct fields. diff --git a/vision/apiv1/product_search_client.go b/vision/apiv1/product_search_client.go index 3dbd92484259..f5dff0bda6e8 100644 --- a/vision/apiv1/product_search_client.go +++ b/vision/apiv1/product_search_client.go @@ -63,7 +63,7 @@ type ProductSearchCallOptions struct { PurgeProducts []gax.CallOption } -func defaultProductSearchClientOptions() []option.ClientOption { +func defaultProductSearchGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("vision.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("vision.mtls.googleapis.com:443"), @@ -293,32 +293,367 @@ func defaultProductSearchCallOptions() *ProductSearchCallOptions { } } +// internalProductSearchClient is an interface that defines the methods availaible from Cloud Vision API. +type internalProductSearchClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateProductSet(context.Context, *visionpb.CreateProductSetRequest, ...gax.CallOption) (*visionpb.ProductSet, error) + ListProductSets(context.Context, *visionpb.ListProductSetsRequest, ...gax.CallOption) *ProductSetIterator + GetProductSet(context.Context, *visionpb.GetProductSetRequest, ...gax.CallOption) (*visionpb.ProductSet, error) + UpdateProductSet(context.Context, *visionpb.UpdateProductSetRequest, ...gax.CallOption) (*visionpb.ProductSet, error) + DeleteProductSet(context.Context, *visionpb.DeleteProductSetRequest, ...gax.CallOption) error + CreateProduct(context.Context, *visionpb.CreateProductRequest, ...gax.CallOption) (*visionpb.Product, error) + ListProducts(context.Context, *visionpb.ListProductsRequest, ...gax.CallOption) *ProductIterator + GetProduct(context.Context, *visionpb.GetProductRequest, ...gax.CallOption) (*visionpb.Product, error) + UpdateProduct(context.Context, *visionpb.UpdateProductRequest, ...gax.CallOption) (*visionpb.Product, error) + DeleteProduct(context.Context, *visionpb.DeleteProductRequest, ...gax.CallOption) error + CreateReferenceImage(context.Context, *visionpb.CreateReferenceImageRequest, ...gax.CallOption) (*visionpb.ReferenceImage, error) + DeleteReferenceImage(context.Context, *visionpb.DeleteReferenceImageRequest, ...gax.CallOption) error + ListReferenceImages(context.Context, *visionpb.ListReferenceImagesRequest, ...gax.CallOption) *ReferenceImageIterator + GetReferenceImage(context.Context, *visionpb.GetReferenceImageRequest, ...gax.CallOption) (*visionpb.ReferenceImage, error) + AddProductToProductSet(context.Context, *visionpb.AddProductToProductSetRequest, ...gax.CallOption) error + RemoveProductFromProductSet(context.Context, *visionpb.RemoveProductFromProductSetRequest, ...gax.CallOption) error + ListProductsInProductSet(context.Context, *visionpb.ListProductsInProductSetRequest, ...gax.CallOption) *ProductIterator + ImportProductSets(context.Context, *visionpb.ImportProductSetsRequest, ...gax.CallOption) (*ImportProductSetsOperation, error) + ImportProductSetsOperation(name string) *ImportProductSetsOperation + PurgeProducts(context.Context, *visionpb.PurgeProductsRequest, ...gax.CallOption) (*PurgeProductsOperation, error) + PurgeProductsOperation(name string) *PurgeProductsOperation +} + // ProductSearchClient is a client for interacting with Cloud Vision API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Manages Products and ProductSets of reference images for use in product +// search. It uses the following resource model: +// +// The API has a collection of ProductSet resources, named +// projects/*/locations/*/productSets/*, which acts as a way to put different +// products into groups to limit identification. +// +// In parallel, +// +// The API has a collection of Product resources, named +// projects/*/locations/*/products/* +// +// Each Product has a collection of ReferenceImage resources, named +// projects/*/locations/*/products/*/referenceImages/* type ProductSearchClient struct { + // The internal transport-dependent client. + internalClient internalProductSearchClient + + // The call options for this service. + CallOptions *ProductSearchCallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ProductSearchClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ProductSearchClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ProductSearchClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateProductSet creates and returns a new ProductSet resource. +// +// Possible errors: +// +// Returns INVALID_ARGUMENT if display_name is missing, or is longer than +// 4096 characters. +func (c *ProductSearchClient) CreateProductSet(ctx context.Context, req *visionpb.CreateProductSetRequest, opts ...gax.CallOption) (*visionpb.ProductSet, error) { + return c.internalClient.CreateProductSet(ctx, req, opts...) +} + +// ListProductSets lists ProductSets in an unspecified order. +// +// Possible errors: +// +// Returns INVALID_ARGUMENT if page_size is greater than 100, or less +// than 1. +func (c *ProductSearchClient) ListProductSets(ctx context.Context, req *visionpb.ListProductSetsRequest, opts ...gax.CallOption) *ProductSetIterator { + return c.internalClient.ListProductSets(ctx, req, opts...) +} + +// GetProductSet gets information associated with a ProductSet. +// +// Possible errors: +// +// Returns NOT_FOUND if the ProductSet does not exist. +func (c *ProductSearchClient) GetProductSet(ctx context.Context, req *visionpb.GetProductSetRequest, opts ...gax.CallOption) (*visionpb.ProductSet, error) { + return c.internalClient.GetProductSet(ctx, req, opts...) +} + +// UpdateProductSet makes changes to a ProductSet resource. +// Only display_name can be updated currently. +// +// Possible errors: +// +// Returns NOT_FOUND if the ProductSet does not exist. +// +// Returns INVALID_ARGUMENT if display_name is present in update_mask but +// missing from the request or longer than 4096 characters. +func (c *ProductSearchClient) UpdateProductSet(ctx context.Context, req *visionpb.UpdateProductSetRequest, opts ...gax.CallOption) (*visionpb.ProductSet, error) { + return c.internalClient.UpdateProductSet(ctx, req, opts...) +} + +// DeleteProductSet permanently deletes a ProductSet. Products and ReferenceImages in the +// ProductSet are not deleted. +// +// The actual image files are not deleted from Google Cloud Storage. +func (c *ProductSearchClient) DeleteProductSet(ctx context.Context, req *visionpb.DeleteProductSetRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteProductSet(ctx, req, opts...) +} + +// CreateProduct creates and returns a new product resource. +// +// Possible errors: +// +// Returns INVALID_ARGUMENT if display_name is missing or longer than 4096 +// characters. +// +// Returns INVALID_ARGUMENT if description is longer than 4096 characters. +// +// Returns INVALID_ARGUMENT if product_category is missing or invalid. +func (c *ProductSearchClient) CreateProduct(ctx context.Context, req *visionpb.CreateProductRequest, opts ...gax.CallOption) (*visionpb.Product, error) { + return c.internalClient.CreateProduct(ctx, req, opts...) +} + +// ListProducts lists products in an unspecified order. +// +// Possible errors: +// +// Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1. +func (c *ProductSearchClient) ListProducts(ctx context.Context, req *visionpb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator { + return c.internalClient.ListProducts(ctx, req, opts...) +} + +// GetProduct gets information associated with a Product. +// +// Possible errors: +// +// Returns NOT_FOUND if the Product does not exist. +func (c *ProductSearchClient) GetProduct(ctx context.Context, req *visionpb.GetProductRequest, opts ...gax.CallOption) (*visionpb.Product, error) { + return c.internalClient.GetProduct(ctx, req, opts...) +} + +// UpdateProduct makes changes to a Product resource. +// Only the display_name, description, and labels fields can be updated +// right now. +// +// If labels are updated, the change will not be reflected in queries until +// the next index time. +// +// Possible errors: +// +// Returns NOT_FOUND if the Product does not exist. +// +// Returns INVALID_ARGUMENT if display_name is present in update_mask but is +// missing from the request or longer than 4096 characters. +// +// Returns INVALID_ARGUMENT if description is present in update_mask but is +// longer than 4096 characters. +// +// Returns INVALID_ARGUMENT if product_category is present in update_mask. +func (c *ProductSearchClient) UpdateProduct(ctx context.Context, req *visionpb.UpdateProductRequest, opts ...gax.CallOption) (*visionpb.Product, error) { + return c.internalClient.UpdateProduct(ctx, req, opts...) +} + +// DeleteProduct permanently deletes a product and its reference images. +// +// Metadata of the product and all its images will be deleted right away, but +// search queries against ProductSets containing the product may still work +// until all related caches are refreshed. +func (c *ProductSearchClient) DeleteProduct(ctx context.Context, req *visionpb.DeleteProductRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteProduct(ctx, req, opts...) +} + +// CreateReferenceImage creates and returns a new ReferenceImage resource. +// +// The bounding_poly field is optional. If bounding_poly is not specified, +// the system will try to detect regions of interest in the image that are +// compatible with the product_category on the parent product. If it is +// specified, detection is ALWAYS skipped. The system converts polygons into +// non-rotated rectangles. +// +// Note that the pipeline will resize the image if the image resolution is too +// large to process (above 50MP). +// +// Possible errors: +// +// Returns INVALID_ARGUMENT if the image_uri is missing or longer than 4096 +// characters. +// +// Returns INVALID_ARGUMENT if the product does not exist. +// +// Returns INVALID_ARGUMENT if bounding_poly is not provided, and nothing +// compatible with the parent product’s product_category is detected. +// +// Returns INVALID_ARGUMENT if bounding_poly contains more than 10 polygons. +func (c *ProductSearchClient) CreateReferenceImage(ctx context.Context, req *visionpb.CreateReferenceImageRequest, opts ...gax.CallOption) (*visionpb.ReferenceImage, error) { + return c.internalClient.CreateReferenceImage(ctx, req, opts...) +} + +// DeleteReferenceImage permanently deletes a reference image. +// +// The image metadata will be deleted right away, but search queries +// against ProductSets containing the image may still work until all related +// caches are refreshed. +// +// The actual image files are not deleted from Google Cloud Storage. +func (c *ProductSearchClient) DeleteReferenceImage(ctx context.Context, req *visionpb.DeleteReferenceImageRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteReferenceImage(ctx, req, opts...) +} + +// ListReferenceImages lists reference images. +// +// Possible errors: +// +// Returns NOT_FOUND if the parent product does not exist. +// +// Returns INVALID_ARGUMENT if the page_size is greater than 100, or less +// than 1. +func (c *ProductSearchClient) ListReferenceImages(ctx context.Context, req *visionpb.ListReferenceImagesRequest, opts ...gax.CallOption) *ReferenceImageIterator { + return c.internalClient.ListReferenceImages(ctx, req, opts...) +} + +// GetReferenceImage gets information associated with a ReferenceImage. +// +// Possible errors: +// +// Returns NOT_FOUND if the specified image does not exist. +func (c *ProductSearchClient) GetReferenceImage(ctx context.Context, req *visionpb.GetReferenceImageRequest, opts ...gax.CallOption) (*visionpb.ReferenceImage, error) { + return c.internalClient.GetReferenceImage(ctx, req, opts...) +} + +// AddProductToProductSet adds a Product to the specified ProductSet. If the Product is already +// present, no change is made. +// +// One Product can be added to at most 100 ProductSets. +// +// Possible errors: +// +// Returns NOT_FOUND if the Product or the ProductSet doesn’t exist. +func (c *ProductSearchClient) AddProductToProductSet(ctx context.Context, req *visionpb.AddProductToProductSetRequest, opts ...gax.CallOption) error { + return c.internalClient.AddProductToProductSet(ctx, req, opts...) +} + +// RemoveProductFromProductSet removes a Product from the specified ProductSet. +func (c *ProductSearchClient) RemoveProductFromProductSet(ctx context.Context, req *visionpb.RemoveProductFromProductSetRequest, opts ...gax.CallOption) error { + return c.internalClient.RemoveProductFromProductSet(ctx, req, opts...) +} + +// ListProductsInProductSet lists the Products in a ProductSet, in an unspecified order. If the +// ProductSet does not exist, the products field of the response will be +// empty. +// +// Possible errors: +// +// Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1. +func (c *ProductSearchClient) ListProductsInProductSet(ctx context.Context, req *visionpb.ListProductsInProductSetRequest, opts ...gax.CallOption) *ProductIterator { + return c.internalClient.ListProductsInProductSet(ctx, req, opts...) +} + +// ImportProductSets asynchronous API that imports a list of reference images to specified +// product sets based on a list of image information. +// +// The google.longrunning.Operation API can be used to keep track of the +// progress and results of the request. +// Operation.metadata contains BatchOperationMetadata. (progress) +// Operation.response contains ImportProductSetsResponse. (results) +// +// The input source of this method is a csv file on Google Cloud Storage. +// For the format of the csv file please see +// ImportProductSetsGcsSource.csv_file_uri. +func (c *ProductSearchClient) ImportProductSets(ctx context.Context, req *visionpb.ImportProductSetsRequest, opts ...gax.CallOption) (*ImportProductSetsOperation, error) { + return c.internalClient.ImportProductSets(ctx, req, opts...) +} + +// ImportProductSetsOperation returns a new ImportProductSetsOperation from a given name. +// The name must be that of a previously created ImportProductSetsOperation, possibly from a different process. +func (c *ProductSearchClient) ImportProductSetsOperation(name string) *ImportProductSetsOperation { + return c.internalClient.ImportProductSetsOperation(name) +} + +// PurgeProducts asynchronous API to delete all Products in a ProductSet or all Products +// that are in no ProductSet. +// +// If a Product is a member of the specified ProductSet in addition to other +// ProductSets, the Product will still be deleted. +// +// It is recommended to not delete the specified ProductSet until after this +// operation has completed. It is also recommended to not add any of the +// Products involved in the batch delete to a new ProductSet while this +// operation is running because those Products may still end up deleted. +// +// It’s not possible to undo the PurgeProducts operation. Therefore, it is +// recommended to keep the csv files used in ImportProductSets (if that was +// how you originally built the Product Set) before starting PurgeProducts, in +// case you need to re-import the data after deletion. +// +// If the plan is to purge all of the Products from a ProductSet and then +// re-use the empty ProductSet to re-import new Products into the empty +// ProductSet, you must wait until the PurgeProducts operation has finished +// for that ProductSet. +// +// The google.longrunning.Operation API can be used to keep track of the +// progress and results of the request. +// Operation.metadata contains BatchOperationMetadata. (progress) +func (c *ProductSearchClient) PurgeProducts(ctx context.Context, req *visionpb.PurgeProductsRequest, opts ...gax.CallOption) (*PurgeProductsOperation, error) { + return c.internalClient.PurgeProducts(ctx, req, opts...) +} + +// PurgeProductsOperation returns a new PurgeProductsOperation from a given name. +// The name must be that of a previously created PurgeProductsOperation, possibly from a different process. +func (c *ProductSearchClient) PurgeProductsOperation(name string) *PurgeProductsOperation { + return c.internalClient.PurgeProductsOperation(name) +} + +// productSearchGRPCClient is a client for interacting with Cloud Vision API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type productSearchGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ProductSearchClient + CallOptions **ProductSearchCallOptions + // The gRPC API client. productSearchClient visionpb.ProductSearchClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *ProductSearchCallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewProductSearchClient creates a new product search client. +// NewProductSearchClient creates a new product search client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Manages Products and ProductSets of reference images for use in product // search. It uses the following resource model: @@ -335,8 +670,7 @@ type ProductSearchClient struct { // Each Product has a collection of ReferenceImage resources, named // projects/*/locations/*/products/*/referenceImages/* func NewProductSearchClient(ctx context.Context, opts ...option.ClientOption) (*ProductSearchClient, error) { - clientOpts := defaultProductSearchClientOptions() - + clientOpts := defaultProductSearchGRPCClientOptions() if newProductSearchClientHook != nil { hookOpts, err := newProductSearchClientHook(ctx, clientHookParams{}) if err != nil { @@ -354,16 +688,19 @@ func NewProductSearchClient(ctx context.Context, opts ...option.ClientOption) (* if err != nil { return nil, err } - c := &ProductSearchClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultProductSearchCallOptions(), + client := ProductSearchClient{CallOptions: defaultProductSearchCallOptions()} + c := &productSearchGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, productSearchClient: visionpb.NewProductSearchClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -373,38 +710,33 @@ func NewProductSearchClient(ctx context.Context, opts ...option.ClientOption) (* // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ProductSearchClient) Connection() *grpc.ClientConn { +func (c *productSearchGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ProductSearchClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ProductSearchClient) setGoogleClientInfo(keyval ...string) { +func (c *productSearchGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateProductSet creates and returns a new ProductSet resource. -// -// Possible errors: -// -// Returns INVALID_ARGUMENT if display_name is missing, or is longer than -// 4096 characters. -func (c *ProductSearchClient) CreateProductSet(ctx context.Context, req *visionpb.CreateProductSetRequest, opts ...gax.CallOption) (*visionpb.ProductSet, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *productSearchGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *productSearchGRPCClient) CreateProductSet(ctx context.Context, req *visionpb.CreateProductSetRequest, opts ...gax.CallOption) (*visionpb.ProductSet, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -412,7 +744,7 @@ func (c *ProductSearchClient) CreateProductSet(ctx context.Context, req *visionp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateProductSet[0:len(c.CallOptions.CreateProductSet):len(c.CallOptions.CreateProductSet)], opts...) + opts = append((*c.CallOptions).CreateProductSet[0:len((*c.CallOptions).CreateProductSet):len((*c.CallOptions).CreateProductSet)], opts...) var resp *visionpb.ProductSet err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -425,16 +757,10 @@ func (c *ProductSearchClient) CreateProductSet(ctx context.Context, req *visionp return resp, nil } -// ListProductSets lists ProductSets in an unspecified order. -// -// Possible errors: -// -// Returns INVALID_ARGUMENT if page_size is greater than 100, or less -// than 1. -func (c *ProductSearchClient) ListProductSets(ctx context.Context, req *visionpb.ListProductSetsRequest, opts ...gax.CallOption) *ProductSetIterator { +func (c *productSearchGRPCClient) ListProductSets(ctx context.Context, req *visionpb.ListProductSetsRequest, opts ...gax.CallOption) *ProductSetIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListProductSets[0:len(c.CallOptions.ListProductSets):len(c.CallOptions.ListProductSets)], opts...) + opts = append((*c.CallOptions).ListProductSets[0:len((*c.CallOptions).ListProductSets):len((*c.CallOptions).ListProductSets)], opts...) it := &ProductSetIterator{} req = proto.Clone(req).(*visionpb.ListProductSetsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*visionpb.ProductSet, string, error) { @@ -471,12 +797,7 @@ func (c *ProductSearchClient) ListProductSets(ctx context.Context, req *visionpb return it } -// GetProductSet gets information associated with a ProductSet. -// -// Possible errors: -// -// Returns NOT_FOUND if the ProductSet does not exist. -func (c *ProductSearchClient) GetProductSet(ctx context.Context, req *visionpb.GetProductSetRequest, opts ...gax.CallOption) (*visionpb.ProductSet, error) { +func (c *productSearchGRPCClient) GetProductSet(ctx context.Context, req *visionpb.GetProductSetRequest, opts ...gax.CallOption) (*visionpb.ProductSet, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -484,7 +805,7 @@ func (c *ProductSearchClient) GetProductSet(ctx context.Context, req *visionpb.G } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetProductSet[0:len(c.CallOptions.GetProductSet):len(c.CallOptions.GetProductSet)], opts...) + opts = append((*c.CallOptions).GetProductSet[0:len((*c.CallOptions).GetProductSet):len((*c.CallOptions).GetProductSet)], opts...) var resp *visionpb.ProductSet err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -497,16 +818,7 @@ func (c *ProductSearchClient) GetProductSet(ctx context.Context, req *visionpb.G return resp, nil } -// UpdateProductSet makes changes to a ProductSet resource. -// Only display_name can be updated currently. -// -// Possible errors: -// -// Returns NOT_FOUND if the ProductSet does not exist. -// -// Returns INVALID_ARGUMENT if display_name is present in update_mask but -// missing from the request or longer than 4096 characters. -func (c *ProductSearchClient) UpdateProductSet(ctx context.Context, req *visionpb.UpdateProductSetRequest, opts ...gax.CallOption) (*visionpb.ProductSet, error) { +func (c *productSearchGRPCClient) UpdateProductSet(ctx context.Context, req *visionpb.UpdateProductSetRequest, opts ...gax.CallOption) (*visionpb.ProductSet, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -514,7 +826,7 @@ func (c *ProductSearchClient) UpdateProductSet(ctx context.Context, req *visionp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product_set.name", url.QueryEscape(req.GetProductSet().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateProductSet[0:len(c.CallOptions.UpdateProductSet):len(c.CallOptions.UpdateProductSet)], opts...) + opts = append((*c.CallOptions).UpdateProductSet[0:len((*c.CallOptions).UpdateProductSet):len((*c.CallOptions).UpdateProductSet)], opts...) var resp *visionpb.ProductSet err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -527,11 +839,7 @@ func (c *ProductSearchClient) UpdateProductSet(ctx context.Context, req *visionp return resp, nil } -// DeleteProductSet permanently deletes a ProductSet. Products and ReferenceImages in the -// ProductSet are not deleted. -// -// The actual image files are not deleted from Google Cloud Storage. -func (c *ProductSearchClient) DeleteProductSet(ctx context.Context, req *visionpb.DeleteProductSetRequest, opts ...gax.CallOption) error { +func (c *productSearchGRPCClient) DeleteProductSet(ctx context.Context, req *visionpb.DeleteProductSetRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -539,7 +847,7 @@ func (c *ProductSearchClient) DeleteProductSet(ctx context.Context, req *visionp } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteProductSet[0:len(c.CallOptions.DeleteProductSet):len(c.CallOptions.DeleteProductSet)], opts...) + opts = append((*c.CallOptions).DeleteProductSet[0:len((*c.CallOptions).DeleteProductSet):len((*c.CallOptions).DeleteProductSet)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.productSearchClient.DeleteProductSet(ctx, req, settings.GRPC...) @@ -548,17 +856,7 @@ func (c *ProductSearchClient) DeleteProductSet(ctx context.Context, req *visionp return err } -// CreateProduct creates and returns a new product resource. -// -// Possible errors: -// -// Returns INVALID_ARGUMENT if display_name is missing or longer than 4096 -// characters. -// -// Returns INVALID_ARGUMENT if description is longer than 4096 characters. -// -// Returns INVALID_ARGUMENT if product_category is missing or invalid. -func (c *ProductSearchClient) CreateProduct(ctx context.Context, req *visionpb.CreateProductRequest, opts ...gax.CallOption) (*visionpb.Product, error) { +func (c *productSearchGRPCClient) CreateProduct(ctx context.Context, req *visionpb.CreateProductRequest, opts ...gax.CallOption) (*visionpb.Product, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -566,7 +864,7 @@ func (c *ProductSearchClient) CreateProduct(ctx context.Context, req *visionpb.C } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateProduct[0:len(c.CallOptions.CreateProduct):len(c.CallOptions.CreateProduct)], opts...) + opts = append((*c.CallOptions).CreateProduct[0:len((*c.CallOptions).CreateProduct):len((*c.CallOptions).CreateProduct)], opts...) var resp *visionpb.Product err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -579,15 +877,10 @@ func (c *ProductSearchClient) CreateProduct(ctx context.Context, req *visionpb.C return resp, nil } -// ListProducts lists products in an unspecified order. -// -// Possible errors: -// -// Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1. -func (c *ProductSearchClient) ListProducts(ctx context.Context, req *visionpb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator { +func (c *productSearchGRPCClient) ListProducts(ctx context.Context, req *visionpb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListProducts[0:len(c.CallOptions.ListProducts):len(c.CallOptions.ListProducts)], opts...) + opts = append((*c.CallOptions).ListProducts[0:len((*c.CallOptions).ListProducts):len((*c.CallOptions).ListProducts)], opts...) it := &ProductIterator{} req = proto.Clone(req).(*visionpb.ListProductsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*visionpb.Product, string, error) { @@ -624,12 +917,7 @@ func (c *ProductSearchClient) ListProducts(ctx context.Context, req *visionpb.Li return it } -// GetProduct gets information associated with a Product. -// -// Possible errors: -// -// Returns NOT_FOUND if the Product does not exist. -func (c *ProductSearchClient) GetProduct(ctx context.Context, req *visionpb.GetProductRequest, opts ...gax.CallOption) (*visionpb.Product, error) { +func (c *productSearchGRPCClient) GetProduct(ctx context.Context, req *visionpb.GetProductRequest, opts ...gax.CallOption) (*visionpb.Product, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -637,7 +925,7 @@ func (c *ProductSearchClient) GetProduct(ctx context.Context, req *visionpb.GetP } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetProduct[0:len(c.CallOptions.GetProduct):len(c.CallOptions.GetProduct)], opts...) + opts = append((*c.CallOptions).GetProduct[0:len((*c.CallOptions).GetProduct):len((*c.CallOptions).GetProduct)], opts...) var resp *visionpb.Product err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -650,25 +938,7 @@ func (c *ProductSearchClient) GetProduct(ctx context.Context, req *visionpb.GetP return resp, nil } -// UpdateProduct makes changes to a Product resource. -// Only the display_name, description, and labels fields can be updated -// right now. -// -// If labels are updated, the change will not be reflected in queries until -// the next index time. -// -// Possible errors: -// -// Returns NOT_FOUND if the Product does not exist. -// -// Returns INVALID_ARGUMENT if display_name is present in update_mask but is -// missing from the request or longer than 4096 characters. -// -// Returns INVALID_ARGUMENT if description is present in update_mask but is -// longer than 4096 characters. -// -// Returns INVALID_ARGUMENT if product_category is present in update_mask. -func (c *ProductSearchClient) UpdateProduct(ctx context.Context, req *visionpb.UpdateProductRequest, opts ...gax.CallOption) (*visionpb.Product, error) { +func (c *productSearchGRPCClient) UpdateProduct(ctx context.Context, req *visionpb.UpdateProductRequest, opts ...gax.CallOption) (*visionpb.Product, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -676,7 +946,7 @@ func (c *ProductSearchClient) UpdateProduct(ctx context.Context, req *visionpb.U } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "product.name", url.QueryEscape(req.GetProduct().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateProduct[0:len(c.CallOptions.UpdateProduct):len(c.CallOptions.UpdateProduct)], opts...) + opts = append((*c.CallOptions).UpdateProduct[0:len((*c.CallOptions).UpdateProduct):len((*c.CallOptions).UpdateProduct)], opts...) var resp *visionpb.Product err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -689,12 +959,7 @@ func (c *ProductSearchClient) UpdateProduct(ctx context.Context, req *visionpb.U return resp, nil } -// DeleteProduct permanently deletes a product and its reference images. -// -// Metadata of the product and all its images will be deleted right away, but -// search queries against ProductSets containing the product may still work -// until all related caches are refreshed. -func (c *ProductSearchClient) DeleteProduct(ctx context.Context, req *visionpb.DeleteProductRequest, opts ...gax.CallOption) error { +func (c *productSearchGRPCClient) DeleteProduct(ctx context.Context, req *visionpb.DeleteProductRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -702,7 +967,7 @@ func (c *ProductSearchClient) DeleteProduct(ctx context.Context, req *visionpb.D } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteProduct[0:len(c.CallOptions.DeleteProduct):len(c.CallOptions.DeleteProduct)], opts...) + opts = append((*c.CallOptions).DeleteProduct[0:len((*c.CallOptions).DeleteProduct):len((*c.CallOptions).DeleteProduct)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.productSearchClient.DeleteProduct(ctx, req, settings.GRPC...) @@ -711,29 +976,7 @@ func (c *ProductSearchClient) DeleteProduct(ctx context.Context, req *visionpb.D return err } -// CreateReferenceImage creates and returns a new ReferenceImage resource. -// -// The bounding_poly field is optional. If bounding_poly is not specified, -// the system will try to detect regions of interest in the image that are -// compatible with the product_category on the parent product. If it is -// specified, detection is ALWAYS skipped. The system converts polygons into -// non-rotated rectangles. -// -// Note that the pipeline will resize the image if the image resolution is too -// large to process (above 50MP). -// -// Possible errors: -// -// Returns INVALID_ARGUMENT if the image_uri is missing or longer than 4096 -// characters. -// -// Returns INVALID_ARGUMENT if the product does not exist. -// -// Returns INVALID_ARGUMENT if bounding_poly is not provided, and nothing -// compatible with the parent product’s product_category is detected. -// -// Returns INVALID_ARGUMENT if bounding_poly contains more than 10 polygons. -func (c *ProductSearchClient) CreateReferenceImage(ctx context.Context, req *visionpb.CreateReferenceImageRequest, opts ...gax.CallOption) (*visionpb.ReferenceImage, error) { +func (c *productSearchGRPCClient) CreateReferenceImage(ctx context.Context, req *visionpb.CreateReferenceImageRequest, opts ...gax.CallOption) (*visionpb.ReferenceImage, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -741,7 +984,7 @@ func (c *ProductSearchClient) CreateReferenceImage(ctx context.Context, req *vis } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateReferenceImage[0:len(c.CallOptions.CreateReferenceImage):len(c.CallOptions.CreateReferenceImage)], opts...) + opts = append((*c.CallOptions).CreateReferenceImage[0:len((*c.CallOptions).CreateReferenceImage):len((*c.CallOptions).CreateReferenceImage)], opts...) var resp *visionpb.ReferenceImage err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -754,14 +997,7 @@ func (c *ProductSearchClient) CreateReferenceImage(ctx context.Context, req *vis return resp, nil } -// DeleteReferenceImage permanently deletes a reference image. -// -// The image metadata will be deleted right away, but search queries -// against ProductSets containing the image may still work until all related -// caches are refreshed. -// -// The actual image files are not deleted from Google Cloud Storage. -func (c *ProductSearchClient) DeleteReferenceImage(ctx context.Context, req *visionpb.DeleteReferenceImageRequest, opts ...gax.CallOption) error { +func (c *productSearchGRPCClient) DeleteReferenceImage(ctx context.Context, req *visionpb.DeleteReferenceImageRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -769,7 +1005,7 @@ func (c *ProductSearchClient) DeleteReferenceImage(ctx context.Context, req *vis } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteReferenceImage[0:len(c.CallOptions.DeleteReferenceImage):len(c.CallOptions.DeleteReferenceImage)], opts...) + opts = append((*c.CallOptions).DeleteReferenceImage[0:len((*c.CallOptions).DeleteReferenceImage):len((*c.CallOptions).DeleteReferenceImage)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.productSearchClient.DeleteReferenceImage(ctx, req, settings.GRPC...) @@ -778,18 +1014,10 @@ func (c *ProductSearchClient) DeleteReferenceImage(ctx context.Context, req *vis return err } -// ListReferenceImages lists reference images. -// -// Possible errors: -// -// Returns NOT_FOUND if the parent product does not exist. -// -// Returns INVALID_ARGUMENT if the page_size is greater than 100, or less -// than 1. -func (c *ProductSearchClient) ListReferenceImages(ctx context.Context, req *visionpb.ListReferenceImagesRequest, opts ...gax.CallOption) *ReferenceImageIterator { +func (c *productSearchGRPCClient) ListReferenceImages(ctx context.Context, req *visionpb.ListReferenceImagesRequest, opts ...gax.CallOption) *ReferenceImageIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListReferenceImages[0:len(c.CallOptions.ListReferenceImages):len(c.CallOptions.ListReferenceImages)], opts...) + opts = append((*c.CallOptions).ListReferenceImages[0:len((*c.CallOptions).ListReferenceImages):len((*c.CallOptions).ListReferenceImages)], opts...) it := &ReferenceImageIterator{} req = proto.Clone(req).(*visionpb.ListReferenceImagesRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*visionpb.ReferenceImage, string, error) { @@ -826,12 +1054,7 @@ func (c *ProductSearchClient) ListReferenceImages(ctx context.Context, req *visi return it } -// GetReferenceImage gets information associated with a ReferenceImage. -// -// Possible errors: -// -// Returns NOT_FOUND if the specified image does not exist. -func (c *ProductSearchClient) GetReferenceImage(ctx context.Context, req *visionpb.GetReferenceImageRequest, opts ...gax.CallOption) (*visionpb.ReferenceImage, error) { +func (c *productSearchGRPCClient) GetReferenceImage(ctx context.Context, req *visionpb.GetReferenceImageRequest, opts ...gax.CallOption) (*visionpb.ReferenceImage, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -839,7 +1062,7 @@ func (c *ProductSearchClient) GetReferenceImage(ctx context.Context, req *vision } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetReferenceImage[0:len(c.CallOptions.GetReferenceImage):len(c.CallOptions.GetReferenceImage)], opts...) + opts = append((*c.CallOptions).GetReferenceImage[0:len((*c.CallOptions).GetReferenceImage):len((*c.CallOptions).GetReferenceImage)], opts...) var resp *visionpb.ReferenceImage err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -852,15 +1075,7 @@ func (c *ProductSearchClient) GetReferenceImage(ctx context.Context, req *vision return resp, nil } -// AddProductToProductSet adds a Product to the specified ProductSet. If the Product is already -// present, no change is made. -// -// One Product can be added to at most 100 ProductSets. -// -// Possible errors: -// -// Returns NOT_FOUND if the Product or the ProductSet doesn’t exist. -func (c *ProductSearchClient) AddProductToProductSet(ctx context.Context, req *visionpb.AddProductToProductSetRequest, opts ...gax.CallOption) error { +func (c *productSearchGRPCClient) AddProductToProductSet(ctx context.Context, req *visionpb.AddProductToProductSetRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -868,7 +1083,7 @@ func (c *ProductSearchClient) AddProductToProductSet(ctx context.Context, req *v } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AddProductToProductSet[0:len(c.CallOptions.AddProductToProductSet):len(c.CallOptions.AddProductToProductSet)], opts...) + opts = append((*c.CallOptions).AddProductToProductSet[0:len((*c.CallOptions).AddProductToProductSet):len((*c.CallOptions).AddProductToProductSet)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.productSearchClient.AddProductToProductSet(ctx, req, settings.GRPC...) @@ -877,8 +1092,7 @@ func (c *ProductSearchClient) AddProductToProductSet(ctx context.Context, req *v return err } -// RemoveProductFromProductSet removes a Product from the specified ProductSet. -func (c *ProductSearchClient) RemoveProductFromProductSet(ctx context.Context, req *visionpb.RemoveProductFromProductSetRequest, opts ...gax.CallOption) error { +func (c *productSearchGRPCClient) RemoveProductFromProductSet(ctx context.Context, req *visionpb.RemoveProductFromProductSetRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -886,7 +1100,7 @@ func (c *ProductSearchClient) RemoveProductFromProductSet(ctx context.Context, r } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.RemoveProductFromProductSet[0:len(c.CallOptions.RemoveProductFromProductSet):len(c.CallOptions.RemoveProductFromProductSet)], opts...) + opts = append((*c.CallOptions).RemoveProductFromProductSet[0:len((*c.CallOptions).RemoveProductFromProductSet):len((*c.CallOptions).RemoveProductFromProductSet)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.productSearchClient.RemoveProductFromProductSet(ctx, req, settings.GRPC...) @@ -895,17 +1109,10 @@ func (c *ProductSearchClient) RemoveProductFromProductSet(ctx context.Context, r return err } -// ListProductsInProductSet lists the Products in a ProductSet, in an unspecified order. If the -// ProductSet does not exist, the products field of the response will be -// empty. -// -// Possible errors: -// -// Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1. -func (c *ProductSearchClient) ListProductsInProductSet(ctx context.Context, req *visionpb.ListProductsInProductSetRequest, opts ...gax.CallOption) *ProductIterator { +func (c *productSearchGRPCClient) ListProductsInProductSet(ctx context.Context, req *visionpb.ListProductsInProductSetRequest, opts ...gax.CallOption) *ProductIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListProductsInProductSet[0:len(c.CallOptions.ListProductsInProductSet):len(c.CallOptions.ListProductsInProductSet)], opts...) + opts = append((*c.CallOptions).ListProductsInProductSet[0:len((*c.CallOptions).ListProductsInProductSet):len((*c.CallOptions).ListProductsInProductSet)], opts...) it := &ProductIterator{} req = proto.Clone(req).(*visionpb.ListProductsInProductSetRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*visionpb.Product, string, error) { @@ -942,18 +1149,7 @@ func (c *ProductSearchClient) ListProductsInProductSet(ctx context.Context, req return it } -// ImportProductSets asynchronous API that imports a list of reference images to specified -// product sets based on a list of image information. -// -// The google.longrunning.Operation API can be used to keep track of the -// progress and results of the request. -// Operation.metadata contains BatchOperationMetadata. (progress) -// Operation.response contains ImportProductSetsResponse. (results) -// -// The input source of this method is a csv file on Google Cloud Storage. -// For the format of the csv file please see -// ImportProductSetsGcsSource.csv_file_uri. -func (c *ProductSearchClient) ImportProductSets(ctx context.Context, req *visionpb.ImportProductSetsRequest, opts ...gax.CallOption) (*ImportProductSetsOperation, error) { +func (c *productSearchGRPCClient) ImportProductSets(ctx context.Context, req *visionpb.ImportProductSetsRequest, opts ...gax.CallOption) (*ImportProductSetsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -961,7 +1157,7 @@ func (c *ProductSearchClient) ImportProductSets(ctx context.Context, req *vision } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ImportProductSets[0:len(c.CallOptions.ImportProductSets):len(c.CallOptions.ImportProductSets)], opts...) + opts = append((*c.CallOptions).ImportProductSets[0:len((*c.CallOptions).ImportProductSets):len((*c.CallOptions).ImportProductSets)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -972,35 +1168,11 @@ func (c *ProductSearchClient) ImportProductSets(ctx context.Context, req *vision return nil, err } return &ImportProductSetsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// PurgeProducts asynchronous API to delete all Products in a ProductSet or all Products -// that are in no ProductSet. -// -// If a Product is a member of the specified ProductSet in addition to other -// ProductSets, the Product will still be deleted. -// -// It is recommended to not delete the specified ProductSet until after this -// operation has completed. It is also recommended to not add any of the -// Products involved in the batch delete to a new ProductSet while this -// operation is running because those Products may still end up deleted. -// -// It’s not possible to undo the PurgeProducts operation. Therefore, it is -// recommended to keep the csv files used in ImportProductSets (if that was -// how you originally built the Product Set) before starting PurgeProducts, in -// case you need to re-import the data after deletion. -// -// If the plan is to purge all of the Products from a ProductSet and then -// re-use the empty ProductSet to re-import new Products into the empty -// ProductSet, you must wait until the PurgeProducts operation has finished -// for that ProductSet. -// -// The google.longrunning.Operation API can be used to keep track of the -// progress and results of the request. -// Operation.metadata contains BatchOperationMetadata. (progress) -func (c *ProductSearchClient) PurgeProducts(ctx context.Context, req *visionpb.PurgeProductsRequest, opts ...gax.CallOption) (*PurgeProductsOperation, error) { +func (c *productSearchGRPCClient) PurgeProducts(ctx context.Context, req *visionpb.PurgeProductsRequest, opts ...gax.CallOption) (*PurgeProductsOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -1008,7 +1180,7 @@ func (c *ProductSearchClient) PurgeProducts(ctx context.Context, req *visionpb.P } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.PurgeProducts[0:len(c.CallOptions.PurgeProducts):len(c.CallOptions.PurgeProducts)], opts...) + opts = append((*c.CallOptions).PurgeProducts[0:len((*c.CallOptions).PurgeProducts):len((*c.CallOptions).PurgeProducts)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -1019,7 +1191,7 @@ func (c *ProductSearchClient) PurgeProducts(ctx context.Context, req *visionpb.P return nil, err } return &PurgeProductsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -1030,9 +1202,9 @@ type ImportProductSetsOperation struct { // ImportProductSetsOperation returns a new ImportProductSetsOperation from a given name. // The name must be that of a previously created ImportProductSetsOperation, possibly from a different process. -func (c *ProductSearchClient) ImportProductSetsOperation(name string) *ImportProductSetsOperation { +func (c *productSearchGRPCClient) ImportProductSetsOperation(name string) *ImportProductSetsOperation { return &ImportProductSetsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -1099,9 +1271,9 @@ type PurgeProductsOperation struct { // PurgeProductsOperation returns a new PurgeProductsOperation from a given name. // The name must be that of a previously created PurgeProductsOperation, possibly from a different process. -func (c *ProductSearchClient) PurgeProductsOperation(name string) *PurgeProductsOperation { +func (c *productSearchGRPCClient) PurgeProductsOperation(name string) *PurgeProductsOperation { return &PurgeProductsOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/vision/apiv1/product_search_client_example_test.go b/vision/apiv1/product_search_client_example_test.go index c155925a0022..282f7348c2e7 100644 --- a/vision/apiv1/product_search_client_example_test.go +++ b/vision/apiv1/product_search_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewProductSearchClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleProductSearchClient_CreateProductSet() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.CreateProductSetRequest{ // TODO: Fill request struct fields. @@ -55,14 +56,12 @@ func ExampleProductSearchClient_CreateProductSet() { } func ExampleProductSearchClient_ListProductSets() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.ListProductSetsRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleProductSearchClient_ListProductSets() { } func ExampleProductSearchClient_GetProductSet() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.GetProductSetRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleProductSearchClient_GetProductSet() { } func ExampleProductSearchClient_UpdateProductSet() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.UpdateProductSetRequest{ // TODO: Fill request struct fields. @@ -127,6 +124,7 @@ func ExampleProductSearchClient_DeleteProductSet() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.DeleteProductSetRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleProductSearchClient_DeleteProductSet() { } func ExampleProductSearchClient_CreateProduct() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.CreateProductRequest{ // TODO: Fill request struct fields. @@ -158,14 +155,12 @@ func ExampleProductSearchClient_CreateProduct() { } func ExampleProductSearchClient_ListProducts() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.ListProductsRequest{ // TODO: Fill request struct fields. @@ -185,13 +180,12 @@ func ExampleProductSearchClient_ListProducts() { } func ExampleProductSearchClient_GetProduct() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.GetProductRequest{ // TODO: Fill request struct fields. @@ -205,13 +199,12 @@ func ExampleProductSearchClient_GetProduct() { } func ExampleProductSearchClient_UpdateProduct() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.UpdateProductRequest{ // TODO: Fill request struct fields. @@ -230,6 +223,7 @@ func ExampleProductSearchClient_DeleteProduct() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.DeleteProductRequest{ // TODO: Fill request struct fields. @@ -241,13 +235,12 @@ func ExampleProductSearchClient_DeleteProduct() { } func ExampleProductSearchClient_CreateReferenceImage() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.CreateReferenceImageRequest{ // TODO: Fill request struct fields. @@ -266,6 +259,7 @@ func ExampleProductSearchClient_DeleteReferenceImage() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.DeleteReferenceImageRequest{ // TODO: Fill request struct fields. @@ -277,14 +271,12 @@ func ExampleProductSearchClient_DeleteReferenceImage() { } func ExampleProductSearchClient_ListReferenceImages() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.ListReferenceImagesRequest{ // TODO: Fill request struct fields. @@ -304,13 +296,12 @@ func ExampleProductSearchClient_ListReferenceImages() { } func ExampleProductSearchClient_GetReferenceImage() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.GetReferenceImageRequest{ // TODO: Fill request struct fields. @@ -329,6 +320,7 @@ func ExampleProductSearchClient_AddProductToProductSet() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.AddProductToProductSetRequest{ // TODO: Fill request struct fields. @@ -345,6 +337,7 @@ func ExampleProductSearchClient_RemoveProductFromProductSet() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.RemoveProductFromProductSetRequest{ // TODO: Fill request struct fields. @@ -356,14 +349,12 @@ func ExampleProductSearchClient_RemoveProductFromProductSet() { } func ExampleProductSearchClient_ListProductsInProductSet() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.ListProductsInProductSetRequest{ // TODO: Fill request struct fields. @@ -383,13 +374,12 @@ func ExampleProductSearchClient_ListProductsInProductSet() { } func ExampleProductSearchClient_ImportProductSets() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.ImportProductSetsRequest{ // TODO: Fill request struct fields. @@ -408,13 +398,12 @@ func ExampleProductSearchClient_ImportProductSets() { } func ExampleProductSearchClient_PurgeProducts() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" - ctx := context.Background() c, err := vision.NewProductSearchClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.PurgeProductsRequest{ // TODO: Fill request struct fields. diff --git a/vision/apiv1p1beta1/doc.go b/vision/apiv1p1beta1/doc.go index e9560ba222ca..34c01395734c 100644 --- a/vision/apiv1p1beta1/doc.go +++ b/vision/apiv1p1beta1/doc.go @@ -21,6 +21,8 @@ // and landmark detection, optical character recognition (OCR), and detection // of explicit content, into applications. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -30,7 +32,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package vision // import "cloud.google.com/go/vision/apiv1p1beta1" import ( @@ -50,7 +52,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/vision/apiv1p1beta1/image_annotator_client.go b/vision/apiv1p1beta1/image_annotator_client.go index b135d8faeb74..6aec0b3d0e36 100644 --- a/vision/apiv1p1beta1/image_annotator_client.go +++ b/vision/apiv1p1beta1/image_annotator_client.go @@ -38,7 +38,7 @@ type ImageAnnotatorCallOptions struct { BatchAnnotateImages []gax.CallOption } -func defaultImageAnnotatorClientOptions() []option.ClientOption { +func defaultImageAnnotatorGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("vision.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("vision.mtls.googleapis.com:443"), @@ -67,34 +67,83 @@ func defaultImageAnnotatorCallOptions() *ImageAnnotatorCallOptions { } } +// internalImageAnnotatorClient is an interface that defines the methods availaible from Cloud Vision API. +type internalImageAnnotatorClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + BatchAnnotateImages(context.Context, *visionpb.BatchAnnotateImagesRequest, ...gax.CallOption) (*visionpb.BatchAnnotateImagesResponse, error) +} + // ImageAnnotatorClient is a client for interacting with Cloud Vision API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Service that performs Google Cloud Vision API detection tasks over client +// images, such as face, landmark, logo, label, and text detection. The +// ImageAnnotator service returns detected entities from the images. type ImageAnnotatorClient struct { + // The internal transport-dependent client. + internalClient internalImageAnnotatorClient + + // The call options for this service. + CallOptions *ImageAnnotatorCallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *ImageAnnotatorClient) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *ImageAnnotatorClient) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *ImageAnnotatorClient) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// BatchAnnotateImages run image detection and annotation for a batch of images. +func (c *ImageAnnotatorClient) BatchAnnotateImages(ctx context.Context, req *visionpb.BatchAnnotateImagesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateImagesResponse, error) { + return c.internalClient.BatchAnnotateImages(ctx, req, opts...) +} + +// imageAnnotatorGRPCClient is a client for interacting with Cloud Vision API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type imageAnnotatorGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing ImageAnnotatorClient + CallOptions **ImageAnnotatorCallOptions + // The gRPC API client. imageAnnotatorClient visionpb.ImageAnnotatorClient - // The call options for this service. - CallOptions *ImageAnnotatorCallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewImageAnnotatorClient creates a new image annotator client. +// NewImageAnnotatorClient creates a new image annotator client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service that performs Google Cloud Vision API detection tasks over client // images, such as face, landmark, logo, label, and text detection. The // ImageAnnotator service returns detected entities from the images. func NewImageAnnotatorClient(ctx context.Context, opts ...option.ClientOption) (*ImageAnnotatorClient, error) { - clientOpts := defaultImageAnnotatorClientOptions() - + clientOpts := defaultImageAnnotatorGRPCClientOptions() if newImageAnnotatorClientHook != nil { hookOpts, err := newImageAnnotatorClientHook(ctx, clientHookParams{}) if err != nil { @@ -112,49 +161,51 @@ func NewImageAnnotatorClient(ctx context.Context, opts ...option.ClientOption) ( if err != nil { return nil, err } - c := &ImageAnnotatorClient{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultImageAnnotatorCallOptions(), + client := ImageAnnotatorClient{CallOptions: defaultImageAnnotatorCallOptions()} + c := &imageAnnotatorGRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, imageAnnotatorClient: visionpb.NewImageAnnotatorClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *ImageAnnotatorClient) Connection() *grpc.ClientConn { +func (c *imageAnnotatorGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *ImageAnnotatorClient) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *ImageAnnotatorClient) setGoogleClientInfo(keyval ...string) { +func (c *imageAnnotatorGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// BatchAnnotateImages run image detection and annotation for a batch of images. -func (c *ImageAnnotatorClient) BatchAnnotateImages(ctx context.Context, req *visionpb.BatchAnnotateImagesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateImagesResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *imageAnnotatorGRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *imageAnnotatorGRPCClient) BatchAnnotateImages(ctx context.Context, req *visionpb.BatchAnnotateImagesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateImagesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.BatchAnnotateImages[0:len(c.CallOptions.BatchAnnotateImages):len(c.CallOptions.BatchAnnotateImages)], opts...) + opts = append((*c.CallOptions).BatchAnnotateImages[0:len((*c.CallOptions).BatchAnnotateImages):len((*c.CallOptions).BatchAnnotateImages)], opts...) var resp *visionpb.BatchAnnotateImagesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/vision/apiv1p1beta1/image_annotator_client_example_test.go b/vision/apiv1p1beta1/image_annotator_client_example_test.go index ed49eb87e63f..6a5d316be210 100644 --- a/vision/apiv1p1beta1/image_annotator_client_example_test.go +++ b/vision/apiv1p1beta1/image_annotator_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewImageAnnotatorClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleImageAnnotatorClient_BatchAnnotateImages() { - // import visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1p1beta1" - ctx := context.Background() c, err := vision.NewImageAnnotatorClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &visionpb.BatchAnnotateImagesRequest{ // TODO: Fill request struct fields. diff --git a/webrisk/apiv1/doc.go b/webrisk/apiv1/doc.go index 92201937d8ae..1da749278fb2 100644 --- a/webrisk/apiv1/doc.go +++ b/webrisk/apiv1/doc.go @@ -26,7 +26,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package webrisk // import "cloud.google.com/go/webrisk/apiv1" import ( @@ -46,7 +46,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/webrisk/apiv1/web_risk_client.go b/webrisk/apiv1/web_risk_client.go index 3ded36bccaf5..12434e19ef77 100644 --- a/webrisk/apiv1/web_risk_client.go +++ b/webrisk/apiv1/web_risk_client.go @@ -43,7 +43,7 @@ type CallOptions struct { CreateSubmission []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("webrisk.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("webrisk.mtls.googleapis.com:443"), @@ -97,33 +97,117 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Web Risk API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ComputeThreatListDiff(context.Context, *webriskpb.ComputeThreatListDiffRequest, ...gax.CallOption) (*webriskpb.ComputeThreatListDiffResponse, error) + SearchUris(context.Context, *webriskpb.SearchUrisRequest, ...gax.CallOption) (*webriskpb.SearchUrisResponse, error) + SearchHashes(context.Context, *webriskpb.SearchHashesRequest, ...gax.CallOption) (*webriskpb.SearchHashesResponse, error) + CreateSubmission(context.Context, *webriskpb.CreateSubmissionRequest, ...gax.CallOption) (*webriskpb.Submission, error) +} + // Client is a client for interacting with Web Risk API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Web Risk API defines an interface to detect malicious URLs on your +// website and in client applications. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ComputeThreatListDiff gets the most recent threat list diffs. These diffs should be applied to +// a local database of hashes to keep it up-to-date. If the local database is +// empty or excessively out-of-date, a complete snapshot of the database will +// be returned. This Method only updates a single ThreatList at a time. To +// update multiple ThreatList databases, this method needs to be called once +// for each list. +func (c *Client) ComputeThreatListDiff(ctx context.Context, req *webriskpb.ComputeThreatListDiffRequest, opts ...gax.CallOption) (*webriskpb.ComputeThreatListDiffResponse, error) { + return c.internalClient.ComputeThreatListDiff(ctx, req, opts...) +} + +// SearchUris this method is used to check whether a URI is on a given threatList. +// Multiple threatLists may be searched in a single query. +// The response will list all requested threatLists the URI was found to +// match. If the URI is not found on any of the requested ThreatList an +// empty response will be returned. +func (c *Client) SearchUris(ctx context.Context, req *webriskpb.SearchUrisRequest, opts ...gax.CallOption) (*webriskpb.SearchUrisResponse, error) { + return c.internalClient.SearchUris(ctx, req, opts...) +} + +// SearchHashes gets the full hashes that match the requested hash prefix. +// This is used after a hash prefix is looked up in a threatList +// and there is a match. The client side threatList only holds partial hashes +// so the client must query this method to determine if there is a full +// hash match of a threat. +func (c *Client) SearchHashes(ctx context.Context, req *webriskpb.SearchHashesRequest, opts ...gax.CallOption) (*webriskpb.SearchHashesResponse, error) { + return c.internalClient.SearchHashes(ctx, req, opts...) +} + +// CreateSubmission creates a Submission of a URI suspected of containing phishing content to +// be reviewed. If the result verifies the existence of malicious phishing +// content, the site will be added to the Google’s Social Engineering +// lists (at https://support.google.com/webmasters/answer/6350487/) in order to +// protect users that could get exposed to this threat in the future. Only +// projects with CREATE_SUBMISSION_USERS visibility can use this method. +func (c *Client) CreateSubmission(ctx context.Context, req *webriskpb.CreateSubmissionRequest, opts ...gax.CallOption) (*webriskpb.Submission, error) { + return c.internalClient.CreateSubmission(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Web Risk API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client webriskpb.WebRiskServiceClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new web risk service client. +// NewClient creates a new web risk service client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Web Risk API defines an interface to detect malicious URLs on your // website and in client applications. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -141,54 +225,51 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: webriskpb.NewWebRiskServiceClient(connPool), + client: webriskpb.NewWebRiskServiceClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ComputeThreatListDiff gets the most recent threat list diffs. These diffs should be applied to -// a local database of hashes to keep it up-to-date. If the local database is -// empty or excessively out-of-date, a complete snapshot of the database will -// be returned. This Method only updates a single ThreatList at a time. To -// update multiple ThreatList databases, this method needs to be called once -// for each list. -func (c *Client) ComputeThreatListDiff(ctx context.Context, req *webriskpb.ComputeThreatListDiffRequest, opts ...gax.CallOption) (*webriskpb.ComputeThreatListDiffResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ComputeThreatListDiff(ctx context.Context, req *webriskpb.ComputeThreatListDiffRequest, opts ...gax.CallOption) (*webriskpb.ComputeThreatListDiffResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ComputeThreatListDiff[0:len(c.CallOptions.ComputeThreatListDiff):len(c.CallOptions.ComputeThreatListDiff)], opts...) + opts = append((*c.CallOptions).ComputeThreatListDiff[0:len((*c.CallOptions).ComputeThreatListDiff):len((*c.CallOptions).ComputeThreatListDiff)], opts...) var resp *webriskpb.ComputeThreatListDiffResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -201,19 +282,14 @@ func (c *Client) ComputeThreatListDiff(ctx context.Context, req *webriskpb.Compu return resp, nil } -// SearchUris this method is used to check whether a URI is on a given threatList. -// Multiple threatLists may be searched in a single query. -// The response will list all requested threatLists the URI was found to -// match. If the URI is not found on any of the requested ThreatList an -// empty response will be returned. -func (c *Client) SearchUris(ctx context.Context, req *webriskpb.SearchUrisRequest, opts ...gax.CallOption) (*webriskpb.SearchUrisResponse, error) { +func (c *gRPCClient) SearchUris(ctx context.Context, req *webriskpb.SearchUrisRequest, opts ...gax.CallOption) (*webriskpb.SearchUrisResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.SearchUris[0:len(c.CallOptions.SearchUris):len(c.CallOptions.SearchUris)], opts...) + opts = append((*c.CallOptions).SearchUris[0:len((*c.CallOptions).SearchUris):len((*c.CallOptions).SearchUris)], opts...) var resp *webriskpb.SearchUrisResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -226,19 +302,14 @@ func (c *Client) SearchUris(ctx context.Context, req *webriskpb.SearchUrisReques return resp, nil } -// SearchHashes gets the full hashes that match the requested hash prefix. -// This is used after a hash prefix is looked up in a threatList -// and there is a match. The client side threatList only holds partial hashes -// so the client must query this method to determine if there is a full -// hash match of a threat. -func (c *Client) SearchHashes(ctx context.Context, req *webriskpb.SearchHashesRequest, opts ...gax.CallOption) (*webriskpb.SearchHashesResponse, error) { +func (c *gRPCClient) SearchHashes(ctx context.Context, req *webriskpb.SearchHashesRequest, opts ...gax.CallOption) (*webriskpb.SearchHashesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.SearchHashes[0:len(c.CallOptions.SearchHashes):len(c.CallOptions.SearchHashes)], opts...) + opts = append((*c.CallOptions).SearchHashes[0:len((*c.CallOptions).SearchHashes):len((*c.CallOptions).SearchHashes)], opts...) var resp *webriskpb.SearchHashesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -251,13 +322,7 @@ func (c *Client) SearchHashes(ctx context.Context, req *webriskpb.SearchHashesRe return resp, nil } -// CreateSubmission creates a Submission of a URI suspected of containing phishing content to -// be reviewed. If the result verifies the existence of malicious phishing -// content, the site will be added to the Google’s Social Engineering -// lists (at https://support.google.com/webmasters/answer/6350487/) in order to -// protect users that could get exposed to this threat in the future. Only -// projects with CREATE_SUBMISSION_USERS visibility can use this method. -func (c *Client) CreateSubmission(ctx context.Context, req *webriskpb.CreateSubmissionRequest, opts ...gax.CallOption) (*webriskpb.Submission, error) { +func (c *gRPCClient) CreateSubmission(ctx context.Context, req *webriskpb.CreateSubmissionRequest, opts ...gax.CallOption) (*webriskpb.Submission, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) defer cancel() @@ -265,7 +330,7 @@ func (c *Client) CreateSubmission(ctx context.Context, req *webriskpb.CreateSubm } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSubmission[0:len(c.CallOptions.CreateSubmission):len(c.CallOptions.CreateSubmission)], opts...) + opts = append((*c.CallOptions).CreateSubmission[0:len((*c.CallOptions).CreateSubmission):len((*c.CallOptions).CreateSubmission)], opts...) var resp *webriskpb.Submission err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/webrisk/apiv1/web_risk_client_example_test.go b/webrisk/apiv1/web_risk_client_example_test.go index ca068a65efb7..cdfd2c669a39 100644 --- a/webrisk/apiv1/web_risk_client_example_test.go +++ b/webrisk/apiv1/web_risk_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ComputeThreatListDiff() { - // import webriskpb "google.golang.org/genproto/googleapis/cloud/webrisk/v1" - ctx := context.Background() c, err := webrisk.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &webriskpb.ComputeThreatListDiffRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleClient_ComputeThreatListDiff() { } func ExampleClient_SearchUris() { - // import webriskpb "google.golang.org/genproto/googleapis/cloud/webrisk/v1" - ctx := context.Background() c, err := webrisk.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &webriskpb.SearchUrisRequest{ // TODO: Fill request struct fields. @@ -74,13 +74,12 @@ func ExampleClient_SearchUris() { } func ExampleClient_SearchHashes() { - // import webriskpb "google.golang.org/genproto/googleapis/cloud/webrisk/v1" - ctx := context.Background() c, err := webrisk.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &webriskpb.SearchHashesRequest{ // TODO: Fill request struct fields. @@ -94,13 +93,12 @@ func ExampleClient_SearchHashes() { } func ExampleClient_CreateSubmission() { - // import webriskpb "google.golang.org/genproto/googleapis/cloud/webrisk/v1" - ctx := context.Background() c, err := webrisk.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &webriskpb.CreateSubmissionRequest{ // TODO: Fill request struct fields. diff --git a/webrisk/apiv1beta1/doc.go b/webrisk/apiv1beta1/doc.go index 314bbbe54b13..d8cd829add9f 100644 --- a/webrisk/apiv1beta1/doc.go +++ b/webrisk/apiv1beta1/doc.go @@ -17,6 +17,8 @@ // Package webrisk is an auto-generated package for the // Web Risk API. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -26,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package webrisk // import "cloud.google.com/go/webrisk/apiv1beta1" import ( @@ -46,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/webrisk/apiv1beta1/web_risk_service_v1_beta1_client.go b/webrisk/apiv1beta1/web_risk_service_v1_beta1_client.go index 56cd396a824b..685d308f758e 100644 --- a/webrisk/apiv1beta1/web_risk_service_v1_beta1_client.go +++ b/webrisk/apiv1beta1/web_risk_service_v1_beta1_client.go @@ -40,7 +40,7 @@ type WebRiskServiceV1Beta1CallOptions struct { SearchHashes []gax.CallOption } -func defaultWebRiskServiceV1Beta1ClientOptions() []option.ClientOption { +func defaultWebRiskServiceV1Beta1GRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("webrisk.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("webrisk.mtls.googleapis.com:443"), @@ -93,33 +93,97 @@ func defaultWebRiskServiceV1Beta1CallOptions() *WebRiskServiceV1Beta1CallOptions } } +// internalWebRiskServiceV1Beta1Client is an interface that defines the methods availaible from Web Risk API. +type internalWebRiskServiceV1Beta1Client interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ComputeThreatListDiff(context.Context, *webriskpb.ComputeThreatListDiffRequest, ...gax.CallOption) (*webriskpb.ComputeThreatListDiffResponse, error) + SearchUris(context.Context, *webriskpb.SearchUrisRequest, ...gax.CallOption) (*webriskpb.SearchUrisResponse, error) + SearchHashes(context.Context, *webriskpb.SearchHashesRequest, ...gax.CallOption) (*webriskpb.SearchHashesResponse, error) +} + // WebRiskServiceV1Beta1Client is a client for interacting with Web Risk API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Web Risk v1beta1 API defines an interface to detect malicious URLs on your +// website and in client applications. type WebRiskServiceV1Beta1Client struct { + // The internal transport-dependent client. + internalClient internalWebRiskServiceV1Beta1Client + + // The call options for this service. + CallOptions *WebRiskServiceV1Beta1CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *WebRiskServiceV1Beta1Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *WebRiskServiceV1Beta1Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *WebRiskServiceV1Beta1Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ComputeThreatListDiff gets the most recent threat list diffs. +func (c *WebRiskServiceV1Beta1Client) ComputeThreatListDiff(ctx context.Context, req *webriskpb.ComputeThreatListDiffRequest, opts ...gax.CallOption) (*webriskpb.ComputeThreatListDiffResponse, error) { + return c.internalClient.ComputeThreatListDiff(ctx, req, opts...) +} + +// SearchUris this method is used to check whether a URI is on a given threatList. +func (c *WebRiskServiceV1Beta1Client) SearchUris(ctx context.Context, req *webriskpb.SearchUrisRequest, opts ...gax.CallOption) (*webriskpb.SearchUrisResponse, error) { + return c.internalClient.SearchUris(ctx, req, opts...) +} + +// SearchHashes gets the full hashes that match the requested hash prefix. +// This is used after a hash prefix is looked up in a threatList +// and there is a match. The client side threatList only holds partial hashes +// so the client must query this method to determine if there is a full +// hash match of a threat. +func (c *WebRiskServiceV1Beta1Client) SearchHashes(ctx context.Context, req *webriskpb.SearchHashesRequest, opts ...gax.CallOption) (*webriskpb.SearchHashesResponse, error) { + return c.internalClient.SearchHashes(ctx, req, opts...) +} + +// webRiskServiceV1Beta1GRPCClient is a client for interacting with Web Risk API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type webRiskServiceV1Beta1GRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing WebRiskServiceV1Beta1Client + CallOptions **WebRiskServiceV1Beta1CallOptions + // The gRPC API client. webRiskServiceV1Beta1Client webriskpb.WebRiskServiceV1Beta1Client - // The call options for this service. - CallOptions *WebRiskServiceV1Beta1CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewWebRiskServiceV1Beta1Client creates a new web risk service v1 beta1 client. +// NewWebRiskServiceV1Beta1Client creates a new web risk service v1 beta1 client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Web Risk v1beta1 API defines an interface to detect malicious URLs on your // website and in client applications. func NewWebRiskServiceV1Beta1Client(ctx context.Context, opts ...option.ClientOption) (*WebRiskServiceV1Beta1Client, error) { - clientOpts := defaultWebRiskServiceV1Beta1ClientOptions() - + clientOpts := defaultWebRiskServiceV1Beta1GRPCClientOptions() if newWebRiskServiceV1Beta1ClientHook != nil { hookOpts, err := newWebRiskServiceV1Beta1ClientHook(ctx, clientHookParams{}) if err != nil { @@ -137,49 +201,51 @@ func NewWebRiskServiceV1Beta1Client(ctx context.Context, opts ...option.ClientOp if err != nil { return nil, err } - c := &WebRiskServiceV1Beta1Client{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultWebRiskServiceV1Beta1CallOptions(), + client := WebRiskServiceV1Beta1Client{CallOptions: defaultWebRiskServiceV1Beta1CallOptions()} + c := &webRiskServiceV1Beta1GRPCClient{ + connPool: connPool, + disableDeadlines: disableDeadlines, webRiskServiceV1Beta1Client: webriskpb.NewWebRiskServiceV1Beta1Client(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *WebRiskServiceV1Beta1Client) Connection() *grpc.ClientConn { +func (c *webRiskServiceV1Beta1GRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *WebRiskServiceV1Beta1Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *WebRiskServiceV1Beta1Client) setGoogleClientInfo(keyval ...string) { +func (c *webRiskServiceV1Beta1GRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ComputeThreatListDiff gets the most recent threat list diffs. -func (c *WebRiskServiceV1Beta1Client) ComputeThreatListDiff(ctx context.Context, req *webriskpb.ComputeThreatListDiffRequest, opts ...gax.CallOption) (*webriskpb.ComputeThreatListDiffResponse, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *webRiskServiceV1Beta1GRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *webRiskServiceV1Beta1GRPCClient) ComputeThreatListDiff(ctx context.Context, req *webriskpb.ComputeThreatListDiffRequest, opts ...gax.CallOption) (*webriskpb.ComputeThreatListDiffResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.ComputeThreatListDiff[0:len(c.CallOptions.ComputeThreatListDiff):len(c.CallOptions.ComputeThreatListDiff)], opts...) + opts = append((*c.CallOptions).ComputeThreatListDiff[0:len((*c.CallOptions).ComputeThreatListDiff):len((*c.CallOptions).ComputeThreatListDiff)], opts...) var resp *webriskpb.ComputeThreatListDiffResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -192,15 +258,14 @@ func (c *WebRiskServiceV1Beta1Client) ComputeThreatListDiff(ctx context.Context, return resp, nil } -// SearchUris this method is used to check whether a URI is on a given threatList. -func (c *WebRiskServiceV1Beta1Client) SearchUris(ctx context.Context, req *webriskpb.SearchUrisRequest, opts ...gax.CallOption) (*webriskpb.SearchUrisResponse, error) { +func (c *webRiskServiceV1Beta1GRPCClient) SearchUris(ctx context.Context, req *webriskpb.SearchUrisRequest, opts ...gax.CallOption) (*webriskpb.SearchUrisResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.SearchUris[0:len(c.CallOptions.SearchUris):len(c.CallOptions.SearchUris)], opts...) + opts = append((*c.CallOptions).SearchUris[0:len((*c.CallOptions).SearchUris):len((*c.CallOptions).SearchUris)], opts...) var resp *webriskpb.SearchUrisResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -213,19 +278,14 @@ func (c *WebRiskServiceV1Beta1Client) SearchUris(ctx context.Context, req *webri return resp, nil } -// SearchHashes gets the full hashes that match the requested hash prefix. -// This is used after a hash prefix is looked up in a threatList -// and there is a match. The client side threatList only holds partial hashes -// so the client must query this method to determine if there is a full -// hash match of a threat. -func (c *WebRiskServiceV1Beta1Client) SearchHashes(ctx context.Context, req *webriskpb.SearchHashesRequest, opts ...gax.CallOption) (*webriskpb.SearchHashesResponse, error) { +func (c *webRiskServiceV1Beta1GRPCClient) SearchHashes(ctx context.Context, req *webriskpb.SearchHashesRequest, opts ...gax.CallOption) (*webriskpb.SearchHashesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } ctx = insertMetadata(ctx, c.xGoogMetadata) - opts = append(c.CallOptions.SearchHashes[0:len(c.CallOptions.SearchHashes):len(c.CallOptions.SearchHashes)], opts...) + opts = append((*c.CallOptions).SearchHashes[0:len((*c.CallOptions).SearchHashes):len((*c.CallOptions).SearchHashes)], opts...) var resp *webriskpb.SearchHashesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/webrisk/apiv1beta1/web_risk_service_v1_beta1_client_example_test.go b/webrisk/apiv1beta1/web_risk_service_v1_beta1_client_example_test.go index a5c0719ebe0c..69dad3bd8ead 100644 --- a/webrisk/apiv1beta1/web_risk_service_v1_beta1_client_example_test.go +++ b/webrisk/apiv1beta1/web_risk_service_v1_beta1_client_example_test.go @@ -29,18 +29,19 @@ func ExampleNewWebRiskServiceV1Beta1Client() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleWebRiskServiceV1Beta1Client_ComputeThreatListDiff() { - // import webriskpb "google.golang.org/genproto/googleapis/cloud/webrisk/v1beta1" - ctx := context.Background() c, err := webrisk.NewWebRiskServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &webriskpb.ComputeThreatListDiffRequest{ // TODO: Fill request struct fields. @@ -54,13 +55,12 @@ func ExampleWebRiskServiceV1Beta1Client_ComputeThreatListDiff() { } func ExampleWebRiskServiceV1Beta1Client_SearchUris() { - // import webriskpb "google.golang.org/genproto/googleapis/cloud/webrisk/v1beta1" - ctx := context.Background() c, err := webrisk.NewWebRiskServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &webriskpb.SearchUrisRequest{ // TODO: Fill request struct fields. @@ -74,13 +74,12 @@ func ExampleWebRiskServiceV1Beta1Client_SearchUris() { } func ExampleWebRiskServiceV1Beta1Client_SearchHashes() { - // import webriskpb "google.golang.org/genproto/googleapis/cloud/webrisk/v1beta1" - ctx := context.Background() c, err := webrisk.NewWebRiskServiceV1Beta1Client(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &webriskpb.SearchHashesRequest{ // TODO: Fill request struct fields. diff --git a/websecurityscanner/apiv1/doc.go b/websecurityscanner/apiv1/doc.go index 22a64ba59189..6cfc38b30389 100644 --- a/websecurityscanner/apiv1/doc.go +++ b/websecurityscanner/apiv1/doc.go @@ -28,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package websecurityscanner // import "cloud.google.com/go/websecurityscanner/apiv1" import ( @@ -48,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/websecurityscanner/apiv1/web_security_scanner_client.go b/websecurityscanner/apiv1/web_security_scanner_client.go index 6f97ede209df..4027b961550b 100644 --- a/websecurityscanner/apiv1/web_security_scanner_client.go +++ b/websecurityscanner/apiv1/web_security_scanner_client.go @@ -54,7 +54,7 @@ type CallOptions struct { ListFindingTypeStats []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("websecurityscanner.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("websecurityscanner.mtls.googleapis.com:443"), @@ -183,34 +183,156 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Web Security Scanner API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + CreateScanConfig(context.Context, *websecurityscannerpb.CreateScanConfigRequest, ...gax.CallOption) (*websecurityscannerpb.ScanConfig, error) + DeleteScanConfig(context.Context, *websecurityscannerpb.DeleteScanConfigRequest, ...gax.CallOption) error + GetScanConfig(context.Context, *websecurityscannerpb.GetScanConfigRequest, ...gax.CallOption) (*websecurityscannerpb.ScanConfig, error) + ListScanConfigs(context.Context, *websecurityscannerpb.ListScanConfigsRequest, ...gax.CallOption) *ScanConfigIterator + UpdateScanConfig(context.Context, *websecurityscannerpb.UpdateScanConfigRequest, ...gax.CallOption) (*websecurityscannerpb.ScanConfig, error) + StartScanRun(context.Context, *websecurityscannerpb.StartScanRunRequest, ...gax.CallOption) (*websecurityscannerpb.ScanRun, error) + GetScanRun(context.Context, *websecurityscannerpb.GetScanRunRequest, ...gax.CallOption) (*websecurityscannerpb.ScanRun, error) + ListScanRuns(context.Context, *websecurityscannerpb.ListScanRunsRequest, ...gax.CallOption) *ScanRunIterator + StopScanRun(context.Context, *websecurityscannerpb.StopScanRunRequest, ...gax.CallOption) (*websecurityscannerpb.ScanRun, error) + ListCrawledUrls(context.Context, *websecurityscannerpb.ListCrawledUrlsRequest, ...gax.CallOption) *CrawledUrlIterator + GetFinding(context.Context, *websecurityscannerpb.GetFindingRequest, ...gax.CallOption) (*websecurityscannerpb.Finding, error) + ListFindings(context.Context, *websecurityscannerpb.ListFindingsRequest, ...gax.CallOption) *FindingIterator + ListFindingTypeStats(context.Context, *websecurityscannerpb.ListFindingTypeStatsRequest, ...gax.CallOption) (*websecurityscannerpb.ListFindingTypeStatsResponse, error) +} + // Client is a client for interacting with Web Security Scanner API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Web Security Scanner Service identifies security vulnerabilities in web +// applications hosted on Google Cloud. It crawls your application, and +// attempts to exercise as many user inputs and event handlers as possible. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// CreateScanConfig creates a new ScanConfig. +func (c *Client) CreateScanConfig(ctx context.Context, req *websecurityscannerpb.CreateScanConfigRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanConfig, error) { + return c.internalClient.CreateScanConfig(ctx, req, opts...) +} + +// DeleteScanConfig deletes an existing ScanConfig and its child resources. +func (c *Client) DeleteScanConfig(ctx context.Context, req *websecurityscannerpb.DeleteScanConfigRequest, opts ...gax.CallOption) error { + return c.internalClient.DeleteScanConfig(ctx, req, opts...) +} + +// GetScanConfig gets a ScanConfig. +func (c *Client) GetScanConfig(ctx context.Context, req *websecurityscannerpb.GetScanConfigRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanConfig, error) { + return c.internalClient.GetScanConfig(ctx, req, opts...) +} + +// ListScanConfigs lists ScanConfigs under a given project. +func (c *Client) ListScanConfigs(ctx context.Context, req *websecurityscannerpb.ListScanConfigsRequest, opts ...gax.CallOption) *ScanConfigIterator { + return c.internalClient.ListScanConfigs(ctx, req, opts...) +} + +// UpdateScanConfig updates a ScanConfig. This method support partial update of a ScanConfig. +func (c *Client) UpdateScanConfig(ctx context.Context, req *websecurityscannerpb.UpdateScanConfigRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanConfig, error) { + return c.internalClient.UpdateScanConfig(ctx, req, opts...) +} + +// StartScanRun start a ScanRun according to the given ScanConfig. +func (c *Client) StartScanRun(ctx context.Context, req *websecurityscannerpb.StartScanRunRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanRun, error) { + return c.internalClient.StartScanRun(ctx, req, opts...) +} + +// GetScanRun gets a ScanRun. +func (c *Client) GetScanRun(ctx context.Context, req *websecurityscannerpb.GetScanRunRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanRun, error) { + return c.internalClient.GetScanRun(ctx, req, opts...) +} + +// ListScanRuns lists ScanRuns under a given ScanConfig, in descending order of ScanRun +// stop time. +func (c *Client) ListScanRuns(ctx context.Context, req *websecurityscannerpb.ListScanRunsRequest, opts ...gax.CallOption) *ScanRunIterator { + return c.internalClient.ListScanRuns(ctx, req, opts...) +} + +// StopScanRun stops a ScanRun. The stopped ScanRun is returned. +func (c *Client) StopScanRun(ctx context.Context, req *websecurityscannerpb.StopScanRunRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanRun, error) { + return c.internalClient.StopScanRun(ctx, req, opts...) +} + +// ListCrawledUrls list CrawledUrls under a given ScanRun. +func (c *Client) ListCrawledUrls(ctx context.Context, req *websecurityscannerpb.ListCrawledUrlsRequest, opts ...gax.CallOption) *CrawledUrlIterator { + return c.internalClient.ListCrawledUrls(ctx, req, opts...) +} + +// GetFinding gets a Finding. +func (c *Client) GetFinding(ctx context.Context, req *websecurityscannerpb.GetFindingRequest, opts ...gax.CallOption) (*websecurityscannerpb.Finding, error) { + return c.internalClient.GetFinding(ctx, req, opts...) +} + +// ListFindings list Findings under a given ScanRun. +func (c *Client) ListFindings(ctx context.Context, req *websecurityscannerpb.ListFindingsRequest, opts ...gax.CallOption) *FindingIterator { + return c.internalClient.ListFindings(ctx, req, opts...) +} + +// ListFindingTypeStats list all FindingTypeStats under a given ScanRun. +func (c *Client) ListFindingTypeStats(ctx context.Context, req *websecurityscannerpb.ListFindingTypeStatsRequest, opts ...gax.CallOption) (*websecurityscannerpb.ListFindingTypeStatsResponse, error) { + return c.internalClient.ListFindingTypeStats(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Web Security Scanner API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client websecurityscannerpb.WebSecurityScannerClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new web security scanner client. +// NewClient creates a new web security scanner client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Web Security Scanner Service identifies security vulnerabilities in web // applications hosted on Google Cloud. It crawls your application, and // attempts to exercise as many user inputs and event handlers as possible. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -228,42 +350,44 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: websecurityscannerpb.NewWebSecurityScannerClient(connPool), + client: websecurityscannerpb.NewWebSecurityScannerClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// CreateScanConfig creates a new ScanConfig. -func (c *Client) CreateScanConfig(ctx context.Context, req *websecurityscannerpb.CreateScanConfigRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanConfig, error) { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) CreateScanConfig(ctx context.Context, req *websecurityscannerpb.CreateScanConfigRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -271,7 +395,7 @@ func (c *Client) CreateScanConfig(ctx context.Context, req *websecurityscannerpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateScanConfig[0:len(c.CallOptions.CreateScanConfig):len(c.CallOptions.CreateScanConfig)], opts...) + opts = append((*c.CallOptions).CreateScanConfig[0:len((*c.CallOptions).CreateScanConfig):len((*c.CallOptions).CreateScanConfig)], opts...) var resp *websecurityscannerpb.ScanConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -284,8 +408,7 @@ func (c *Client) CreateScanConfig(ctx context.Context, req *websecurityscannerpb return resp, nil } -// DeleteScanConfig deletes an existing ScanConfig and its child resources. -func (c *Client) DeleteScanConfig(ctx context.Context, req *websecurityscannerpb.DeleteScanConfigRequest, opts ...gax.CallOption) error { +func (c *gRPCClient) DeleteScanConfig(ctx context.Context, req *websecurityscannerpb.DeleteScanConfigRequest, opts ...gax.CallOption) error { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -293,7 +416,7 @@ func (c *Client) DeleteScanConfig(ctx context.Context, req *websecurityscannerpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteScanConfig[0:len(c.CallOptions.DeleteScanConfig):len(c.CallOptions.DeleteScanConfig)], opts...) + opts = append((*c.CallOptions).DeleteScanConfig[0:len((*c.CallOptions).DeleteScanConfig):len((*c.CallOptions).DeleteScanConfig)], opts...) err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error _, err = c.client.DeleteScanConfig(ctx, req, settings.GRPC...) @@ -302,8 +425,7 @@ func (c *Client) DeleteScanConfig(ctx context.Context, req *websecurityscannerpb return err } -// GetScanConfig gets a ScanConfig. -func (c *Client) GetScanConfig(ctx context.Context, req *websecurityscannerpb.GetScanConfigRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanConfig, error) { +func (c *gRPCClient) GetScanConfig(ctx context.Context, req *websecurityscannerpb.GetScanConfigRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -311,7 +433,7 @@ func (c *Client) GetScanConfig(ctx context.Context, req *websecurityscannerpb.Ge } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetScanConfig[0:len(c.CallOptions.GetScanConfig):len(c.CallOptions.GetScanConfig)], opts...) + opts = append((*c.CallOptions).GetScanConfig[0:len((*c.CallOptions).GetScanConfig):len((*c.CallOptions).GetScanConfig)], opts...) var resp *websecurityscannerpb.ScanConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -324,11 +446,10 @@ func (c *Client) GetScanConfig(ctx context.Context, req *websecurityscannerpb.Ge return resp, nil } -// ListScanConfigs lists ScanConfigs under a given project. -func (c *Client) ListScanConfigs(ctx context.Context, req *websecurityscannerpb.ListScanConfigsRequest, opts ...gax.CallOption) *ScanConfigIterator { +func (c *gRPCClient) ListScanConfigs(ctx context.Context, req *websecurityscannerpb.ListScanConfigsRequest, opts ...gax.CallOption) *ScanConfigIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListScanConfigs[0:len(c.CallOptions.ListScanConfigs):len(c.CallOptions.ListScanConfigs)], opts...) + opts = append((*c.CallOptions).ListScanConfigs[0:len((*c.CallOptions).ListScanConfigs):len((*c.CallOptions).ListScanConfigs)], opts...) it := &ScanConfigIterator{} req = proto.Clone(req).(*websecurityscannerpb.ListScanConfigsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*websecurityscannerpb.ScanConfig, string, error) { @@ -365,8 +486,7 @@ func (c *Client) ListScanConfigs(ctx context.Context, req *websecurityscannerpb. return it } -// UpdateScanConfig updates a ScanConfig. This method support partial update of a ScanConfig. -func (c *Client) UpdateScanConfig(ctx context.Context, req *websecurityscannerpb.UpdateScanConfigRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanConfig, error) { +func (c *gRPCClient) UpdateScanConfig(ctx context.Context, req *websecurityscannerpb.UpdateScanConfigRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanConfig, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -374,7 +494,7 @@ func (c *Client) UpdateScanConfig(ctx context.Context, req *websecurityscannerpb } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "scan_config.name", url.QueryEscape(req.GetScanConfig().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateScanConfig[0:len(c.CallOptions.UpdateScanConfig):len(c.CallOptions.UpdateScanConfig)], opts...) + opts = append((*c.CallOptions).UpdateScanConfig[0:len((*c.CallOptions).UpdateScanConfig):len((*c.CallOptions).UpdateScanConfig)], opts...) var resp *websecurityscannerpb.ScanConfig err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -387,8 +507,7 @@ func (c *Client) UpdateScanConfig(ctx context.Context, req *websecurityscannerpb return resp, nil } -// StartScanRun start a ScanRun according to the given ScanConfig. -func (c *Client) StartScanRun(ctx context.Context, req *websecurityscannerpb.StartScanRunRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanRun, error) { +func (c *gRPCClient) StartScanRun(ctx context.Context, req *websecurityscannerpb.StartScanRunRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanRun, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -396,7 +515,7 @@ func (c *Client) StartScanRun(ctx context.Context, req *websecurityscannerpb.Sta } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.StartScanRun[0:len(c.CallOptions.StartScanRun):len(c.CallOptions.StartScanRun)], opts...) + opts = append((*c.CallOptions).StartScanRun[0:len((*c.CallOptions).StartScanRun):len((*c.CallOptions).StartScanRun)], opts...) var resp *websecurityscannerpb.ScanRun err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -409,8 +528,7 @@ func (c *Client) StartScanRun(ctx context.Context, req *websecurityscannerpb.Sta return resp, nil } -// GetScanRun gets a ScanRun. -func (c *Client) GetScanRun(ctx context.Context, req *websecurityscannerpb.GetScanRunRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanRun, error) { +func (c *gRPCClient) GetScanRun(ctx context.Context, req *websecurityscannerpb.GetScanRunRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanRun, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -418,7 +536,7 @@ func (c *Client) GetScanRun(ctx context.Context, req *websecurityscannerpb.GetSc } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetScanRun[0:len(c.CallOptions.GetScanRun):len(c.CallOptions.GetScanRun)], opts...) + opts = append((*c.CallOptions).GetScanRun[0:len((*c.CallOptions).GetScanRun):len((*c.CallOptions).GetScanRun)], opts...) var resp *websecurityscannerpb.ScanRun err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -431,12 +549,10 @@ func (c *Client) GetScanRun(ctx context.Context, req *websecurityscannerpb.GetSc return resp, nil } -// ListScanRuns lists ScanRuns under a given ScanConfig, in descending order of ScanRun -// stop time. -func (c *Client) ListScanRuns(ctx context.Context, req *websecurityscannerpb.ListScanRunsRequest, opts ...gax.CallOption) *ScanRunIterator { +func (c *gRPCClient) ListScanRuns(ctx context.Context, req *websecurityscannerpb.ListScanRunsRequest, opts ...gax.CallOption) *ScanRunIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListScanRuns[0:len(c.CallOptions.ListScanRuns):len(c.CallOptions.ListScanRuns)], opts...) + opts = append((*c.CallOptions).ListScanRuns[0:len((*c.CallOptions).ListScanRuns):len((*c.CallOptions).ListScanRuns)], opts...) it := &ScanRunIterator{} req = proto.Clone(req).(*websecurityscannerpb.ListScanRunsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*websecurityscannerpb.ScanRun, string, error) { @@ -473,8 +589,7 @@ func (c *Client) ListScanRuns(ctx context.Context, req *websecurityscannerpb.Lis return it } -// StopScanRun stops a ScanRun. The stopped ScanRun is returned. -func (c *Client) StopScanRun(ctx context.Context, req *websecurityscannerpb.StopScanRunRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanRun, error) { +func (c *gRPCClient) StopScanRun(ctx context.Context, req *websecurityscannerpb.StopScanRunRequest, opts ...gax.CallOption) (*websecurityscannerpb.ScanRun, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -482,7 +597,7 @@ func (c *Client) StopScanRun(ctx context.Context, req *websecurityscannerpb.Stop } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.StopScanRun[0:len(c.CallOptions.StopScanRun):len(c.CallOptions.StopScanRun)], opts...) + opts = append((*c.CallOptions).StopScanRun[0:len((*c.CallOptions).StopScanRun):len((*c.CallOptions).StopScanRun)], opts...) var resp *websecurityscannerpb.ScanRun err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -495,11 +610,10 @@ func (c *Client) StopScanRun(ctx context.Context, req *websecurityscannerpb.Stop return resp, nil } -// ListCrawledUrls list CrawledUrls under a given ScanRun. -func (c *Client) ListCrawledUrls(ctx context.Context, req *websecurityscannerpb.ListCrawledUrlsRequest, opts ...gax.CallOption) *CrawledUrlIterator { +func (c *gRPCClient) ListCrawledUrls(ctx context.Context, req *websecurityscannerpb.ListCrawledUrlsRequest, opts ...gax.CallOption) *CrawledUrlIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListCrawledUrls[0:len(c.CallOptions.ListCrawledUrls):len(c.CallOptions.ListCrawledUrls)], opts...) + opts = append((*c.CallOptions).ListCrawledUrls[0:len((*c.CallOptions).ListCrawledUrls):len((*c.CallOptions).ListCrawledUrls)], opts...) it := &CrawledUrlIterator{} req = proto.Clone(req).(*websecurityscannerpb.ListCrawledUrlsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*websecurityscannerpb.CrawledUrl, string, error) { @@ -536,8 +650,7 @@ func (c *Client) ListCrawledUrls(ctx context.Context, req *websecurityscannerpb. return it } -// GetFinding gets a Finding. -func (c *Client) GetFinding(ctx context.Context, req *websecurityscannerpb.GetFindingRequest, opts ...gax.CallOption) (*websecurityscannerpb.Finding, error) { +func (c *gRPCClient) GetFinding(ctx context.Context, req *websecurityscannerpb.GetFindingRequest, opts ...gax.CallOption) (*websecurityscannerpb.Finding, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -545,7 +658,7 @@ func (c *Client) GetFinding(ctx context.Context, req *websecurityscannerpb.GetFi } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetFinding[0:len(c.CallOptions.GetFinding):len(c.CallOptions.GetFinding)], opts...) + opts = append((*c.CallOptions).GetFinding[0:len((*c.CallOptions).GetFinding):len((*c.CallOptions).GetFinding)], opts...) var resp *websecurityscannerpb.Finding err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -558,11 +671,10 @@ func (c *Client) GetFinding(ctx context.Context, req *websecurityscannerpb.GetFi return resp, nil } -// ListFindings list Findings under a given ScanRun. -func (c *Client) ListFindings(ctx context.Context, req *websecurityscannerpb.ListFindingsRequest, opts ...gax.CallOption) *FindingIterator { +func (c *gRPCClient) ListFindings(ctx context.Context, req *websecurityscannerpb.ListFindingsRequest, opts ...gax.CallOption) *FindingIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListFindings[0:len(c.CallOptions.ListFindings):len(c.CallOptions.ListFindings)], opts...) + opts = append((*c.CallOptions).ListFindings[0:len((*c.CallOptions).ListFindings):len((*c.CallOptions).ListFindings)], opts...) it := &FindingIterator{} req = proto.Clone(req).(*websecurityscannerpb.ListFindingsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*websecurityscannerpb.Finding, string, error) { @@ -599,8 +711,7 @@ func (c *Client) ListFindings(ctx context.Context, req *websecurityscannerpb.Lis return it } -// ListFindingTypeStats list all FindingTypeStats under a given ScanRun. -func (c *Client) ListFindingTypeStats(ctx context.Context, req *websecurityscannerpb.ListFindingTypeStatsRequest, opts ...gax.CallOption) (*websecurityscannerpb.ListFindingTypeStatsResponse, error) { +func (c *gRPCClient) ListFindingTypeStats(ctx context.Context, req *websecurityscannerpb.ListFindingTypeStatsRequest, opts ...gax.CallOption) (*websecurityscannerpb.ListFindingTypeStatsResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() @@ -608,7 +719,7 @@ func (c *Client) ListFindingTypeStats(ctx context.Context, req *websecurityscann } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListFindingTypeStats[0:len(c.CallOptions.ListFindingTypeStats):len(c.CallOptions.ListFindingTypeStats)], opts...) + opts = append((*c.CallOptions).ListFindingTypeStats[0:len((*c.CallOptions).ListFindingTypeStats):len((*c.CallOptions).ListFindingTypeStats)], opts...) var resp *websecurityscannerpb.ListFindingTypeStatsResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/websecurityscanner/apiv1/web_security_scanner_client_example_test.go b/websecurityscanner/apiv1/web_security_scanner_client_example_test.go index 7abd93cc013f..164085b78e95 100644 --- a/websecurityscanner/apiv1/web_security_scanner_client_example_test.go +++ b/websecurityscanner/apiv1/web_security_scanner_client_example_test.go @@ -30,18 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_CreateScanConfig() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.CreateScanConfigRequest{ // TODO: Fill request struct fields. @@ -60,6 +61,7 @@ func ExampleClient_DeleteScanConfig() { if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.DeleteScanConfigRequest{ // TODO: Fill request struct fields. @@ -71,13 +73,12 @@ func ExampleClient_DeleteScanConfig() { } func ExampleClient_GetScanConfig() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.GetScanConfigRequest{ // TODO: Fill request struct fields. @@ -91,14 +92,12 @@ func ExampleClient_GetScanConfig() { } func ExampleClient_ListScanConfigs() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.ListScanConfigsRequest{ // TODO: Fill request struct fields. @@ -118,13 +117,12 @@ func ExampleClient_ListScanConfigs() { } func ExampleClient_UpdateScanConfig() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.UpdateScanConfigRequest{ // TODO: Fill request struct fields. @@ -138,13 +136,12 @@ func ExampleClient_UpdateScanConfig() { } func ExampleClient_StartScanRun() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.StartScanRunRequest{ // TODO: Fill request struct fields. @@ -158,13 +155,12 @@ func ExampleClient_StartScanRun() { } func ExampleClient_GetScanRun() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.GetScanRunRequest{ // TODO: Fill request struct fields. @@ -178,14 +174,12 @@ func ExampleClient_GetScanRun() { } func ExampleClient_ListScanRuns() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.ListScanRunsRequest{ // TODO: Fill request struct fields. @@ -205,13 +199,12 @@ func ExampleClient_ListScanRuns() { } func ExampleClient_StopScanRun() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.StopScanRunRequest{ // TODO: Fill request struct fields. @@ -225,14 +218,12 @@ func ExampleClient_StopScanRun() { } func ExampleClient_ListCrawledUrls() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.ListCrawledUrlsRequest{ // TODO: Fill request struct fields. @@ -252,13 +243,12 @@ func ExampleClient_ListCrawledUrls() { } func ExampleClient_GetFinding() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.GetFindingRequest{ // TODO: Fill request struct fields. @@ -272,14 +262,12 @@ func ExampleClient_GetFinding() { } func ExampleClient_ListFindings() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.ListFindingsRequest{ // TODO: Fill request struct fields. @@ -299,13 +287,12 @@ func ExampleClient_ListFindings() { } func ExampleClient_ListFindingTypeStats() { - // import websecurityscannerpb "google.golang.org/genproto/googleapis/cloud/websecurityscanner/v1" - ctx := context.Background() c, err := websecurityscanner.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &websecurityscannerpb.ListFindingTypeStatsRequest{ // TODO: Fill request struct fields. diff --git a/workflows/apiv1beta/doc.go b/workflows/apiv1beta/doc.go index 4ed90f897991..b6bd586da321 100644 --- a/workflows/apiv1beta/doc.go +++ b/workflows/apiv1beta/doc.go @@ -17,6 +17,8 @@ // Package workflows is an auto-generated package for the // Workflows API. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -26,7 +28,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package workflows // import "cloud.google.com/go/workflows/apiv1beta" import ( @@ -46,7 +48,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/workflows/apiv1beta/workflows_client.go b/workflows/apiv1beta/workflows_client.go index 7c4ba5512388..58ffacd69468 100644 --- a/workflows/apiv1beta/workflows_client.go +++ b/workflows/apiv1beta/workflows_client.go @@ -48,7 +48,7 @@ type CallOptions struct { UpdateWorkflow []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("workflows.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("workflows.mtls.googleapis.com:443"), @@ -70,39 +70,147 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Workflows API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListWorkflows(context.Context, *workflowspb.ListWorkflowsRequest, ...gax.CallOption) *WorkflowIterator + GetWorkflow(context.Context, *workflowspb.GetWorkflowRequest, ...gax.CallOption) (*workflowspb.Workflow, error) + CreateWorkflow(context.Context, *workflowspb.CreateWorkflowRequest, ...gax.CallOption) (*CreateWorkflowOperation, error) + CreateWorkflowOperation(name string) *CreateWorkflowOperation + DeleteWorkflow(context.Context, *workflowspb.DeleteWorkflowRequest, ...gax.CallOption) (*DeleteWorkflowOperation, error) + DeleteWorkflowOperation(name string) *DeleteWorkflowOperation + UpdateWorkflow(context.Context, *workflowspb.UpdateWorkflowRequest, ...gax.CallOption) (*UpdateWorkflowOperation, error) + UpdateWorkflowOperation(name string) *UpdateWorkflowOperation +} + // Client is a client for interacting with Workflows API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Workflows is used to deploy and execute workflow programs. +// Workflows makes sure the program executes reliably, despite hardware and +// networking interruptions. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions + + // LROClient is used internally to handle long-running operations. + // It is exposed so that its CallOptions can be modified if required. + // Users should not Close this client. + LROClient *lroauto.OperationsClient +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListWorkflows lists Workflows in a given project and location. +// The default order is not specified. +func (c *Client) ListWorkflows(ctx context.Context, req *workflowspb.ListWorkflowsRequest, opts ...gax.CallOption) *WorkflowIterator { + return c.internalClient.ListWorkflows(ctx, req, opts...) +} + +// GetWorkflow gets details of a single Workflow. +func (c *Client) GetWorkflow(ctx context.Context, req *workflowspb.GetWorkflowRequest, opts ...gax.CallOption) (*workflowspb.Workflow, error) { + return c.internalClient.GetWorkflow(ctx, req, opts...) +} + +// CreateWorkflow creates a new workflow. If a workflow with the specified name already +// exists in the specified project and location, the long running operation +// will return ALREADY_EXISTS error. +func (c *Client) CreateWorkflow(ctx context.Context, req *workflowspb.CreateWorkflowRequest, opts ...gax.CallOption) (*CreateWorkflowOperation, error) { + return c.internalClient.CreateWorkflow(ctx, req, opts...) +} + +// CreateWorkflowOperation returns a new CreateWorkflowOperation from a given name. +// The name must be that of a previously created CreateWorkflowOperation, possibly from a different process. +func (c *Client) CreateWorkflowOperation(name string) *CreateWorkflowOperation { + return c.internalClient.CreateWorkflowOperation(name) +} + +// DeleteWorkflow deletes a workflow with the specified name. +// This method also cancels and deletes all running executions of the +// workflow. +func (c *Client) DeleteWorkflow(ctx context.Context, req *workflowspb.DeleteWorkflowRequest, opts ...gax.CallOption) (*DeleteWorkflowOperation, error) { + return c.internalClient.DeleteWorkflow(ctx, req, opts...) +} + +// DeleteWorkflowOperation returns a new DeleteWorkflowOperation from a given name. +// The name must be that of a previously created DeleteWorkflowOperation, possibly from a different process. +func (c *Client) DeleteWorkflowOperation(name string) *DeleteWorkflowOperation { + return c.internalClient.DeleteWorkflowOperation(name) +} + +// UpdateWorkflow updates an existing workflow. +// Running this method has no impact on already running executions of the +// workflow. A new revision of the workflow may be created as a result of a +// successful update operation. In that case, such revision will be used +// in new workflow executions. +func (c *Client) UpdateWorkflow(ctx context.Context, req *workflowspb.UpdateWorkflowRequest, opts ...gax.CallOption) (*UpdateWorkflowOperation, error) { + return c.internalClient.UpdateWorkflow(ctx, req, opts...) +} + +// UpdateWorkflowOperation returns a new UpdateWorkflowOperation from a given name. +// The name must be that of a previously created UpdateWorkflowOperation, possibly from a different process. +func (c *Client) UpdateWorkflowOperation(name string) *UpdateWorkflowOperation { + return c.internalClient.UpdateWorkflowOperation(name) +} + +// gRPCClient is a client for interacting with Workflows API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client workflowspb.WorkflowsClient - // LROClient is used internally to handle longrunning operations. + // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. - LROClient *lroauto.OperationsClient - - // The call options for this service. - CallOptions *CallOptions + LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new workflows client. +// NewClient creates a new workflows client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Workflows is used to deploy and execute workflow programs. // Workflows makes sure the program executes reliably, despite hardware and // networking interruptions. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -120,16 +228,19 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: workflowspb.NewWorkflowsClient(connPool), + client: workflowspb.NewWorkflowsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) + client.internalClient = c + + client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. @@ -139,37 +250,36 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error // TODO: investigate error conditions. return nil, err } - return c, nil + c.LROClient = &client.LROClient + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListWorkflows lists Workflows in a given project and location. -// The default order is not specified. -func (c *Client) ListWorkflows(ctx context.Context, req *workflowspb.ListWorkflowsRequest, opts ...gax.CallOption) *WorkflowIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ListWorkflows(ctx context.Context, req *workflowspb.ListWorkflowsRequest, opts ...gax.CallOption) *WorkflowIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListWorkflows[0:len(c.CallOptions.ListWorkflows):len(c.CallOptions.ListWorkflows)], opts...) + opts = append((*c.CallOptions).ListWorkflows[0:len((*c.CallOptions).ListWorkflows):len((*c.CallOptions).ListWorkflows)], opts...) it := &WorkflowIterator{} req = proto.Clone(req).(*workflowspb.ListWorkflowsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*workflowspb.Workflow, string, error) { @@ -206,11 +316,10 @@ func (c *Client) ListWorkflows(ctx context.Context, req *workflowspb.ListWorkflo return it } -// GetWorkflow gets details of a single Workflow. -func (c *Client) GetWorkflow(ctx context.Context, req *workflowspb.GetWorkflowRequest, opts ...gax.CallOption) (*workflowspb.Workflow, error) { +func (c *gRPCClient) GetWorkflow(ctx context.Context, req *workflowspb.GetWorkflowRequest, opts ...gax.CallOption) (*workflowspb.Workflow, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetWorkflow[0:len(c.CallOptions.GetWorkflow):len(c.CallOptions.GetWorkflow)], opts...) + opts = append((*c.CallOptions).GetWorkflow[0:len((*c.CallOptions).GetWorkflow):len((*c.CallOptions).GetWorkflow)], opts...) var resp *workflowspb.Workflow err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -223,13 +332,10 @@ func (c *Client) GetWorkflow(ctx context.Context, req *workflowspb.GetWorkflowRe return resp, nil } -// CreateWorkflow creates a new workflow. If a workflow with the specified name already -// exists in the specified project and location, the long running operation -// will return ALREADY_EXISTS error. -func (c *Client) CreateWorkflow(ctx context.Context, req *workflowspb.CreateWorkflowRequest, opts ...gax.CallOption) (*CreateWorkflowOperation, error) { +func (c *gRPCClient) CreateWorkflow(ctx context.Context, req *workflowspb.CreateWorkflowRequest, opts ...gax.CallOption) (*CreateWorkflowOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateWorkflow[0:len(c.CallOptions.CreateWorkflow):len(c.CallOptions.CreateWorkflow)], opts...) + opts = append((*c.CallOptions).CreateWorkflow[0:len((*c.CallOptions).CreateWorkflow):len((*c.CallOptions).CreateWorkflow)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -240,17 +346,14 @@ func (c *Client) CreateWorkflow(ctx context.Context, req *workflowspb.CreateWork return nil, err } return &CreateWorkflowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// DeleteWorkflow deletes a workflow with the specified name. -// This method also cancels and deletes all running executions of the -// workflow. -func (c *Client) DeleteWorkflow(ctx context.Context, req *workflowspb.DeleteWorkflowRequest, opts ...gax.CallOption) (*DeleteWorkflowOperation, error) { +func (c *gRPCClient) DeleteWorkflow(ctx context.Context, req *workflowspb.DeleteWorkflowRequest, opts ...gax.CallOption) (*DeleteWorkflowOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteWorkflow[0:len(c.CallOptions.DeleteWorkflow):len(c.CallOptions.DeleteWorkflow)], opts...) + opts = append((*c.CallOptions).DeleteWorkflow[0:len((*c.CallOptions).DeleteWorkflow):len((*c.CallOptions).DeleteWorkflow)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -261,19 +364,14 @@ func (c *Client) DeleteWorkflow(ctx context.Context, req *workflowspb.DeleteWork return nil, err } return &DeleteWorkflowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } -// UpdateWorkflow updates an existing workflow. -// Running this method has no impact on already running executions of the -// workflow. A new revision of the workflow may be created as a result of a -// successful update operation. In that case, such revision will be used -// in new workflow executions. -func (c *Client) UpdateWorkflow(ctx context.Context, req *workflowspb.UpdateWorkflowRequest, opts ...gax.CallOption) (*UpdateWorkflowOperation, error) { +func (c *gRPCClient) UpdateWorkflow(ctx context.Context, req *workflowspb.UpdateWorkflowRequest, opts ...gax.CallOption) (*UpdateWorkflowOperation, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "workflow.name", url.QueryEscape(req.GetWorkflow().GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateWorkflow[0:len(c.CallOptions.UpdateWorkflow):len(c.CallOptions.UpdateWorkflow)], opts...) + opts = append((*c.CallOptions).UpdateWorkflow[0:len((*c.CallOptions).UpdateWorkflow):len((*c.CallOptions).UpdateWorkflow)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -284,7 +382,7 @@ func (c *Client) UpdateWorkflow(ctx context.Context, req *workflowspb.UpdateWork return nil, err } return &UpdateWorkflowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, resp), + lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } @@ -295,9 +393,9 @@ type CreateWorkflowOperation struct { // CreateWorkflowOperation returns a new CreateWorkflowOperation from a given name. // The name must be that of a previously created CreateWorkflowOperation, possibly from a different process. -func (c *Client) CreateWorkflowOperation(name string) *CreateWorkflowOperation { +func (c *gRPCClient) CreateWorkflowOperation(name string) *CreateWorkflowOperation { return &CreateWorkflowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -364,9 +462,9 @@ type DeleteWorkflowOperation struct { // DeleteWorkflowOperation returns a new DeleteWorkflowOperation from a given name. // The name must be that of a previously created DeleteWorkflowOperation, possibly from a different process. -func (c *Client) DeleteWorkflowOperation(name string) *DeleteWorkflowOperation { +func (c *gRPCClient) DeleteWorkflowOperation(name string) *DeleteWorkflowOperation { return &DeleteWorkflowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } @@ -422,9 +520,9 @@ type UpdateWorkflowOperation struct { // UpdateWorkflowOperation returns a new UpdateWorkflowOperation from a given name. // The name must be that of a previously created UpdateWorkflowOperation, possibly from a different process. -func (c *Client) UpdateWorkflowOperation(name string) *UpdateWorkflowOperation { +func (c *gRPCClient) UpdateWorkflowOperation(name string) *UpdateWorkflowOperation { return &UpdateWorkflowOperation{ - lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}), + lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } diff --git a/workflows/apiv1beta/workflows_client_example_test.go b/workflows/apiv1beta/workflows_client_example_test.go index d73afa3c43f6..2f75fffa93e2 100644 --- a/workflows/apiv1beta/workflows_client_example_test.go +++ b/workflows/apiv1beta/workflows_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ListWorkflows() { - // import workflowspb "google.golang.org/genproto/googleapis/cloud/workflows/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := workflows.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &workflowspb.ListWorkflowsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleClient_ListWorkflows() { } func ExampleClient_GetWorkflow() { - // import workflowspb "google.golang.org/genproto/googleapis/cloud/workflows/v1beta" - ctx := context.Background() c, err := workflows.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &workflowspb.GetWorkflowRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleClient_GetWorkflow() { } func ExampleClient_CreateWorkflow() { - // import workflowspb "google.golang.org/genproto/googleapis/cloud/workflows/v1beta" - ctx := context.Background() c, err := workflows.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &workflowspb.CreateWorkflowRequest{ // TODO: Fill request struct fields. @@ -107,13 +105,12 @@ func ExampleClient_CreateWorkflow() { } func ExampleClient_DeleteWorkflow() { - // import workflowspb "google.golang.org/genproto/googleapis/cloud/workflows/v1beta" - ctx := context.Background() c, err := workflows.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &workflowspb.DeleteWorkflowRequest{ // TODO: Fill request struct fields. @@ -130,13 +127,12 @@ func ExampleClient_DeleteWorkflow() { } func ExampleClient_UpdateWorkflow() { - // import workflowspb "google.golang.org/genproto/googleapis/cloud/workflows/v1beta" - ctx := context.Background() c, err := workflows.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &workflowspb.UpdateWorkflowRequest{ // TODO: Fill request struct fields. diff --git a/workflows/executions/apiv1beta/doc.go b/workflows/executions/apiv1beta/doc.go index 87fe7418a63e..f0173bce015c 100644 --- a/workflows/executions/apiv1beta/doc.go +++ b/workflows/executions/apiv1beta/doc.go @@ -19,6 +19,8 @@ // // Manages user-provided workflows. // +// NOTE: This package is in beta. It is not stable, and may be subject to changes. +// // Use of Context // // The ctx passed to NewClient is used for authentication requests and @@ -28,7 +30,7 @@ // To close the open connection, use the Close() method. // // For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. +// please visit https://pkg.go.dev/cloud.google.com/go. package executions // import "cloud.google.com/go/workflows/executions/apiv1beta" import ( @@ -48,7 +50,7 @@ import ( type clientHookParams struct{} type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) -const versionClient = "20210518" +const versionClient = "20210520" func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { out, _ := metadata.FromOutgoingContext(ctx) diff --git a/workflows/executions/apiv1beta/executions_client.go b/workflows/executions/apiv1beta/executions_client.go index 427b4af1caab..5e72fd4142db 100644 --- a/workflows/executions/apiv1beta/executions_client.go +++ b/workflows/executions/apiv1beta/executions_client.go @@ -43,7 +43,7 @@ type CallOptions struct { CancelExecution []gax.CallOption } -func defaultClientOptions() []option.ClientOption { +func defaultGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("workflowexecutions.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("workflowexecutions.mtls.googleapis.com:443"), @@ -64,33 +64,102 @@ func defaultCallOptions() *CallOptions { } } +// internalClient is an interface that defines the methods availaible from Workflow Executions API. +type internalClient interface { + Close() error + setGoogleClientInfo(...string) + Connection() *grpc.ClientConn + ListExecutions(context.Context, *executionspb.ListExecutionsRequest, ...gax.CallOption) *ExecutionIterator + CreateExecution(context.Context, *executionspb.CreateExecutionRequest, ...gax.CallOption) (*executionspb.Execution, error) + GetExecution(context.Context, *executionspb.GetExecutionRequest, ...gax.CallOption) (*executionspb.Execution, error) + CancelExecution(context.Context, *executionspb.CancelExecutionRequest, ...gax.CallOption) (*executionspb.Execution, error) +} + // Client is a client for interacting with Workflow Executions API. -// // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +// +// Executions is used to start and manage running instances of +// Workflows called executions. type Client struct { + // The internal transport-dependent client. + internalClient internalClient + + // The call options for this service. + CallOptions *CallOptions +} + +// Wrapper methods routed to the internal client. + +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *Client) Close() error { + return c.internalClient.Close() +} + +// setGoogleClientInfo sets the name and version of the application in +// the `x-goog-api-client` header passed on each request. Intended for +// use by Google-written clients. +func (c *Client) setGoogleClientInfo(...string) { + c.internalClient.setGoogleClientInfo() +} + +// Connection returns a connection to the API service. +// +// Deprecated. +func (c *Client) Connection() *grpc.ClientConn { + return c.internalClient.Connection() +} + +// ListExecutions returns a list of executions which belong to the workflow with +// the given name. The method returns executions of all workflow +// revisions. Returned executions are ordered by their start time (newest +// first). +func (c *Client) ListExecutions(ctx context.Context, req *executionspb.ListExecutionsRequest, opts ...gax.CallOption) *ExecutionIterator { + return c.internalClient.ListExecutions(ctx, req, opts...) +} + +// CreateExecution creates a new execution using the latest revision of the given workflow. +func (c *Client) CreateExecution(ctx context.Context, req *executionspb.CreateExecutionRequest, opts ...gax.CallOption) (*executionspb.Execution, error) { + return c.internalClient.CreateExecution(ctx, req, opts...) +} + +// GetExecution returns an execution of the given name. +func (c *Client) GetExecution(ctx context.Context, req *executionspb.GetExecutionRequest, opts ...gax.CallOption) (*executionspb.Execution, error) { + return c.internalClient.GetExecution(ctx, req, opts...) +} + +// CancelExecution cancels an execution of the given name. +func (c *Client) CancelExecution(ctx context.Context, req *executionspb.CancelExecutionRequest, opts ...gax.CallOption) (*executionspb.Execution, error) { + return c.internalClient.CancelExecution(ctx, req, opts...) +} + +// gRPCClient is a client for interacting with Workflow Executions API over gRPC transport. +// +// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. +type gRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool + // Points back to the CallOptions field of the containing Client + CallOptions **CallOptions + // The gRPC API client. client executionspb.ExecutionsClient - // The call options for this service. - CallOptions *CallOptions - // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } -// NewClient creates a new executions client. +// NewClient creates a new executions client based on gRPC. +// The returned client must be Closed when it is done being used to clean up its underlying connections. // // Executions is used to start and manage running instances of // Workflows called executions. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - + clientOpts := defaultGRPCClientOptions() if newClientHook != nil { hookOpts, err := newClientHook(ctx, clientHookParams{}) if err != nil { @@ -108,48 +177,47 @@ func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error if err != nil { return nil, err } - c := &Client{ + client := Client{CallOptions: defaultCallOptions()} + + c := &gRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: executionspb.NewExecutionsClient(connPool), + client: executionspb.NewExecutionsClient(connPool), + CallOptions: &client.CallOptions, } c.setGoogleClientInfo() - return c, nil + client.internalClient = c + + return &client, nil } // Connection returns a connection to the API service. // // Deprecated. -func (c *Client) Connection() *grpc.ClientConn { +func (c *gRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { +func (c *gRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } -// ListExecutions returns a list of executions which belong to the workflow with -// the given name. The method returns executions of all workflow -// revisions. Returned executions are ordered by their start time (newest -// first). -func (c *Client) ListExecutions(ctx context.Context, req *executionspb.ListExecutionsRequest, opts ...gax.CallOption) *ExecutionIterator { +// Close closes the connection to the API service. The user should invoke this when +// the client is no longer required. +func (c *gRPCClient) Close() error { + return c.connPool.Close() +} + +func (c *gRPCClient) ListExecutions(ctx context.Context, req *executionspb.ListExecutionsRequest, opts ...gax.CallOption) *ExecutionIterator { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListExecutions[0:len(c.CallOptions.ListExecutions):len(c.CallOptions.ListExecutions)], opts...) + opts = append((*c.CallOptions).ListExecutions[0:len((*c.CallOptions).ListExecutions):len((*c.CallOptions).ListExecutions)], opts...) it := &ExecutionIterator{} req = proto.Clone(req).(*executionspb.ListExecutionsRequest) it.InternalFetch = func(pageSize int, pageToken string) ([]*executionspb.Execution, string, error) { @@ -186,11 +254,10 @@ func (c *Client) ListExecutions(ctx context.Context, req *executionspb.ListExecu return it } -// CreateExecution creates a new execution using the latest revision of the given workflow. -func (c *Client) CreateExecution(ctx context.Context, req *executionspb.CreateExecutionRequest, opts ...gax.CallOption) (*executionspb.Execution, error) { +func (c *gRPCClient) CreateExecution(ctx context.Context, req *executionspb.CreateExecutionRequest, opts ...gax.CallOption) (*executionspb.Execution, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateExecution[0:len(c.CallOptions.CreateExecution):len(c.CallOptions.CreateExecution)], opts...) + opts = append((*c.CallOptions).CreateExecution[0:len((*c.CallOptions).CreateExecution):len((*c.CallOptions).CreateExecution)], opts...) var resp *executionspb.Execution err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -203,11 +270,10 @@ func (c *Client) CreateExecution(ctx context.Context, req *executionspb.CreateEx return resp, nil } -// GetExecution returns an execution of the given name. -func (c *Client) GetExecution(ctx context.Context, req *executionspb.GetExecutionRequest, opts ...gax.CallOption) (*executionspb.Execution, error) { +func (c *gRPCClient) GetExecution(ctx context.Context, req *executionspb.GetExecutionRequest, opts ...gax.CallOption) (*executionspb.Execution, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetExecution[0:len(c.CallOptions.GetExecution):len(c.CallOptions.GetExecution)], opts...) + opts = append((*c.CallOptions).GetExecution[0:len((*c.CallOptions).GetExecution):len((*c.CallOptions).GetExecution)], opts...) var resp *executionspb.Execution err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error @@ -220,11 +286,10 @@ func (c *Client) GetExecution(ctx context.Context, req *executionspb.GetExecutio return resp, nil } -// CancelExecution cancels an execution of the given name. -func (c *Client) CancelExecution(ctx context.Context, req *executionspb.CancelExecutionRequest, opts ...gax.CallOption) (*executionspb.Execution, error) { +func (c *gRPCClient) CancelExecution(ctx context.Context, req *executionspb.CancelExecutionRequest, opts ...gax.CallOption) (*executionspb.Execution, error) { md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CancelExecution[0:len(c.CallOptions.CancelExecution):len(c.CallOptions.CancelExecution)], opts...) + opts = append((*c.CallOptions).CancelExecution[0:len((*c.CallOptions).CancelExecution):len((*c.CallOptions).CancelExecution)], opts...) var resp *executionspb.Execution err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error diff --git a/workflows/executions/apiv1beta/executions_client_example_test.go b/workflows/executions/apiv1beta/executions_client_example_test.go index ee4d2730f8a7..b1465e377645 100644 --- a/workflows/executions/apiv1beta/executions_client_example_test.go +++ b/workflows/executions/apiv1beta/executions_client_example_test.go @@ -30,19 +30,19 @@ func ExampleNewClient() { if err != nil { // TODO: Handle error. } + defer c.Close() + // TODO: Use client. _ = c } func ExampleClient_ListExecutions() { - // import executionspb "google.golang.org/genproto/googleapis/cloud/workflows/executions/v1beta" - // import "google.golang.org/api/iterator" - ctx := context.Background() c, err := executions.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &executionspb.ListExecutionsRequest{ // TODO: Fill request struct fields. @@ -62,13 +62,12 @@ func ExampleClient_ListExecutions() { } func ExampleClient_CreateExecution() { - // import executionspb "google.golang.org/genproto/googleapis/cloud/workflows/executions/v1beta" - ctx := context.Background() c, err := executions.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &executionspb.CreateExecutionRequest{ // TODO: Fill request struct fields. @@ -82,13 +81,12 @@ func ExampleClient_CreateExecution() { } func ExampleClient_GetExecution() { - // import executionspb "google.golang.org/genproto/googleapis/cloud/workflows/executions/v1beta" - ctx := context.Background() c, err := executions.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &executionspb.GetExecutionRequest{ // TODO: Fill request struct fields. @@ -102,13 +100,12 @@ func ExampleClient_GetExecution() { } func ExampleClient_CancelExecution() { - // import executionspb "google.golang.org/genproto/googleapis/cloud/workflows/executions/v1beta" - ctx := context.Background() c, err := executions.NewClient(ctx) if err != nil { // TODO: Handle error. } + defer c.Close() req := &executionspb.CancelExecutionRequest{ // TODO: Fill request struct fields.